package com.xtd.project.assets.service.impl;

import com.xtd.common.exception.CustomException;
import com.xtd.common.utils.DateUtils;
import com.xtd.common.utils.SecurityUtils;
import com.xtd.common.utils.StringUtils;
import com.xtd.framework.aspectj.lang.annotation.DataScope;
import com.xtd.project.assets.domain.DbAssetsStock;
import com.xtd.project.assets.domain.DbAssetsStockOut;
import com.xtd.project.assets.domain.DbAssetsStockScrap;
import com.xtd.project.assets.mapper.DbAssetsStockMapper;
import com.xtd.project.assets.mapper.DbAssetsStockScrapMapper;
import com.xtd.project.assets.service.IDbAssetsStockScrapService;
import com.xtd.project.assets.service.IDbTableHisService;
import com.xtd.project.system.domain.SysUser;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 资产报废Service业务层处理
 *
 * @author xtd
 * @date 2020-04-17
 */
@Service
public class DbAssetsStockScrapServiceImpl implements IDbAssetsStockScrapService
{
    @Autowired
    private DbAssetsStockScrapMapper dbAssetsStockScrapMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private IDbTableHisService iDbTableHisService;


    /**
     * 查询资产报废
     *
     * @param aId 资产报废ID
     * @return 资产报废
     */
    @Override
    public DbAssetsStockScrap selectDbAssetsStockScrapById(Long aId)
    {
        return dbAssetsStockScrapMapper.selectDbAssetsStockScrapById(aId);
    }

