package com.zbf.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbf.common.core.text.Convert;
import com.zbf.common.utils.DateUtils;
import com.zbf.common.utils.StringUtils;
import com.zbf.system.domain.OutBound;
import com.zbf.system.mapper.OutBoundMapper;
import com.zbf.system.service.IOutBoundService;
import org.flowable.engine.HistoryService;
import org.flowable.engine.IdentityService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 出库申请单Service业务层处理
 *
 * @author tony
 * @date 2024-08-07
 */
@Service
public class OutBoundServiceImpl extends ServiceImpl<OutBoundMapper, OutBound> implements IOutBoundService //修改
{
    private final Logger logger = LoggerFactory.getLogger(OutBoundServiceImpl.class);
    @Autowired
    private OutBoundMapper outBoundMapper;
    @Resource
    private RuntimeService runtimeService;

    @Resource
    private TaskService taskService;

    @Resource
    IdentityService identityService;

    @Resource
    HistoryService historyService;

    /**
     * 查询出库申请单
     *
     * @param id 出库申请单主键
     * @return 出库申请单
     */
    @Override
    public OutBound selectOutBoundById(Long id)
    {
        return outBoundMapper.selectOutBoundById(id);
    }

    /**
     * 查询出库申请单列表
     *
     * @param outBound 出库申请单
     * @return 出库申请单
     */
    @Override
    public List<OutBound> selectOutBoundList(OutBound outBound)
    {
        return outBoundMapper.selectOutBoundList(outBound);
    }

    /**
     * 新增出库申请单
     *
     * @param outBound 出库申请单
     * @return 结果
     */
    @Override
    public int insertOutBound(OutBound outBound)
    {
        outBound.setCreateTime(new Date());
        outBound.setUpdateTime(new Date());
        int row = outBoundMapper.insertOutBound(outBound);
        // 启动流程
        identityService.setAuthenticatedUserId(outBound.getApplyer());
        HashMap<String, Object> variables = new HashMap<>();
        variables.put("starter", outBound.getApplyer());
        variables.put("userId", outBound.getApplyer());
        variables.put("deptmanager", outBound.getDeptmanager());
        variables.put("deliveryId",outBound.getDeliveryId());
        variables.put("ckType", outBound.getCkType());
        variables.put("managerName", outBound.getManagerName());
        variables.put("outBoundId",outBound.getId());
        variables.put("instanceId",outBound.getInstanceId());
        //新增第三申请人
        Task autoTask = null;
        ProcessInstance pickingout_audit = null;
        if(StringUtils.isNotBlank(outBound.getCrossDeptManager())) {
            variables.put("crossDeptManager", outBound.getCrossDeptManager());
            pickingout_audit = runtimeService.startProcessInstanceByKey("Pickingout_Audit", String.valueOf(outBound.getId()), variables);
            // 自动完成第一个任务
            autoTask = taskService.createTaskQuery().processDefinitionKey("Pickingout_Audit").processInstanceBusinessKey(String.valueOf(outBound.getId())).singleResult();
        }else {
            pickingout_audit = runtimeService.startProcessInstanceByKey("Flowable_Pickingout", String.valueOf(outBound.getId()), variables);
            // 自动完成第一个任务
           autoTask = taskService.createTaskQuery().processDefinitionKey("Flowable_Pickingout").processInstanceBusinessKey(String.valueOf(outBound.getId())).singleResult();
        }
        //更新outbound表和tckOrder表
        taskService.complete(autoTask.getId());
        //            // 根据流程实例ID和审核人查询任务
            List<Task> tasks = taskService.createTaskQuery()
                    .processInstanceId(pickingout_audit.getId()) // 指定流程实例ID
                    .taskAssignee(outBound.getDeptmanager())              // 指定审核人
                    .orderByTaskCreateTime().desc()  // 按任务创建时间排序
                    .list();
            if (tasks.isEmpty()) {
//                logger.error("获取运行中待审核任务为空！");
//                throw new RuntimeException("获取运行中待审核任务为空");
            } else {
                Task task = tasks.get(0);
                outBound.setTaskId(task.getId());
                // 根据流程实例ID和审核人查询任务
                outBound.setfInstanceId(pickingout_audit.getId());
                outBound.setUpdateTime(new Date());
                outBoundMapper.updateOutBound(outBound);
                logger.info("更新完成，任务号为：{}", task.getId());
            }

        return row;
    }

    /**
     * 修改出库申请单
     *
     * @param outBound 出库申请单
     * @return 结果
     */
    @Override
    public int updateOutBound(OutBound outBound)
    {
        return outBoundMapper.updateOutBound(outBound);
    }

    /**
     * 批量删除出库申请单
     *
     * @param ids 需要删除的出库申请单主键
     * @return 结果
     */
    @Override
    public int deleteOutBoundByIds(String ids)
    {
        String[] keys = Convert.toStrArray(ids);
        for (String key : keys) {
            ProcessInstance process = runtimeService.createProcessInstanceQuery().processDefinitionKey("Flowable_Pickingout").processInstanceBusinessKey(key).singleResult();
            if (process != null) {
                runtimeService.deleteProcessInstance(process.getId(), "删除");
            }
            // 删除历史数据
            HistoricProcessInstance history = historyService.createHistoricProcessInstanceQuery().processDefinitionKey("Flowable_Pickingout").processInstanceBusinessKey(key).singleResult();
            if (history != null) {
                historyService.deleteHistoricProcessInstance(history.getId());
            }
            outBoundMapper.deleteOutBoundByIds(Convert.toStrArray(ids));
        }
        return keys.length;
    }

    /**
     * 删除出库申请单信息
     *
     * @param id 出库申请单主键
     * @return 结果
     */
    @Override
    public int deleteOutBoundById(Long id)
    {
        return outBoundMapper.deleteOutBoundById(id);
    }


    /**
     * 批量禁用
     *
     * @param id 出库申请单主键
     * @return 结果
     */
    @Override
    public int disabledOutBoundByIds(Long[] ids) {
        return outBoundMapper.disabledOutBoundByIds(ids);
    }

    /**
     * 批量启用
     *
     * @param id 出库申请单主键
     * @return 结果
     */
    @Override
    public int enableOutBoundByIds(Long[] ids) {
        return outBoundMapper.enableOutBoundByIds(ids);
    }

    /**
     * 修改状态
     *
     * @param outBound 工序管理主键
     * @return 结果
     */
    @Override
    public int updateStatus(OutBound outBound) {
        return outBoundMapper.updateOutBound(outBound);
    }

}
