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.DbAssetsStockLocked;
import com.xtd.project.assets.domain.DbAssetsStockOut;
import com.xtd.project.assets.mapper.DbAssetsStockLockedMapper;
import com.xtd.project.assets.mapper.DbAssetsStockMapper;
import com.xtd.project.assets.mapper.DbAssetsStockOutMapper;
import com.xtd.project.assets.service.IDbAssetsStockOutService;
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 org.springframework.transaction.annotation.Transactional;

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

/**
 * 资产出库Service业务层处理
 *
 * @author xtd
 * @date 2020-04-16
 */
@Service
public class DbAssetsStockOutServiceImpl implements IDbAssetsStockOutService {
    @Autowired
    private DbAssetsStockOutMapper dbAssetsStockOutMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private IDbTableHisService iDbTableHisService;


    /**
     * 查询资产出库
     *
     * @param aId 资产出库ID
     * @return 资产出库
     */
    @Override
    public DbAssetsStockOut selectDbAssetsStockOutById(Long aId) {
        return dbAssetsStockOutMapper.selectDbAssetsStockOutById(aId);
    }

    /**
     * 查询资产出库列表
     *
     * @param dbAssetsStockOut 资产出库
     * @return 资产出库
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<DbAssetsStockOut> selectDbAssetsStockOutList(DbAssetsStockOut dbAssetsStockOut) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long userId = user.getUserId();
        String appUserId = userId.toString();

        List<DbAssetsStockOut> dbAssetsStockOuts = dbAssetsStockOutMapper.selectDbAssetsStockOutList(dbAssetsStockOut);
        for (DbAssetsStockOut dbAssetsStockOutRe : dbAssetsStockOuts) {
            String instanceId = dbAssetsStockOutRe.getInstanceId();
            if (!StringUtils.isNull(instanceId)) {
                Task task = taskService.createTaskQuery().taskAssignee(appUserId).processInstanceId(instanceId).singleResult();
                if (!StringUtils.isNull(task)) {
                    dbAssetsStockOutRe.setTaskId(task.getId());
                }
            }
        }
        return dbAssetsStockOuts;
    }

    /**
     * 新增资产出库
     *
     * @param dbAssetsStockOut 资产出库
     * @return 结果
     */
    @Override
    public int insertDbAssetsStockOut(DbAssetsStockOut dbAssetsStockOut) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long userId = user.getUserId();
        dbAssetsStockOut.setCreateBy(userId.toString());
        dbAssetsStockOut.setCreateTime(DateUtils.getNowDate());
        return dbAssetsStockOutMapper.insertDbAssetsStockOut(dbAssetsStockOut);
    }

    /**
     * 修改资产出库
     *
     * @param dbAssetsStockOut 资产出库
     * @return 结果
     */
    @Override
    public int updateDbAssetsStockOut(DbAssetsStockOut dbAssetsStockOut) {
        dbAssetsStockOut.setUpdateTime(DateUtils.getNowDate());
        return dbAssetsStockOutMapper.updateDbAssetsStockOut(dbAssetsStockOut);
    }

    /**
     * 批量删除资产出库
     *
     * @param aIds 需要删除的资产出库ID
     * @return 结果
     */
    @Override
    public int deleteDbAssetsStockOutByIds(Long[] aIds) {
        return dbAssetsStockOutMapper.deleteDbAssetsStockOutByIds(aIds);
    }

    /**
     * 删除资产出库信息
     *
     * @param aId 资产出库ID
     * @return 结果
     */
    @Override
    public int deleteDbAssetsStockOutById(Long aId) {
        return dbAssetsStockOutMapper.deleteDbAssetsStockOutById(aId);
    }

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private DbAssetsStockMapper dbAssetsStockMapper;

    @Transactional
    @Override
    public void commit(Long aId, String processId) {
        DbAssetsStockOut dbAssetsStockOut = dbAssetsStockOutMapper.selectDbAssetsStockOutById(aId);
        checkData(dbAssetsStockOut);
        String processInstanceId = commitData(processId, dbAssetsStockOut);
        //更新表单
        updateData(aId, dbAssetsStockOut, processInstanceId);
    }

    @Autowired
    private DbAssetsStockLockedMapper dbAssetsStockLockedMapper;

    private void checkData(DbAssetsStockOut dbAssetsStockOut) {
        Long dbAsStId = dbAssetsStockOut.getDbAsStId();
        Long aLong = dbAssetsStockOut.getaId();
        DbAssetsStockOut parmData = new DbAssetsStockOut();
        parmData.setDbAsStId(dbAsStId);
        List<DbAssetsStockOut> dbAssetsStockOuts = dbAssetsStockOutMapper.selectDbAssetsStockOutList(parmData);
        if (dbAssetsStockOuts.size() > 0) {
            for (DbAssetsStockOut x : dbAssetsStockOuts) {
                Integer state = x.getState();
                if(StringUtils.isNotNull(state)){
                    String string = state.toString();
                    if ( "0".equals(string)||"2".equals(string)) {
                        throw new CustomException("该物资被使用无法提交");
                    }
                }
            }
        }
//        DbAssetsStockLocked dbAssetsStockLocked=new DbAssetsStockLocked();
//        dbAssetsStockLocked.setDbAsStId(dbAsStId);
//        dbAssetsStockLocked.setDbAsStTableId(aLong);
//        dbAssetsStockLocked.setDbAsStTableName("db_assets_stock_out");
//        List<DbAssetsStockLocked> dbAssetsStockLockeds = dbAssetsStockLockedMapper.selectDbAssetsStockLockedList(dbAssetsStockLocked);
//        if(dbAssetsStockLockeds.size()>0){
//            for (DbAssetsStockLocked assetsStockLocked : dbAssetsStockLockeds) {
//                Long dbAsStTableId = assetsStockLocked.getDbAsStTableId();
//                if(aLong.equals(dbAsStTableId)){
//
//                }
//            }
//        }
    }

    private void updateData(Long aId, DbAssetsStockOut dbAssetsStockOut, String processInstanceId) {
        dbAssetsStockOut.setInstanceId(processInstanceId);
        dbAssetsStockOut.setState(0);
        dbAssetsStockOutMapper.updateDbAssetsStockOut(dbAssetsStockOut);
        //插入历史
        iDbTableHisService.insertDbTableHis(processInstanceId, aId, "db_assets_stock_out");
    }

    private String commitData(String processId, DbAssetsStockOut dbAssetsStockOut) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long userId = user.getUserId();
        // 启动流程时设置业务 key
        Map<String, Object> map = new HashMap<>();
        String appUserId = userId.toString();
        map.put("appUserId", appUserId);
        ProcessInstance processInstance = runtimeService
                .startProcessInstanceById(processId, map);
        String processInstanceId = processInstance.getId();
        Task task = taskService.createTaskQuery().taskAssignee(appUserId).processInstanceId(processInstanceId).singleResult();
        String taskId = task.getId();
        map.put("formData", dbAssetsStockOut);
        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);
        return processInstanceId;
    }

    @Override
    public void recommit(DbAssetsStockOut dbAssetsStockOut) {
        checkData(dbAssetsStockOut);
        reCommitData(dbAssetsStockOut);
    }

    private void reCommitData(DbAssetsStockOut dbAssetsStockOut) {
        String taskId = dbAssetsStockOut.getTaskId();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long userId = user.getUserId();
        // 启动流程时设置业务 key
        Map<String, Object> map = new HashMap<>();
        map.put("formData", dbAssetsStockOut);
        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);
        //设置为审核中
        dbAssetsStockOut.setState(0);
        dbAssetsStockOutMapper.updateDbAssetsStockOut(dbAssetsStockOut);
    }
}