    /**
     * 查询资产报废列表
     *
     * @param dbAssetsStockScrap 资产报废
     * @return 资产报废
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<DbAssetsStockScrap> selectDbAssetsStockScrapList(DbAssetsStockScrap dbAssetsStockScrap)
    {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        String appUserId = userId.toString();
        List<DbAssetsStockScrap> dbAssetsStockScraps = dbAssetsStockScrapMapper.selectDbAssetsStockScrapList(dbAssetsStockScrap);
        for (DbAssetsStockScrap data : dbAssetsStockScraps) {
            String instanceId = data.getInstanceId();
            if (!StringUtils.isNull(instanceId)) {
                Task task = taskService.createTaskQuery().taskAssignee(appUserId).processInstanceId(instanceId).singleResult();
                if (!StringUtils.isNull(task)) {
                    data.setTaskId(task.getId());
                }
            }
        }
        return dbAssetsStockScraps;
    }

    /**
     * 新增资产报废
     *
     * @param dbAssetsStockScrap 资产报废
     * @return 结果
     */
    @Override
    public int insertDbAssetsStockScrap(DbAssetsStockScrap dbAssetsStockScrap)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long userId = user.getUserId();
        dbAssetsStockScrap.setCreateBy(userId.toString());
        dbAssetsStockScrap.setCreateTime(DateUtils.getNowDate());
        return dbAssetsStockScrapMapper.insertDbAssetsStockScrap(dbAssetsStockScrap);
    }

    /**
     * 修改资产报废
     *
     * @param dbAssetsStockScrap 资产报废
     * @return 结果
     */
    @Override
    public int updateDbAssetsStockScrap(DbAssetsStockScrap dbAssetsStockScrap)
    {   SysUser user = SecurityUtils.getLoginUser().getUser();
        Long userId = user.getUserId();
        dbAssetsStockScrap.setUpdateBy(userId.toString());
        dbAssetsStockScrap.setUpdateTime(DateUtils.getNowDate());
        return dbAssetsStockScrapMapper.updateDbAssetsStockScrap(dbAssetsStockScrap);
    }

    /**
     * 批量删除资产报废
     *
     * @param aIds 需要删除的资产报废ID
     * @return 结果
     */
    @Override
    public int deleteDbAssetsStockScrapByIds(Long[] aIds)
    {
        return dbAssetsStockScrapMapper.deleteDbAssetsStockScrapByIds(aIds);
    }

    /**
     * 删除资产报废信息
     *
     * @param aId 资产报废ID
     * @return 结果
     */
    @Override
    public int deleteDbAssetsStockScrapById(Long aId)
    {
        return dbAssetsStockScrapMapper.deleteDbAssetsStockScrapById(aId);
    }
    @Autowired
    private ApplicationContext applicationContext;
    @Override
    public void commit(Long aId, String processId) {
        DbAssetsStockScrap dbAssetsStockScrap = dbAssetsStockScrapMapper.selectDbAssetsStockScrapById(aId);
        checkData(dbAssetsStockScrap);
        //提交数据
        String processInstanceId = commitData(processId, dbAssetsStockScrap);
        //更新本地数据
        updateData(aId, dbAssetsStockScrap, processInstanceId);

    }

    private void updateData(Long aId, DbAssetsStockScrap dbAssetsStockScrap, String processInstanceId) {
        //更新表单
        dbAssetsStockScrap.setInstanceId(processInstanceId);
        //设置为审核中
        dbAssetsStockScrap.setState(0);
        dbAssetsStockScrapMapper.updateDbAssetsStockScrap(dbAssetsStockScrap);
        //插入历史
        iDbTableHisService.insertDbTableHis(processInstanceId, aId, "db_assets_stock_scrap");
    }

    private String commitData(String processId, DbAssetsStockScrap dbAssetsStockScrap) {
        // 启动流程时设置业务 key
        Map<String, Object> map = new HashMap<>();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long userId = user.getUserId();
        String appUserId = userId.toString();
        map.put("appUserId", appUserId);
        map.put("formData", dbAssetsStockScrap);
        map.put("creatUserName", user.getUserName());
        map.put("creatDeptName", user.getDept().getDeptName());
        map.put("creatTime", DateUtils.getNowDate());
        ProcessInstance processInstance = runtimeService
                .startProcessInstanceById(processId, map);
        String processInstanceId = processInstance.getId();
        Task task = taskService.createTaskQuery().taskAssignee(appUserId).processInstanceId(processInstanceId).singleResult();
        String taskId = task.getId();
        //设置签收
        taskService.claim(taskId, userId.toString());
        //完成task
        taskService.complete(taskId, map);
        return processInstanceId;
    }

    @Autowired
    private DbAssetsStockMapper dbAssetsStockMapper;
    private void checkData(DbAssetsStockScrap dbAssetsStockScrap) {
        Long dbAsStId = dbAssetsStockScrap.getDbAsStId();
        Long aLong = dbAssetsStockScrap.getaId();
        DbAssetsStockScrap parmData = new DbAssetsStockScrap();
        parmData.setDbAsStId(dbAsStId);
        List<DbAssetsStockScrap> dbAssetsStockOuts = dbAssetsStockScrapMapper.selectDbAssetsStockScrapList(parmData);
        if (dbAssetsStockOuts.size() > 0) {
            for (DbAssetsStockScrap x : dbAssetsStockOuts) {
                Integer state = x.getState();
                if(StringUtils.isNotNull(state)){
                    String string = state.toString();
                    if ( "0".equals(string)||"2".equals(string)) {
                        throw new CustomException("该物资被使用无法提交");
                    }
                }

            }
        }
    }


    @Override
    public void recommit(DbAssetsStockScrap dbAssetsStockScrap) {
        //检查数据有效性
        checkData(dbAssetsStockScrap);
        //重新提交数据
        recommitData(dbAssetsStockScrap);

    }

    private void recommitData(DbAssetsStockScrap dbAssetsStockScrap) {
        Map<String, Object> map = new HashMap<>();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long userId = user.getUserId();
        String appUserId = userId.toString();
        map.put("appUserId", appUserId);
        String taskId = dbAssetsStockScrap.getTaskId();
        map.put("formData", dbAssetsStockScrap);
        map.put("creatUserName", user.getUserName());
        map.put("creatDeptName", user.getDept().getDeptName());
        map.put("creatTime", DateUtils.getNowDate());
        //设置签收
        taskService.claim(taskId, userId.toString());
        //完成task
        taskService.complete(taskId, map);
        //设置为审核中
        dbAssetsStockScrap.setState(0);
        dbAssetsStockScrapMapper.updateDbAssetsStockScrap(dbAssetsStockScrap);
    }
}
