package com.bonus.material.event;

import com.bonus.common.biz.domain.lease.LeaseApplyInfo;
import com.bonus.common.biz.domain.lease.WorkApplyInfo;
import com.bonus.common.biz.domain.lease.WorkPeopleInfo;
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.core.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.basic.domain.dto.SysUserRoleVo;
import com.bonus.material.ma.domain.DirectApplyInfo;
import com.bonus.material.task.domain.TmTask;
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.system.api.domain.SysUser;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

@Component
public class ApplyEventListener {

    @Resource
    private SysWorkflowRecordMapper sysWorkflowRecordMapper;

    @Resource
    private SysWorkflowTypeMapper sysWorkflowTypeMapper;

    @Resource
    private SysWorkflowRecordHistoryMapper sysWorkflowRecordHistoryMapper;

    @Resource
    private SysWorkflowNodeMapper sysWorkflowNodeMapper;

    @Resource
    private DirectAuditMapper directAuditMapper;

    @EventListener
//    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public int addSysWorkflowRecord(InsertWorkflowEvent event) {
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        int count = 0;
        System.out.println("Workflow工作流监听器收到事件: ");

        //获取审批流id
        SysWorkflowType sysWorkflowType = new SysWorkflowType();
        sysWorkflowType.setTaskType(event.getTaskType());
        sysWorkflowType.setIsEnable(1);
        List<SysWorkflowType> sysWorkflowTypeList = sysWorkflowTypeMapper.selectSysWorkflowTypeList(sysWorkflowType);
        if (sysWorkflowTypeList.isEmpty()) {
            throw new ServiceException("新增任务审批记录失败,请创建审核流程");
        }
        SysWorkflowRecord sysWorkflowRecord = new SysWorkflowRecord();
        if (sysWorkflowTypeList.size() == 1) {
            // 如果该任务类型配置了一个审批流，则直接使用
            sysWorkflowType = sysWorkflowTypeList.get(0);
            sysWorkflowRecord = new SysWorkflowRecord();
            sysWorkflowRecord.setWorkflowId(sysWorkflowType.getId());
            sysWorkflowRecord.setTaskId(event.getTaskId());
            sysWorkflowRecord.setTaskType(event.getTaskType());
            sysWorkflowRecord.setTaskCode(event.getTaskCode());
            //创建审批任务
            count = sysWorkflowRecordMapper.addSysWorkflowRecord(sysWorkflowRecord);
            if (0 == count) {
                throw new RuntimeException("创建审批任务失败!");
            }

        } else {
            sysWorkflowRecord = new SysWorkflowRecord();
            sysWorkflowRecord.setTaskId(event.getTaskId());
            sysWorkflowRecord.setTaskType(event.getTaskType());
            sysWorkflowRecord.setTaskCode(event.getTaskCode());
            //创建审批任务
              count = sysWorkflowRecordMapper.addSysWorkflowRecord(sysWorkflowRecord);
            // 如果该任务类型配置了多个审批流，则根据任务信息判断使用
            if (event.getTaskType() == 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() != event.getTaskId());
                if (directAuditMapperList.isEmpty()) {
                    // 如果没有转出转入信息，则使用需要接收审批流
                    if (!sysWorkflowTypeList.isEmpty()) {
                        sysWorkflowTypeList.removeIf(removeIfSysWorkflowType -> removeIfSysWorkflowType.getTypeName().contains("无需接收审批"));
                    }
                } else {
                    // 如果有转出转入信息，则根据转出转入部门判断使用
                    DirectApplyInfo directApplyInfo = directAuditMapperList.get(0);
                    // 如果转入转出的部门ID相同，则使用不需要接收审批流

                    //查询是否是同一实施单位
                    int proIdBack = directAuditMapper.getImpUnit(directApplyInfo.getBackProId());
                    int proIdLease = directAuditMapper.getImpUnit(directApplyInfo.getLeaseProId());

                    if (proIdBack == proIdLease) {
                        sysWorkflowTypeList.removeIf(removeIfSysWorkflowType -> removeIfSysWorkflowType.getTypeName().contains("需要接收审批"));
                    } else {
                        // 如果转入转出的部门ID不同，则使用需要接收审批流
                        sysWorkflowTypeList.removeIf(removeIfSysWorkflowType -> removeIfSysWorkflowType.getTypeName().contains("无需接收审批"));
                    }
                }
                sysWorkflowType = sysWorkflowTypeList.get(0);
            } else {
                // 除了直转任务外，其他任务类型如果有配置多个审批流，先默认选第一个
                sysWorkflowType = sysWorkflowTypeList.get(0);
            }
            sysWorkflowRecord.setWorkflowId(sysWorkflowType.getId());
            //插入任务审批类型
            int countTwo = sysWorkflowRecordMapper.updateSysWorkflowType(sysWorkflowRecord);

        }

        // 获取新创建的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());
        int  projectId = directAuditMapper.getProjectIdById(event.getBackAgreementId());
        //根据project_id获取external_id
        String externalId = directAuditMapper.getExternalId(projectId);
        List<WorkPeopleInfo> userList = new ArrayList<>();
        if (externalId != null && !externalId.isEmpty()) {
            //获取项目总工id
            String leaderId = directAuditMapper.getLeaderId(externalId);
            if(leaderId != null && !leaderId.isEmpty()){
                //获取项目总工账号
                String leaderAccount = directAuditMapper.getUserNameById(leaderId);
                if(leaderAccount != null && !leaderAccount.isEmpty()){
                    userList = directAuditMapper.getUserIdByUserName(leaderAccount);
                    if(userList != null && !userList.isEmpty()){
                        String userIds = userList.stream().map(WorkPeopleInfo::getUserId).map(String::valueOf).collect(Collectors.joining(","));
                        sysWorkflowRecordHistory.setDirectUserIds(userIds);
                    }
                }
            }else{
                directAuditMapper.deleteWorkflowRecord(newId);
                throw new RuntimeException("项目总工不存在");
            }
        }else{
            directAuditMapper.deleteWorkflowRecord(newId);
            throw new RuntimeException("未找到所属工程");
        }
        sysWorkflowRecordHistoryMapper.addSysWorkflowRecordHistory(sysWorkflowRecordHistory);

        if (count > 0 && userList != null && !userList.isEmpty()) {
            createWorkOrderAndPeople(sysUser, event, Long.valueOf(sysWorkflowRecord.getTaskId()), newId,sysWorkflowRecordHistory.getNodeId(),userList);
        }
        return newId;
    }

    private void createWorkOrderAndPeople(SysUser sysUser, InsertWorkflowEvent event, Long taskId, int newId,int nodeId,List<WorkPeopleInfo> userList) {
        //获取工程名称
        int  projectId = directAuditMapper.getProjectIdById(event.getBackAgreementId());
        String projectName = directAuditMapper.getProjectNameById(projectId);
        String id = UUID.randomUUID().toString().replace("-", "");
        String webUrlBase = "/mea-h5/#/pages/businessAudit/directAudit/details";
        String queryParams = UriComponentsBuilder.newInstance()
                .queryParam("appId", "9fa73f046ef520b09e94bbffc3b07702")
                .queryParam("taskId", taskId)
                .queryParam("id", newId)
                .queryParam("nodeId", nodeId)
                .build().encode().toUriString();

        WorkApplyInfo workApplyInfo = new WorkApplyInfo();
        workApplyInfo.setId(id);
        workApplyInfo.setTitle("智能机具-直转申请待审核");
        workApplyInfo.setCreateUserName(sysUser.getUserName());
        workApplyInfo.setContent(sysUser.getNickName() + ":" + event.getTaskCode() + "-" + projectName);
        workApplyInfo.setType(1);
        workApplyInfo.setWebAppId("9fa73f046ef520b09e94bbffc3b07702");
        workApplyInfo.setSendUserName(sysUser.getUserName());
        workApplyInfo.setTypeId(2025050901);
        workApplyInfo.setBusinessId(String.valueOf(newId));
        workApplyInfo.setNextStatus("待审核");
        workApplyInfo.setFlowState(null);
        workApplyInfo.setWebUrl(webUrlBase + queryParams);
        workApplyInfo.setRout(webUrlBase + queryParams);

        int countWork = directAuditMapper.insertWorkOrder(workApplyInfo);
        if (countWork > 0) {
            for (WorkPeopleInfo user : userList) {
                WorkPeopleInfo workPeopleInfo = new WorkPeopleInfo();
                workPeopleInfo.setId(UUID.randomUUID().toString().replace("-", ""));
                workPeopleInfo.setInformationId(id);
                    workPeopleInfo.setReceiverUsername(user.getUserName());
                    workPeopleInfo.setReadState(0);
                    workPeopleInfo.setHandleState(0);
                    workPeopleInfo.setIsExamine(0);
                    directAuditMapper.insertWorkPeople(workPeopleInfo);
            }
        }
    }

}
