package com.chinaweal.aiccs.aiccs.seriousillegal.service.impl;

import com.alibaba.excel.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSWrit;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSWritService;
import com.chinaweal.aiccs.aiccs.auditing.entity.TSOpinion;
import com.chinaweal.aiccs.aiccs.auditing.service.TSOpinionService;
import com.chinaweal.aiccs.aiccs.business.entity.TSTaskList;
import com.chinaweal.aiccs.aiccs.business.service.TSTaskListService;
import com.chinaweal.aiccs.aiccs.business.service.WorkFlowService;
import com.chinaweal.aiccs.aiccs.inspect.service.TSWorkNoService;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.EOtIlldisdetail;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.EOtIlldisdetailTemp;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.dto.TaskListTodoParam;
import com.chinaweal.aiccs.aiccs.seriousillegal.mapper.EOtIlldisdetailTempMapper;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.IEOtIlldisdetailService;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.IEOtIlldisdetailTempService;
import com.chinaweal.aiccs.common.constant.CommonConstants;
import com.chinaweal.aiccs.common.util.FlowUtil;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.common.util.WorkNoUtil;
import com.chinaweal.aiccs.org.service.AicorgService;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 其他部门列入严重违法失信企业名单（黑名单）详细信息_业务暂存表 服务实现类
 * </p>
 *
 * @author aiccs
 * @since 2026-03-05
 */
@Service
@Slf4j
public class EOtIlldisdetailTempServiceImpl extends ServiceImpl<EOtIlldisdetailTempMapper, EOtIlldisdetailTemp> implements IEOtIlldisdetailTempService {

    @Lazy
    @Autowired
    private IEOtIlldisdetailService eOtIlldisdetailService;

    @Autowired
    private TSTaskListService taskListService;

    @Autowired
    private WorkFlowService workFlowService;

    @Autowired
    private TSOpinionService opinionService;

    @Autowired
    private TSWritService tsWritService;

    @Autowired
    private TSWorkNoService workNoService;

    @Autowired
    private AicorgService aicorgService;

    @Override
    public List<EOtIlldisdetailTemp> listByBizSeq(String bizSeq) {
        List<EOtIlldisdetailTemp> list = lambdaQuery().eq(EOtIlldisdetailTemp::getInBizseq, bizSeq)
                .ne(EOtIlldisdetailTemp::getDstate, CommonConstants.DELETED_2).list();
        if (CollectionUtils.isEmpty(list)) {
            list = lambdaQuery().eq(EOtIlldisdetailTemp::getOutBizseq, bizSeq)
                    .ne(EOtIlldisdetailTemp::getDstate, CommonConstants.DELETED_2).list();
        }
        return list;
    }

