package com.bonus.material.work.service.impl;

import com.bonus.common.biz.domain.lease.LeaseApplyInfo;
import com.bonus.common.biz.enums.TmTaskTypeEnum;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.ma.domain.DirectApplyInfo;
import com.bonus.material.work.domain.SysWorkflowNode;
import com.bonus.material.work.domain.SysWorkflowRecord;
import com.bonus.material.work.domain.SysWorkflowRecordHistory;
import com.bonus.material.work.domain.SysWorkflowType;
import com.bonus.material.work.mapper.*;
import com.bonus.material.work.service.SysWorkflowRecordService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
public class SysWorkflowRecordServiceImpl implements SysWorkflowRecordService {

    @Resource
    private SysWorkflowRecordMapper sysWorkflowRecordMapper;

    @Resource
    private SysWorkflowTypeMapper sysWorkflowTypeMapper;

    @Resource
    private SysWorkflowRecordHistoryMapper sysWorkflowRecordHistoryMapper;

    @Resource
    private SysWorkflowNodeMapper sysWorkflowNodeMapper;

    @Resource
    private DirectAuditMapper directAuditMapper;

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public int addSysWorkflowRecord(int taskId, String taskCode, int taskType) {
        //获取审批流id
        SysWorkflowType sysWorkflowType = new SysWorkflowType();
        sysWorkflowType.setTaskType(taskType);
        sysWorkflowType.setIsEnable(1);
        List<SysWorkflowType> sysWorkflowTypeList = sysWorkflowTypeMapper.selectSysWorkflowTypeList(sysWorkflowType);
        if (sysWorkflowTypeList.isEmpty()) {
            throw new ServiceException("新增任务审批记录失败,请创建审核流程");
        }
        if (sysWorkflowTypeList.size() == 1) {
            // 如果该任务类型配置了一个审批流，则直接使用
            sysWorkflowType = sysWorkflowTypeList.get(0);
        } else {
            // 如果该任务类型配置了多个审批流，则根据任务信息判断使用
            if (taskType == TmTaskTypeEnum.TM_TASK_DIRECT.getTaskTypeId()) {
                // 直转审批任务，则根据转出和转入的部门判断，同一部门使用无需接收审批流，不同部门则使用需要接收审批流
                // 先根据任务ID去查询转入和转出部门，进行判断
                List<DirectApplyInfo> directAuditMapperList = directAuditMapper.getList(new DirectApplyInfo());
                directAuditMapperList.removeIf(Objects::isNull);
                directAuditMapperList.removeIf(directApplyInfo -> directApplyInfo.getId() == null || directApplyInfo.getId() != taskId);
                if (directAuditMapperList.isEmpty()) {
                    // 如果没有转出转入信息，则使用需要接收审批流
                    if (!sysWorkflowTypeList.isEmpty()) {
                        sysWorkflowTypeList.removeIf(removeIfSysWorkflowType -> removeIfSysWorkflowType.getTaskName().contains("无需接收审批"));
                    }
                } else {
                    // 如果有转出转入信息，则根据转出转入部门判断使用
                    DirectApplyInfo directApplyInfo = directAuditMapperList.get(0);
                    // 如果转入转出的部门ID相同，则使用不需要接收审批流
                    if (directApplyInfo.getBackUnitId().equals(directApplyInfo.getLeaseUnitId())) {
                        sysWorkflowTypeList.removeIf(removeIfSysWorkflowType -> removeIfSysWorkflowType.getTaskName().contains("需要接收审批"));
                    } else {
                        // 如果转入转出的部门ID不同，则使用需要接收审批流
                        sysWorkflowTypeList.removeIf(removeIfSysWorkflowType -> removeIfSysWorkflowType.getTaskName().contains("无需接收审批"));
                    }
                }
                sysWorkflowType = sysWorkflowTypeList.get(0);
            } else {
                // 除了直转任务外，其他任务类型如果有配置多个审批流，先默认选第一个
                sysWorkflowType = sysWorkflowTypeList.get(0);
            }
        }

        SysWorkflowRecord sysWorkflowRecord = new SysWorkflowRecord();
        sysWorkflowRecord.setWorkflowId(sysWorkflowType.getId());
        sysWorkflowRecord.setTaskId(taskId);
        sysWorkflowRecord.setTaskType(taskType);
        sysWorkflowRecord.setTaskCode(taskCode);
        //创建审批任务
        int count = sysWorkflowRecordMapper.addSysWorkflowRecord(sysWorkflowRecord);
        if (0 == count) {
            throw new RuntimeException("创建审批任务失败!");
        }
        // 获取新创建的ID
        int newId = sysWorkflowRecord.getId();
        //获取当前审核流下的节点
        SysWorkflowNode  sysWorkflowNode = new SysWorkflowNode();
        sysWorkflowNode.setTypeId(sysWorkflowType.getId());
        List<SysWorkflowNode> sysWorkflowNodeList = sysWorkflowNodeMapper.selectSysWorkflowNodeList(sysWorkflowNode);

        ///  2025-06-17 syruan : 任务要查询下个节点待审核的人员存入数据库
        // 获取当前登陆用户id，查询所在的分公司
        Long thisLoginUserDeptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
        if (null == thisLoginUserDeptId) {
            thisLoginUserDeptId = 0L;
        }


        // 创建审核记录
        SysWorkflowRecordHistory sysWorkflowRecordHistory = new SysWorkflowRecordHistory();
        sysWorkflowRecordHistory.setRecordId(sysWorkflowRecord.getId());
        sysWorkflowRecordHistory.setNodeId(sysWorkflowNodeList.get(0).getId());
        sysWorkflowRecordHistory.setNextNodeId(sysWorkflowNodeList.get(1).getId());
        sysWorkflowRecordHistory.setIsAccept(1);
        sysWorkflowRecordHistory.setCreateBy(SecurityUtils.getLoginUser().getUserid().toString());
        sysWorkflowRecordHistory.setCreateTime(DateUtils.getNowDate());
        sysWorkflowRecordHistoryMapper.addSysWorkflowRecordHistory(sysWorkflowRecordHistory);
        return newId;
    }

    /**
     * 判断该任务是否已经在sys_workflow_record表中创建
     * @param leaseApplyInfo
     * @return
     */
    @Override
    public int selectSysWorkflowRecordByTaskId(LeaseApplyInfo leaseApplyInfo) {
        return sysWorkflowRecordMapper.selectSysWorkflowRecordByTaskId(leaseApplyInfo);
    }
}
