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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.business.entity.XrOpinion;
import com.chinaweal.aiccs.aiccs.business.entity.XrTaskList;
import com.chinaweal.aiccs.aiccs.business.entity.dto.ApprovalFormDto;
import com.chinaweal.aiccs.aiccs.business.entity.vo.XrTaskListVo;
import com.chinaweal.aiccs.aiccs.business.rules.init.FlowUtil;
import com.chinaweal.aiccs.aiccs.business.service.IXrOpinionService;
import com.chinaweal.aiccs.aiccs.business.service.IXrTaskListService;
import com.chinaweal.aiccs.aiccs.inspect.service.TSWorkNoService;
import com.chinaweal.aiccs.aiccs.seriousillegalPerson.common.emnu.AuthEnum;
import com.chinaweal.aiccs.aiccs.seriousillegalPerson.entity.XrSeriousIllegalPersonList;
import com.chinaweal.aiccs.aiccs.seriousillegalPerson.entity.XrSeriousIllegalPersonRemList;
import com.chinaweal.aiccs.aiccs.seriousillegalPerson.entity.dto.PersonSpeSaveIvdDto;
import com.chinaweal.aiccs.aiccs.seriousillegalPerson.entity.dto.SeriousIllegalProcessRemDto;
import com.chinaweal.aiccs.aiccs.seriousillegalPerson.entity.dto.SeriousIllegalSpeQueryDto;
import com.chinaweal.aiccs.aiccs.seriousillegalPerson.mapper.XrSeriousIllegalPersonRemListMapper;
import com.chinaweal.aiccs.aiccs.seriousillegalPerson.service.IXrSeriousIllegalPersonListService;
import com.chinaweal.aiccs.aiccs.seriousillegalPerson.service.IXrSeriousIllegalPersonRemListService;
import com.chinaweal.aiccs.aiccs.system.entity.TRBaseCode;
import com.chinaweal.aiccs.aiccs.system.service.TRBaseCodeService;
import com.chinaweal.aiccs.aiccs.writs.entity.Tswrittemplate;
import com.chinaweal.aiccs.aiccs.writs.entity.dto.WritTempEntInfoDto;
import com.chinaweal.aiccs.aiccs.writs.service.TswrittemplateService;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.constant.FlowConstant;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.common.util.WorkNoUtil;
import com.chinaweal.aiccs.org.entity.OrgUnits;
import com.chinaweal.aiccs.org.service.AicorgService;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.aicorg.pojo.AICPermission;
import com.chinaweal.youfool.framework.springboot.base.query.BaseQuery;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import com.chinaweal.youfool.framework.sso.util.SSOUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

import static com.chinaweal.aiccs.common.util.WorkNoUtil.WORKNOTYPE_53;

/**
 * 移出严重违法失信自然人名单（业务表） 服务实现类
 *
 * @author zhouxy
 * @since 2025-07-28
 */
@Service
public class XrSeriousIllegalPersonRemListServiceImpl extends ServiceImpl<XrSeriousIllegalPersonRemListMapper, XrSeriousIllegalPersonRemList> implements IXrSeriousIllegalPersonRemListService {

    @Autowired
    private IXrSeriousIllegalPersonListService iXrSeriousIllegalPersonListService;
    @Autowired
    private IXrTaskListService iXrTaskListService;
    @Autowired
    private IXrOpinionService iXrOpinionService;
    @Autowired
    private AicorgService aicorgService;
    @Autowired
    private TRBaseCodeService trBaseCodeService;
    @Autowired
    private TSWritService tsWritService;
    @Autowired
    private TSWorkNoService tsWorkNoService;
    @Autowired
    private TswrittemplateService tswrittemplateService;

    @Override
    public IPage<XrSeriousIllegalPersonRemList> listXrSeriousIllegalPersonRemList(BaseQuery<SeriousIllegalSpeQueryDto> query, AICUser user) {
        SeriousIllegalSpeQueryDto entity = query.getEntity(SeriousIllegalSpeQueryDto.class);
        Page<XrSeriousIllegalPersonRemList> page = new Page<>(query.getCurrent(), query.getSize());

        String areaCode = aicorgService.getOrgnumberByUserLevel(user,false);
        entity.setAreaCode(areaCode);
        if(StringUtils.equals("history",entity.getBusType())){
            return baseMapper.listRecordByOrg(page, entity);
        } else {
            Map<String, AICPermission> aicPermissions = user.getAicPermissions();
            // 权限
            List<String> authList = new ArrayList<>();
            authList.add(user.getPrimaryKey());
            if (aicPermissions.containsKey(AuthEnum.XR_HANDLE.getTsPermissionCode())) {
                authList.add(user.getRegionID() + ":" + AuthEnum.XR_HANDLE.getCode());
            }
            entity.setAuthList(authList);
            entity.setBusStatus("0");
            return baseMapper.listTodoByOrg(page, entity);
        }
    }

