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

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

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.*;
import com.xtd.project.assets.mapper.DbAssetsStockAllotExMapper;
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.stereotype.Service;
import com.xtd.project.assets.mapper.DbAssetsStockAllotMapper;
import com.xtd.project.assets.service.IDbAssetsStockAllotService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 资产调拨Service业务层处理
 *
 * @author xtd
 * @date 2020-04-20
 */
@Service
public class DbAssetsStockAllotServiceImpl implements IDbAssetsStockAllotService {
    @Autowired
    private DbAssetsStockAllotMapper dbAssetsStockAllotMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private IDbTableHisService iDbTableHisService;


    /**
     * 查询资产调拨
     *
     * @param aId 资产调拨ID
     * @return 资产调拨
     */
    @Override
    public DbAssetsStockAllot selectDbAssetsStockAllotById(Long aId) {
        return dbAssetsStockAllotMapper.selectDbAssetsStockAllotById(aId);
    }

    /**
     * 查询资产调拨列表
     *
     * @param dbAssetsStockAllotForm 资产调拨
     * @return 资产调拨
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<DbAssetsStockAllotVo> selectDbAssetsStockAllotList(DbAssetsStockAllotVo dbAssetsStockAllotForm) {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        String appUserId = userId.toString();
        List<DbAssetsStockAllotVo> dbAssetsStockAllots = dbAssetsStockAllotMapper.selectDbAssetsStockAllotList(dbAssetsStockAllotForm);
        for (DbAssetsStockAllotVo x : dbAssetsStockAllots) {
            String instanceId = x.getInstanceId();
            if (!StringUtils.isNull(instanceId)) {
                Task task = taskService.createTaskQuery().taskAssignee(appUserId).processInstanceId(instanceId).singleResult();
                if (!StringUtils.isNull(task)) {
                    x.setTaskId(task.getId());
                }
            }
        }
        return dbAssetsStockAllots;
    }

    /**
     * 新增资产调拨
     *
     * @param dbAssetsStockAllot 资产调拨
     * @return 结果
     */
    @Autowired
    private DbAssetsStockAllotExMapper dbAssetsStockAllotExMapper;


    @Override
    @Transactional
    public int insertDbAssetsStockAllot(DbAssetsStockAllot dbAssetsStockAllot) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        String userId = user.getUserId().toString();
        Date nowDate = DateUtils.getNowDate();

        dbAssetsStockAllot.setCreateBy(userId);
        dbAssetsStockAllot.setCreateTime(nowDate);
        int i = dbAssetsStockAllotMapper.insertDbAssetsStockAllot(dbAssetsStockAllot);
        List<Long> stockValue = dbAssetsStockAllot.getStockValue();
        List<DbAssetsStockAllotEx> collect = stockValue.stream().map(x -> {
            DbAssetsStockAllotEx dbAssetsStockAllotEx = new DbAssetsStockAllotEx();
            Long aLong = dbAssetsStockAllot.getaId();
            //调拨申请ID
            dbAssetsStockAllotEx.setAllotId(aLong);
            //物资id
            dbAssetsStockAllotEx.setDbAsStId(x);
            dbAssetsStockAllotEx.setCreateBy(userId);
            dbAssetsStockAllotEx.setCreateTime(nowDate);
            return dbAssetsStockAllotEx;
        }).collect(Collectors.toList());
        if(collect.size()>0){
            dbAssetsStockAllotExMapper.insertlist(collect);
        }
        return i;
    }

    /**
     * 修改资产调拨
     *
     * @param dbAssetsStockAllot 资产调拨
     * @return 结果
     */
    @Override
    public int updateDbAssetsStockAllot(DbAssetsStockAllot dbAssetsStockAllot) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        String userId = user.getUserId().toString();
        Date nowDate = DateUtils.getNowDate();
        dbAssetsStockAllot.setUpdateBy(userId);
        dbAssetsStockAllot.setUpdateTime(nowDate);
        int i = dbAssetsStockAllotMapper.updateDbAssetsStockAllot(dbAssetsStockAllot);
        Long allotId = dbAssetsStockAllot.getaId();
        dbAssetsStockAllotExMapper.deleteDbAssetsStockAllotExByAllotId(allotId);
        List<Long> stockValue = dbAssetsStockAllot.getStockValue();
        List<DbAssetsStockAllotEx> collect = stockValue.stream().map(x -> {
            DbAssetsStockAllotEx dbAssetsStockAllotEx = new DbAssetsStockAllotEx();
            Long aLong = dbAssetsStockAllot.getaId();
            //调拨申请ID
            dbAssetsStockAllotEx.setAllotId(aLong);
            //物资id
            dbAssetsStockAllotEx.setDbAsStId(x);
            dbAssetsStockAllotEx.setCreateBy(userId);
            dbAssetsStockAllotEx.setCreateTime(nowDate);
            return dbAssetsStockAllotEx;
        }).collect(Collectors.toList());
        if(collect.size()>0){
            dbAssetsStockAllotExMapper.insertlist(collect);
        }
        return i;
    }

    /**
     * 批量删除资产调拨
     *
     * @param aIds 需要删除的资产调拨ID
     * @return 结果
     */
    @Override
    public int deleteDbAssetsStockAllotByIds(Long[] aIds) {
        return dbAssetsStockAllotMapper.deleteDbAssetsStockAllotByIds(aIds);
    }

    /**
     * 删除资产调拨信息
     *
     * @param aId 资产调拨ID
     * @return 结果
     */
    @Override
    public int deleteDbAssetsStockAllotById(Long aId) {
        return dbAssetsStockAllotMapper.deleteDbAssetsStockAllotById(aId);
    }

    @Override
    public void commit(Long aId, String processId) {
        DbAssetsStockAllot dbAssetsStockAllot = dbAssetsStockAllotMapper.selectDbAssetsStockAllotById(aId);
        commitData(aId, processId,dbAssetsStockAllot);
    }



    private void commitData(Long aId, String processId,DbAssetsStockAllot dbAssetsStockAllot) {
        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", dbAssetsStockAllot);
        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);
        //更新表单
        dbAssetsStockAllot.setInstanceId(processInstanceId);
        dbAssetsStockAllot.setState(0);
        dbAssetsStockAllotMapper.updateDbAssetsStockAllot(dbAssetsStockAllot);
        //插入历史
        iDbTableHisService.insertDbTableHis(processInstanceId, aId, "db_assets_stock_allot");
    }

    @Override
    public void recommit(DbAssetsStockAllot dbAssetsStockAllot) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long userId = user.getUserId();
        // 启动流程时设置业务 key
        Map<String, Object> map = new HashMap<>();
        String appUserId = userId.toString();
        map.put("appUserId", appUserId);
        String taskId = dbAssetsStockAllot.getTaskId();
        // 启动流程时设置业务 key
        map.put("formData", dbAssetsStockAllot);
        map.put("formData", dbAssetsStockAllot);
        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);
        //设置为审核中
        dbAssetsStockAllot.setState(0);
        dbAssetsStockAllotMapper.updateDbAssetsStockAllot(dbAssetsStockAllot);
    }
}
