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

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinaweal.aiccs.aiccs.business.entity.TSTaskList;
import com.chinaweal.aiccs.aiccs.business.service.TSTaskListService;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.EOtIlldisdetail;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.EOtIlldisdetailTemp;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.dto.RemoveAcceptDto;
import com.chinaweal.aiccs.aiccs.seriousillegal.mapper.EOtIlldisdetailMapper;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.IEOtIlldisdetailService;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.IEOtIlldisdetailTempService;
import com.chinaweal.aiccs.common.util.FlowUtil;
import com.chinaweal.aiccs.common.util.HandleWorkFlowUtil;
import com.chinaweal.aicorg.model.AICUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

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

    @Autowired
    private IEOtIlldisdetailTempService eOtIlldisdetailTempService;

    @Autowired
    private TSTaskListService taskListService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public EOtIlldisdetail copyFromTemp(EOtIlldisdetailTemp tempRecord) {
        if (tempRecord == null) {
            return null;
        }

        EOtIlldisdetail detail = new EOtIlldisdetail();
        BeanUtils.copyProperties(tempRecord, detail);

        // 设置数据汇总时间和单位
        detail.setSExtDatetime(LocalDateTime.now());
        if (tempRecord.getSExtFromnode() != null) {
            detail.setSExtFromnode(tempRecord.getSExtFromnode());
        }

        // 保存到正式表
        save(detail);

        return detail;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchCopyFromTemp(List<EOtIlldisdetailTemp> tempRecords) {
        if (tempRecords == null || tempRecords.isEmpty()) {
            return false;
        }

        for (EOtIlldisdetailTemp tempRecord : tempRecords) {
            copyFromTemp(tempRecord);
        }

        return true;
    }

    @Override
    public List<EOtIlldisdetailTemp> listByBizSeq(String bizSeq) {
        return eOtIlldisdetailTempService.listByBizSeq(bizSeq);
    }

    @Override
    public EOtIlldisdetailTemp getTempById(String illid) {
        return eOtIlldisdetailTempService.getById(illid);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TSTaskList saveEnterAccept(AICUser aicUser, TSTaskList taskListModel, List<EOtIlldisdetailTemp> bizList) {
        if (bizList == null || bizList.isEmpty()) {
            throw new IllegalArgumentException("业务记录列表不能为空");
        }

        // 设置业务名称
        StringBuilder entName = new StringBuilder();
        for (int i = 0; i < bizList.size(); i++) {
            if (i > 0) entName.append("、");
            if (i > 1) {
                entName.append("等企业");
                break;
            }
            entName.append(bizList.get(i).getEntname());
        }
        taskListModel.setBusname(entName.toString());

        // 创建待办并启动工作流
        if (taskListModel.getTasklistid() == null) {
            taskListModel.setAreaCode(aicUser.getRegionID());
            taskListModel = HandleWorkFlowUtil.createTaskList(taskListModel, aicUser);
            taskListService.startWorkFlow(taskListModel, aicUser, FlowUtil.SERIOUS_ILLEGAL_WORKFLOW);
        }

        // 保存到Temp表
        for (EOtIlldisdetailTemp tempRecord : bizList) {
            if (tempRecord.getIllid() == null) {
                tempRecord.setIllid(java.util.UUID.randomUUID().toString().replace("-", ""));
            }
            tempRecord.setDstate("0"); // 0：插入
            tempRecord.setInWorkflowId(taskListModel.getWorkflowid());
            tempRecord.setInBizseq(taskListModel.getBizseqid());
            eOtIlldisdetailTempService.saveOrUpdate(tempRecord);
        }

        return taskListModel;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TSTaskList saveRemoveAccept(AICUser aicUser, TSTaskList taskListModel, RemoveAcceptDto dto, String remexcpresCn) {
        if (dto.getIllidList() == null || dto.getIllidList().isEmpty()) {
            throw new IllegalArgumentException("移出记录清单不能为空");
        }

        // 根据illidList查询正式表记录
        List<EOtIlldisdetail> originalRecords = this.lambdaQuery()
                .in(EOtIlldisdetail::getIllid, dto.getIllidList())
                .list();

        if (originalRecords == null || originalRecords.isEmpty()) {
            throw new IllegalArgumentException("未找到要移出的记录");
        }

        // 检查记录是否已被移出
        for (EOtIlldisdetail record : originalRecords) {
            if (record.getRemdate() != null) {
                throw new IllegalArgumentException("记录 " + record.getEntname() + " 已被移出，不能重复移出");
            }
        }

        // 构建Temp表记录列表
        List<EOtIlldisdetailTemp> bizList = new ArrayList<>();
        for (EOtIlldisdetail originalRecord : originalRecords) {
            EOtIlldisdetailTemp tempRecord = new EOtIlldisdetailTemp();
            // 复制正式表数据到Temp表
            BeanUtils.copyProperties(originalRecord, tempRecord);
            // 保存原始illid到illid字段，以便审批后能正确更新正式表中的对应记录
            // 不生成新的illid，使用原来的illid
            // 设置移出相关信息
            tempRecord.setRemexcpres(dto.getRemexcpres());
            tempRecord.setRemexcpresCn(remexcpresCn);
            tempRecord.setRemdate(dto.getRemdate());
            // 设置业务状态
            tempRecord.setDstate("1"); // 1：更新
            tempRecord.setOutBizseq(taskListModel.getBizseqid());

            bizList.add(tempRecord);
        }

        // 设置业务名称
        StringBuilder entName = new StringBuilder();
        for (int i = 0; i < bizList.size(); i++) {
            if (i > 0) entName.append("、");
            if (i > 1) {
                entName.append("等企业");
                break;
            }
            entName.append(bizList.get(i).getEntname());
        }
        taskListModel.setBusname(entName.toString());

        // 创建待办并启动工作流
        if (taskListModel.getTasklistid() == null) {
            taskListModel.setAreaCode(aicUser.getRegionID());
            taskListModel = HandleWorkFlowUtil.createTaskList(taskListModel, aicUser);
            taskListService.startWorkFlow(taskListModel, aicUser, FlowUtil.SERIOUS_ILLEGAL_WORKFLOW);
        }


        // 保存到Temp表
        for (EOtIlldisdetailTemp tempRecord : bizList) {
            tempRecord.setOutWorkflowId(taskListModel.getWorkflowid());
            eOtIlldisdetailTempService.saveOrUpdate(tempRecord);
        }

        return taskListModel;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TSTaskList saveRemoveAccept(AICUser aicUser, TSTaskList taskListModel, List<EOtIlldisdetailTemp> bizList) {
        if (bizList == null || bizList.isEmpty()) {
            throw new IllegalArgumentException("业务记录列表不能为空");
        }

        // 设置业务名称
        StringBuilder entName = new StringBuilder();
        for (int i = 0; i < bizList.size(); i++) {
            if (i > 0) entName.append("、");
            if (i > 1) {
                entName.append("等企业");
                break;
            }
            entName.append(bizList.get(i).getEntname());
        }
        taskListModel.setBusname(entName.toString());

        // 创建待办并启动工作流
        if (taskListModel.getTasklistid() == null) {
            taskListModel.setAreaCode(aicUser.getRegionID());
            taskListModel = HandleWorkFlowUtil.createTaskList(taskListModel, aicUser);
            taskListService.startWorkFlow(taskListModel, aicUser, FlowUtil.SERIOUS_ILLEGAL_WORKFLOW);
        }

        // 保存到Temp表
        for (EOtIlldisdetailTemp tempRecord : bizList) {
            if (tempRecord.getIllid() == null) {
                tempRecord.setIllid(java.util.UUID.randomUUID().toString().replace("-", ""));
            }
            tempRecord.setDstate("1"); // 1：更新
            tempRecord.setOutBizseq(taskListModel.getBizseqid());
            tempRecord.setOutWorkflowId(taskListModel.getWorkflowid());
            eOtIlldisdetailTempService.saveOrUpdate(tempRecord);
        }


        return taskListModel;
    }
}