    @Override
    public XrTaskListVo saveIvdAccept(PersonSpeSaveIvdDto personSpeSaveIvdDto, AICUser user) {
        LambdaQueryWrapper<XrSeriousIllegalPersonList> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XrSeriousIllegalPersonList::getOperationStatus, '0');
        if(StringUtils.isNotEmpty(personSpeSaveIvdDto.getIllegalListId())){
            queryWrapper.eq(XrSeriousIllegalPersonList::getIllegalListId, personSpeSaveIvdDto.getIllegalListId());
        } else {
            queryWrapper.eq(XrSeriousIllegalPersonList::getCerType, personSpeSaveIvdDto.getCerType())
                    .eq(XrSeriousIllegalPersonList::getCerNo, personSpeSaveIvdDto.getCerNo());
        }
        XrSeriousIllegalPersonList xrSeriousIllegalPersonList = iXrSeriousIllegalPersonListService.getOne(queryWrapper, false);
        if (xrSeriousIllegalPersonList == null) {
            throw new BusinessException("数据为空");
        }

        XrSeriousIllegalPersonRemList xrSeriousIllegalPersonRemList = new XrSeriousIllegalPersonRemList();
        xrSeriousIllegalPersonRemList.setBizSerRemId(UUID.randomUUID().toString())
                .setBizSeqNo(UUID.randomUUID().toString())
                .setIllegalListId(xrSeriousIllegalPersonList.getIllegalListId())
                .setCerType(xrSeriousIllegalPersonList.getCerType())
                .setCerNo(xrSeriousIllegalPersonList.getCerNo())
                .setInv(xrSeriousIllegalPersonList.getInv())
                .setAbnTime(xrSeriousIllegalPersonList.getAbnTime())
                .setApplyTime(LocalDateTime.now())
                .setSerIllRea(xrSeriousIllegalPersonList.getSerIllRea())
                .setAreaCode(user.getRegionID().substring(0, 6))
                .setDecOrg(user.getRegionID())
                .setDecOrgCn(user.getOrgName())
                .setRemSponsorIllegal(user.getPrimaryKey())
                .setStatus("0")
                .setFinished("0")
                .setDisplayed("1")
                .setAddDepId(user.getOrgID())
                .setAddDepName(user.getOrgName());

        XrTaskList xrTaskList = new XrTaskList();
        xrTaskList.setTaskLikeId(UUID.randomUUID().toString())
                .setBizSeqNo(xrSeriousIllegalPersonRemList.getBizSeqNo())
                .setBusName(xrSeriousIllegalPersonRemList.getInv());
        LambdaUpdateWrapper<XrSeriousIllegalPersonList> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(XrSeriousIllegalPersonList::getIsHandling, "1")
                .set(XrSeriousIllegalPersonList::getRemBizSeq, xrSeriousIllegalPersonRemList.getBizSeqNo())
                .eq(XrSeriousIllegalPersonList::getIllegalListId, xrSeriousIllegalPersonList.getIllegalListId());
        iXrSeriousIllegalPersonListService.update(updateWrapper);