    @Override
    public List<EOtIlldisdetailTemp> listByWorkflowId(String workflowId, boolean isEnter) {
        LambdaQueryWrapper<EOtIlldisdetailTemp> wrapper = new LambdaQueryWrapper<>();
        if (isEnter) {
            wrapper.eq(EOtIlldisdetailTemp::getInWorkflowId, workflowId);
        } else {
            wrapper.eq(EOtIlldisdetailTemp::getOutWorkflowId, workflowId);
        }
        return list(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TSTaskList handleEnterApprovalProcess(AICUser user, TSTaskList taskListModel,
                                                 List<EOtIlldisdetailTemp> tempRecords, TSOpinion opinionModel,
                                                 String nextNodeID, String[] nextPerformerids, String[] nextPerformerNames) {
        try {
            // 保存审批意见
            if (opinionModel != null && StringUtils.isNotBlank(opinionModel.getOperOpinion())) {
                opinionModel.setBizseq(taskListModel.getBizseqid());
                opinionModel.setHandler(user.getName());
                opinionModel.setHandlerid(user.getPrimaryKey());
                opinionModel.setHandledate(LocalDateTime.now());
                opinionService.save(opinionModel);
            }

            // 根据节点处理业务逻辑
            if (FlowUtil.SERIOUS_ILLEGAL_EXAMINE_SUCCESS.equals(nextNodeID)) {
                // 审批通过，将Temp表数据复制到正式表
                for (EOtIlldisdetailTemp tempRecord : tempRecords) {
                    tempRecord.setInWorkflowId(taskListModel.getWorkflowid());
                    EOtIlldisdetail detail = eOtIlldisdetailService.copyFromTemp(tempRecord);

                    // 生成列入文书号
                    if (detail != null) {
                        TSWrit tsWritModel = new TSWrit();
                        String tswritId = java.util.UUID.randomUUID().toString();
                        tsWritModel.setWritsid(tswritId);
                        String workNoType = WorkNoUtil.WORKNOTYPE_80; // 其他部门列入严重违法失信企业名单 决定书文号
                        String writsno = workNoService.getOperatingWrirsno(workNoType, user.getRegionID());
                        tsWritModel.setBizseq(taskListModel.getBizseqid());
                        tsWritModel.setWritsno(writsno);
                        tsWritModel.setWritstype(workNoType);
                        tsWritModel.setPripid(detail.getPripid());
                        tsWritModel.setAreaCode(user.getRegionID());
                        tsWritModel.setWritsname(WorkNoUtil.getWorkNoTypeName(workNoType));
                        tsWritModel.setContent(detail.getEntname() + "（统一社会信用代码/注册号："
                                + (detail.getUniscid() != null ? detail.getUniscid() : detail.getRegno())
                                + "）：" + detail.getSerillreaCn());
                        tsWritModel.setCreatetime(LocalDateTime.now());
                        tsWritModel.setLauptime(LocalDateTime.now());
                        tsWritService.save(tsWritModel);

                        // 更新正式表中的列入文书ID
                        detail.setIntowritid(tswritId);
                        detail.setDedocnum(writsno);
                        eOtIlldisdetailService.updateById(detail);
                    }
                }
            } else if (FlowUtil.SERIOUS_ILLEGAL_EXAMINE_FAIL.equals(nextNodeID)) {
                // 审批不通过，删除Temp表数据
                for (EOtIlldisdetailTemp tempRecord : tempRecords) {
                    removeById(tempRecord.getIllid());
                }
            }

            // 流程流转
            if (StringUtils.isNotBlank(nextNodeID) && nextPerformerids != null && nextPerformerids.length > 0) {
                taskListService.updateWorkFlow(user, opinionModel, taskListModel, nextNodeID, nextPerformerids, nextPerformerNames);
            }

            return taskListModel;
        } catch (Exception e) {
            log.error("处理其他部门列入严重违法失信业务审批流程失败", e);
            throw new BusinessException("处理审批流程失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TSTaskList handleRemoveApprovalProcess(AICUser user, TSTaskList taskListModel,
                                                  List<EOtIlldisdetailTemp> tempRecords, TSOpinion opinionModel,
                                                  String nextNodeID, String[] nextPerformerids, String[] nextPerformerNames) {
        try {
            // 保存审批意见
            if (opinionModel != null && StringUtils.isNotBlank(opinionModel.getOperOpinion())) {
                opinionModel.setBizseq(taskListModel.getBizseqid());
                opinionModel.setHandler(user.getName());
                opinionModel.setHandlerid(user.getPrimaryKey());
                opinionModel.setHandledate(LocalDateTime.now());
                opinionService.save(opinionModel);
            }

            // 根据节点处理业务逻辑
            if (FlowUtil.SERIOUS_ILLEGAL_EXAMINE_SUCCESS.equals(nextNodeID)) {
                // 审批通过，更新正式表的移出信息
                for (EOtIlldisdetailTemp tempRecord : tempRecords) {
                    tempRecord.setOutWorkflowId(taskListModel.getWorkflowid());
                    EOtIlldisdetail detail = eOtIlldisdetailService.getById(tempRecord.getIllid());
                    if (detail != null) {
                        // 生成移出文书号
                        TSWrit tsWritModel = new TSWrit();
                        String tswritId = java.util.UUID.randomUUID().toString();
                        tsWritModel.setWritsid(tswritId);
                        String workNoType = WorkNoUtil.WORKNOTYPE_81; // 其他部门移出严重违法失信企业名单 决定书
                        String writsno = workNoService.getOperatingWrirsno(workNoType, user.getRegionID());
                        tsWritModel.setBizseq(taskListModel.getBizseqid());
                        tsWritModel.setWritsno(writsno);
                        tsWritModel.setWritstype(workNoType);
                        tsWritModel.setPripid(detail.getPripid());
                        tsWritModel.setAreaCode(user.getRegionID());
                        tsWritModel.setWritsname(WorkNoUtil.getWorkNoTypeName(workNoType));
                        tsWritModel.setContent(detail.getEntname() + "（统一社会信用代码/注册号："
                                + (detail.getUniscid() != null ? detail.getUniscid() : detail.getRegno())
                                + "）：" + tempRecord.getRemexcpresCn());
                        tsWritModel.setCreatetime(LocalDateTime.now());
                        tsWritModel.setLauptime(LocalDateTime.now());
                        tsWritService.save(tsWritModel);

                        // 更新正式表中的移出信息
                        detail.setRemexcpres(tempRecord.getRemexcpres());
                        detail.setRemexcpresCn(tempRecord.getRemexcpresCn());
                        detail.setRemdate(tempRecord.getRemdate());
                        detail.setRecorg(tempRecord.getRecorg());
                        detail.setRecorgCn(tempRecord.getRecorgCn());
                        detail.setRedocnum(tempRecord.getRedocnum());
                        detail.setRemwritid(tswritId); // 保存移出文书ID
                        detail.setRedocnum(writsno);
                        detail.setSExtDatetime(LocalDateTime.now());
                        eOtIlldisdetailService.updateById(detail);
                    }
                }
            } else if (FlowUtil.SERIOUS_ILLEGAL_EXAMINE_FAIL.equals(nextNodeID)) {
                // 审批不通过，删除Temp表数据
                for (EOtIlldisdetailTemp tempRecord : tempRecords) {
                    removeById(tempRecord.getIllid());
                }
            }

            // 流程流转
            if (StringUtils.isNotBlank(nextNodeID) && nextPerformerids != null && nextPerformerids.length > 0) {
                taskListService.updateWorkFlow(user, opinionModel, taskListModel, nextNodeID, nextPerformerids, nextPerformerNames);
            }

            return taskListModel;
        } catch (Exception e) {
            log.error("处理其他部门移出严重违法失信业务审批流程失败", e);
            throw new BusinessException("处理审批流程失败：" + e.getMessage());
        }
    }

    @Override
    public IPage<TSTaskList> getTaskListTodoPage(IPage<TSTaskList> page, TaskListTodoParam param) {
        return baseMapper.selectTaskListTodoPage(page, param);
    }

    @Override
    public IPage<EOtIlldisdetailTemp> getTodoHistoryPage(IPage<EOtIlldisdetailTemp> page, TaskListTodoParam param) {
        return baseMapper.selectTodoHistoryPage(page, param);
    }
}