        save(xrSeriousIllegalPersonRemList);
        xrTaskList.setApplyOrgId(user.getOrgID());
        xrTaskList.setWorkFlowId(FlowUtil.SERIOUS_REM_WORK_FLOW);
        // 保存待办信息
        iXrTaskListService.startWorkFlowPerson(xrTaskList, new String[]{user.getPrimaryKey()}, null, Arrays.asList(personSpeSaveIvdDto));
        return new XrTaskListVo(xrTaskList.getTaskLikeId(), xrSeriousIllegalPersonRemList.getBizSeqNo(), "");
    }

    @Override
    public void processControl(SeriousIllegalProcessRemDto processRemDto, AICUser user) {
        LambdaQueryWrapper<XrSeriousIllegalPersonRemList> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XrSeriousIllegalPersonRemList::getBizSeqNo, processRemDto.getBizSeqNo());
        XrSeriousIllegalPersonRemList xrSeriousIllegalPersonRemList = getOne(queryWrapper);
        if (xrSeriousIllegalPersonRemList == null) {
            throw new BusinessException("暂无数据");
        }
        LambdaQueryWrapper<XrTaskList> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(XrTaskList::getBizSeqNo, xrSeriousIllegalPersonRemList.getBizSeqNo());
        XrTaskList xrTaskList = iXrTaskListService.getOne(queryWrapper1);

        if (StringUtils.equals(FlowConstant.LINK_TYPE_EXAMINE, processRemDto.getNextNodeID())) {
            XrSeriousIllegalPersonRemList remList = processRemDto.getXrSeriousIllegalPersonRemList();
            //保存文书模板
            tswrittemplateService.savePersonRemTemplates(remList);
            remList.setBizSerRemId(xrSeriousIllegalPersonRemList.getBizSerRemId())
                    .setAreaCode(xrSeriousIllegalPersonRemList.getAreaCode());
            xrSeriousIllegalPersonRemList = remList;
            // 审批流程中把状态设置成 "审核中"
            xrSeriousIllegalPersonRemList.setStatus("1");
            TRBaseCode trbasecode;
            QueryWrapper<TRBaseCode> queryBaWrapper = new QueryWrapper<>();
            queryBaWrapper.lambda().eq(TRBaseCode::getCode, xrSeriousIllegalPersonRemList.getRemExcpRes())
                    .eq(TRBaseCode::getCodeid, "CD74");
            trbasecode = trBaseCodeService.getOne(queryBaWrapper);
            xrSeriousIllegalPersonRemList.setRemExcpResCn(trbasecode.getName());
//            //判断是否是从年报推过来的信用修复
//            xrTaskList = iXrTaskListService.checkNBXrTask(xrTaskList);
        } else if (StringUtils.equals(FlowConstant.LINK_TYPE_APPROVE, processRemDto.getNextNodeID())) {
            // 审核提交，下一步审审批
            // 审批流程中把状态设置成 "审批"
            xrSeriousIllegalPersonRemList.setStatus("2");
        } else if (StringUtils.equals(FlowConstant.LINK_TYPE_END, processRemDto.getNextNodeID())) {
            // 审批提交，结束业务
            // 审批流程中把状态设置成 "通过"
            xrSeriousIllegalPersonRemList.setStatus("3");
            //业务完成
            xrSeriousIllegalPersonRemList.setFinished("1");
            xrSeriousIllegalPersonRemList.setRemDate(LocalDate.now());
            // 移出严重违法
            xrTaskList.setBusStatus(BaseDataConstant.BUSINESS_STATUS_END);
            toEndRemList(xrSeriousIllegalPersonRemList,user);
//            //判断是否是从年报推过来的信用修复
//            xrTaskList = iXrTaskListService.checkNBXrTask(xrTaskList);
        } else if (StringUtils.equals(FlowConstant.LINK_TYPE_NULLIFY, processRemDto.getNextNodeID())) {
            // 审批流程中把状态设置成 "不通过"
            xrSeriousIllegalPersonRemList.setStatus(FlowConstant.LINK_STATUS_FIVE).setFinished("1");
            LambdaQueryWrapper<XrSeriousIllegalPersonList> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(XrSeriousIllegalPersonList::getIllegalListId, xrSeriousIllegalPersonRemList.getIllegalListId());
            XrSeriousIllegalPersonList xrSeriousIllegalPersonList = iXrSeriousIllegalPersonListService.getOne(queryWrapper2);
            xrSeriousIllegalPersonList.setIsHandling("0");
            iXrSeriousIllegalPersonListService.saveOrUpdate(xrSeriousIllegalPersonList);
            if (processRemDto.getOpinion() != null) {
                xrSeriousIllegalPersonRemList.setBackProposal(processRemDto.getOpinion().getOpinionContent());
            }
        } else if (StringUtils.equals(FlowConstant.LINK_TYPE_EXAMINE_FINISH, processRemDto.getNextNodeID())
                || StringUtils.equals(FlowConstant.LINK_TYPE_APPROVE_FINISH, processRemDto.getNextNodeID())) {
            // 审批流程中把状态设置成 "作废"
            xrSeriousIllegalPersonRemList.setStatus("4");
            xrSeriousIllegalPersonRemList.setBackProposal(processRemDto.getOpinion().getOpinionContent());
            xrSeriousIllegalPersonRemList.setFinished("1");
        } else if (StringUtils.equals(FlowConstant.LINK_TYPE_EXAMINE_RETURN, processRemDto.getNextNodeID())) {
            xrSeriousIllegalPersonRemList.setStatus(FlowConstant.LINK_STATUS_ONE);
        } else if (StringUtils.equals(FlowConstant.LINK_TYPE_HANDLE_RETURN, processRemDto.getNextNodeID())) {
            xrSeriousIllegalPersonRemList.setStatus(FlowConstant.LINK_STATUS_ZERO);
        } else if (StringUtils.equals(FlowConstant.LINK_TYPE_REPLENISH, processRemDto.getNextNodeID())) { // 材料补正
            processRemDto.setNextPerformerIds(new String[]{user.getPrimaryKey()});
            xrSeriousIllegalPersonRemList.setStatus(FlowConstant.LINK_STATUS_FOUR);    //材料补正视作不通过
//            xrSeriousIllegalPersonRemList.setBackProposal(processRemDto.getXrSeriousIllegalRemList().getBackProposal());
            xrSeriousIllegalPersonRemList.setIsAccept("2");
            xrSeriousIllegalPersonRemList.setApprovalDate(LocalDate.now());
            xrSeriousIllegalPersonRemList.setFinished("1");
            xrTaskList.setBusStatus(BaseDataConstant.BUSINESS_STATUS_END);
//            //判断是否是从年报推过来的信用修复
//            xrTaskList = iXrTaskListService.checkNBXrTask(xrTaskList);
        }
        xrSeriousIllegalPersonRemList.setRemSponsorIllegal(user.getPrimaryKey());
        saveOrUpdate(xrSeriousIllegalPersonRemList);
        iXrTaskListService.updateWorkFlow(processRemDto.getOpinion(), xrTaskList,
                processRemDto.getNextNodeID(), processRemDto.getNextPerformerIds(), null);
    }

    private void toEndRemList(XrSeriousIllegalPersonRemList xrSeriousIllegalPersonRemList, AICUser user){
        XrSeriousIllegalPersonList xrSeriousIllegalPersonList = iXrSeriousIllegalPersonListService.getById(xrSeriousIllegalPersonRemList.getIllegalListId());
        if (xrSeriousIllegalPersonList == null) {
            throw new BusinessException("严重违法失信自然人名单表数据为空");
        }
        xrSeriousIllegalPersonList.setRemExcpRes(xrSeriousIllegalPersonRemList.getRemExcpRes());
        TRBaseCode trBaseCode = trBaseCodeService.getOne(new LambdaQueryWrapper<TRBaseCode>()
                .eq(TRBaseCode::getCode, xrSeriousIllegalPersonRemList.getRemExcpRes())
                .eq(TRBaseCode::getCodeid, "CD74"));
        if (trBaseCode != null) {
            xrSeriousIllegalPersonList.setRemExcpResCn(trBaseCode.getName());
        }
        xrSeriousIllegalPersonList.setLostCreditExplainRem(xrSeriousIllegalPersonRemList.getLostCreditExplainRem())
                .setRemSponsorIllegal(xrSeriousIllegalPersonRemList.getRemSponsorIllegal())
                .setIsHandling("0")
                .setOperationStatus("1")
                .setDisplayed("1")
                .setRemDate(LocalDate.now())
                .setDisplayed("1");
        //判断列入机关，若是所一级，则改为其上级单位，即区县一级
        xrSeriousIllegalPersonList = iXrSeriousIllegalPersonListService.checkDecOrg(xrSeriousIllegalPersonList,user.getOrgID(),1);

        String remWritId = tsWorkNoService.generateSeriousIncludeDocNo(xrSeriousIllegalPersonRemList.getAreaCode());
        Tswrittemplate tswrittemplate = tswrittemplateService
                .getOne(new LambdaQueryWrapper<Tswrittemplate>()
                        .eq(Tswrittemplate::getBizseq, xrSeriousIllegalPersonRemList.getBizSeqNo()), false);
        if (tswrittemplate != null) {
            TSWrit tsWrit = new TSWrit();
            tsWrit.setWritsid(remWritId)
                    .setBizseq(tswrittemplate.getBizseq())
                    .setWritstype(tswrittemplate.getWritsType())
                    .setWritsname(WorkNoUtil.getWorkNoTypeName(tswrittemplate.getWritsType()))
                    .setPripid(xrSeriousIllegalPersonRemList.getCerNo())
                    .setContent(tswrittemplate.getContent())
                    .setAreaCode(xrSeriousIllegalPersonRemList.getAreaCode());
            tsWritService.save(tsWrit);
        }
        xrSeriousIllegalPersonList.setRemWritId(remWritId);

        saveOrUpdate(xrSeriousIllegalPersonRemList);
        iXrSeriousIllegalPersonListService.saveOrUpdate(xrSeriousIllegalPersonList);
    }

    @Override
    public ApprovalFormDto getApprovalFormByBizSeqNo(String bizSeqNo, String cerNo, String bizSerRemId) {
        ApprovalFormDto approvalFormDto = new ApprovalFormDto();
        LambdaQueryWrapper<XrSeriousIllegalPersonRemList> queryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(bizSerRemId)){
            queryWrapper.eq(XrSeriousIllegalPersonRemList::getBizSerRemId, bizSerRemId);
        } else {
            queryWrapper.eq(XrSeriousIllegalPersonRemList::getBizSeqNo, bizSeqNo)
                    .eq(XrSeriousIllegalPersonRemList::getCerNo, cerNo);
        }

        XrSeriousIllegalPersonRemList xrSeriousIllegalPersonRemList = getOne(queryWrapper);
        LambdaQueryWrapper<XrTaskList> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(XrTaskList::getBizSeqNo, bizSeqNo);
        XrTaskList one = iXrTaskListService.getOne(queryWrapper1);
        List<XrOpinion> data = iXrOpinionService.list(new LambdaQueryWrapper<XrOpinion>()
                .eq(XrOpinion::getTaskListId, one.getTaskLikeId()).orderByDesc(XrOpinion::getUpdateTime));
        BeanUtils.copyProperties(xrSeriousIllegalPersonRemList, approvalFormDto);
        AICUser user = SSOUtil.getUser();
        approvalFormDto.setAreaName(user.getOrgName());
        approvalFormDto.setInv(xrSeriousIllegalPersonRemList.getInv());
        approvalFormDto.setCerNo(xrSeriousIllegalPersonRemList.getCerNo());
        approvalFormDto.setOpinion(data);

        String lostCreditExplain = "";
        TRBaseCode trbasecode = trBaseCodeService.getOne(new LambdaQueryWrapper<TRBaseCode>()
                .eq(TRBaseCode::getCode, xrSeriousIllegalPersonRemList.getRemExcpRes())
                .eq(TRBaseCode::getCodeid, "CD74"));
        if(trbasecode != null){
            lostCreditExplain = trbasecode.getName();
        } else {
            lostCreditExplain = xrSeriousIllegalPersonRemList.getRemExcpResCn();
        }
        //用该字段存移出原因
        approvalFormDto.setLostCreditExplain(lostCreditExplain);

        //信誉是否修复文书
        HashMap<String, Object> map = new HashMap<>();
        LambdaQueryWrapper<TSWrit> tsWritLambdaQueryWrapper = new LambdaQueryWrapper<>();
        tsWritLambdaQueryWrapper.eq(TSWrit::getBizseq, bizSeqNo)
                .eq(TSWrit::getPripid, cerNo)
                .in(TSWrit::getWritstype, "p2","p3");
        TSWrit tsWritRepair = tsWritService.getOne(tsWritLambdaQueryWrapper,false);
        if (tsWritRepair != null) {
            map.put("writsNo", tsWritRepair.getWritsno());
            map.put("abnTime", xrSeriousIllegalPersonRemList.getAbnTime());
            map.put("writTime", tsWritRepair.getCreatetime());
            if (tsWritRepair.getContent() != null) {
                map.put("content", tsWritRepair.getContent());
            } else {
//                WritTempEntInfoDto writTempEntInfoDto = new WritTempEntInfoDto();
//                writTempEntInfoDto.setBizseq(xrSeriousIllegalPersonRemList.getBizSeqNo());
//                Tswrittemplate template = tswrittemplateService.getTemplateTwo(writTempEntInfoDto);
//                map.put("content", template.getContent());
                map.put("content", "");
            }

            map.put("writsName", tsWritRepair.getWritsname());
            String areaName = user.getOrgName();
            OrgUnits orgunits = aicorgService.getOne(new LambdaQueryWrapper<OrgUnits>()
                    .eq(OrgUnits::getOrgUnitId, user.getOrgID()));
            //若当前单位是所级则显示其区局
            if(orgunits.getOrgLevel() >= 5){
                OrgUnits parentOrg = aicorgService.getOne(new LambdaQueryWrapper<OrgUnits>()
                        .eq(OrgUnits::getOrgNumber,StringUtils.substring(user.getRegionID(),0,6)+"000")
                        .eq(OrgUnits::getDeleted, "0"));
                areaName = parentOrg.getOrgUnitName();
            }
            if (areaName.contains("市场监督管理局")) {
                areaName = areaName.substring(0,areaName.indexOf("市场监督管理局"));
            }
            map.put("areaName", areaName);
            map.put("WritsType", tsWritRepair.getWritstype());
            approvalFormDto.setRepairMap(map);
        }
        return approvalFormDto;
    }

}
