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.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.Gzaiccode;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSWrit;
import com.chinaweal.aiccs.aiccs.abnormal.service.IGzaiccodeService;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSWritService;
import com.chinaweal.aiccs.aiccs.business.entity.XrOpinion;
import com.chinaweal.aiccs.aiccs.business.entity.dto.ApprovalFormDto;
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.XrSeriousIllegalPersonSpeList;
import com.chinaweal.aiccs.aiccs.business.entity.XrTaskList;
import com.chinaweal.aiccs.aiccs.seriousillegalPerson.entity.dto.PersonSpeSaveIvdDto;
import com.chinaweal.aiccs.aiccs.seriousillegalPerson.entity.dto.SeriousIllegalProcessDto;
import com.chinaweal.aiccs.aiccs.seriousillegalPerson.entity.dto.SeriousIllegalSpeQueryDto;
import com.chinaweal.aiccs.aiccs.business.entity.vo.XrTaskListVo;
import com.chinaweal.aiccs.aiccs.seriousillegalPerson.mapper.XrSeriousIllegalPersonSpeListMapper;
import com.chinaweal.aiccs.aiccs.seriousillegalPerson.service.IXrSeriousIllegalPersonListService;
import com.chinaweal.aiccs.aiccs.seriousillegalPerson.service.IXrSeriousillegalPersonSpeListService;
import com.chinaweal.aiccs.aiccs.system.entity.TRBaseCode;
import com.chinaweal.aiccs.aiccs.system.service.TRBaseCodeService;
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.context.annotation.Lazy;
import org.springframework.stereotype.Service;

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

/**
 * 列入严重违法失信自然人名单 服务实现类
 *
 * @author zhouxy
 * @since 2025-07-24
 */
@Service
public class XrSeriousIllegalPersonSpeListServiceImpl extends ServiceImpl<XrSeriousIllegalPersonSpeListMapper, XrSeriousIllegalPersonSpeList> implements IXrSeriousillegalPersonSpeListService {

    @Autowired
    private AicorgService aicorgService;
    @Autowired
    private IXrTaskListService iXrTaskListService;
    @Autowired
    private TRBaseCodeService trBaseCodeService;
    @Autowired
    private IXrSeriousIllegalPersonListService iXrSeriousIllegalPersonListService;
    @Autowired
    private TSWorkNoService tsWorkNoService;
    @Autowired
    private TSWritService tsWritService;
    @Resource
    @Lazy
    private IGzaiccodeService iGzaiccodeService;
    @Autowired
    private IXrOpinionService iXrOpinionService;

    @Override
    public IPage<XrSeriousIllegalPersonSpeList> listXrSeriousIllegalPersonSpeList(BaseQuery<SeriousIllegalSpeQueryDto> query, AICUser user) {
        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());
        }
        SeriousIllegalSpeQueryDto entity = query.getEntity(SeriousIllegalSpeQueryDto.class);
        entity.setAuthList(authList);
        IPage<XrSeriousIllegalPersonSpeList> xrSeriousIllegalPersonSpeListIPage;
        Page<XrSeriousIllegalPersonSpeList> page = new Page<>(query.getCurrent(), query.getSize());
        if (Objects.equals(entity.getBusType(), "todo")) {  //待办
            entity.setBusStatus("0");
            xrSeriousIllegalPersonSpeListIPage = baseMapper.selectXrSeriousIllegalPersonSpeListTodo(page, entity);
        } else if (Objects.equals(entity.getBusType(), "history")) {    //记录
            String areaCode = aicorgService.getOrgnumberByUserLevel(user,false);
            entity.setAreaCode(areaCode);
            xrSeriousIllegalPersonSpeListIPage = baseMapper.selectXrSeriousIllegalPersonSpeListHistory(page, entity);
        } else {
            throw new BusinessException("查询列表类型错误，请联系管理员处理");
        }
        return xrSeriousIllegalPersonSpeListIPage;
    }

    @Override
    public XrTaskListVo saveIvdAcceptList(PersonSpeSaveIvdDto speSaveIvdDto, AICUser user) {
        XrSeriousIllegalPersonSpeList xrSeriousIllegalPersonSpeList = new XrSeriousIllegalPersonSpeList();
        xrSeriousIllegalPersonSpeList.setIllegalListId(UUID.randomUUID().toString())
                .setBizSeqNo(UUID.randomUUID().toString())
                .setInv(speSaveIvdDto.getInv())
                .setCerType(speSaveIvdDto.getCerType())
                .setCerNo(speSaveIvdDto.getCerNo())
                .setAreaCode(user.getRegionID().substring(0, 6))
                .setLaupTime(LocalDateTime.now())
                .setIntoSponsorIllegal(user.getPrimaryKey())
                .setAddDepId(user.getOrgID())
                .setAddDepName(user.getOrgName())
                .setStatus("0")
                .setFinished("0")
                .setApprove("0")
                .setBusType("penalty")
                .setDisplayed("1");
        XrTaskList xrTaskList = new XrTaskList();
        xrTaskList.setTaskLikeId(UUID.randomUUID().toString());
        xrTaskList.setBizSeqNo(xrSeriousIllegalPersonSpeList.getBizSeqNo());
        xrTaskList.setAreaCode(user.getRegionID().substring(0, 6));
        xrTaskList.setBusName(xrSeriousIllegalPersonSpeList.getInv());
        xrTaskList.setApplyOrgId(user.getOrgID());
        xrTaskList.setWorkFlowId(FlowUtil.SUCCESSFUL_FLOW_TWO);
        save(xrSeriousIllegalPersonSpeList);
        // 保存待办信息
        iXrTaskListService.startWorkFlowPerson(xrTaskList, new String[]{user.getPrimaryKey()}, null, Arrays.asList(speSaveIvdDto));
        return new XrTaskListVo(xrTaskList.getTaskLikeId(), xrSeriousIllegalPersonSpeList.getBizSeqNo(), "");
    }

    @Override
    public void processControl(SeriousIllegalProcessDto seriousIllegalProcessDto, AICUser user) {
        XrTaskList xrTaskList = iXrTaskListService.getOne(new LambdaQueryWrapper<XrTaskList>().eq(XrTaskList::getBizSeqNo, seriousIllegalProcessDto.getBizSeqNo()));
        LambdaQueryWrapper<XrSeriousIllegalPersonSpeList> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XrSeriousIllegalPersonSpeList::getBizSeqNo, seriousIllegalProcessDto.getBizSeqNo());
        List<XrSeriousIllegalPersonSpeList> xrSeriousIllegalPersonSpeLists = list(queryWrapper);
        if (xrSeriousIllegalPersonSpeLists.isEmpty()) {
            throw new BusinessException("暂无数据");
        }
        LocalDateTime localDateTime = LocalDateTime.now();
        TRBaseCode trbasecode;

        for (XrSeriousIllegalPersonSpeList xrSeriousIllegalPersonSpeList : xrSeriousIllegalPersonSpeLists) {
            XrSeriousIllegalPersonSpeList personSpeList = seriousIllegalProcessDto.getPersonSpeList();
            switch (seriousIllegalProcessDto.getNextNodeID()) {
                case FlowConstant.LINK_TYPE_EXAMINE:
                    personSpeList.setIllegalListId(xrSeriousIllegalPersonSpeList.getIllegalListId());
                    // 保存值
                    xrSeriousIllegalPersonSpeList = personSpeList;
                    QueryWrapper<TRBaseCode> queryBaWrapper = new QueryWrapper<>();
                    queryBaWrapper.lambda().eq(TRBaseCode::getCode, personSpeList.getSerillRea())
                            .eq(TRBaseCode::getCodeid, "CD73");
                    trbasecode = trBaseCodeService.getOne(queryBaWrapper);
                    xrSeriousIllegalPersonSpeList.setSerillReaString(trbasecode.getName());
                    xrSeriousIllegalPersonSpeList.setAbnTime(personSpeList.getAbnTime() == null ?
                                    LocalDate.now() : personSpeList.getAbnTime());
                    xrSeriousIllegalPersonSpeList.setSerillRea(personSpeList.getSerillRea());
                    xrSeriousIllegalPersonSpeList.setLostCreditExplain(personSpeList.getLostCreditExplain());
                    xrSeriousIllegalPersonSpeList.setStatus(FlowConstant.LINK_STATUS_ONE); // 审批流程中把状态设置成 "审核中"
                    break;
                case FlowConstant.LINK_TYPE_LAW:
                    personSpeList.setIllegalListId(xrSeriousIllegalPersonSpeList.getIllegalListId());
                    // 保存值
                    xrSeriousIllegalPersonSpeList = personSpeList;
                    trbasecode = trBaseCodeService.getOne(new LambdaQueryWrapper<TRBaseCode>()
                            .eq(TRBaseCode::getCode, personSpeList.getSerillRea())
                            .eq(TRBaseCode::getCodeid, "CD73"));
                    xrSeriousIllegalPersonSpeList.setSerillReaString(trbasecode.getName())
                            .setAbnTime(personSpeList.getAbnTime() == null ?
                                    LocalDate.now() : personSpeList.getAbnTime());
                    xrSeriousIllegalPersonSpeList.setSerillRea(personSpeList.getSerillRea());
                    xrSeriousIllegalPersonSpeList.setLostCreditExplain(personSpeList.getLostCreditExplain());
                    xrSeriousIllegalPersonSpeList.setStatus(FlowConstant.LINK_STATUS_SEVEN);
                    break;
                case FlowConstant.LINK_TYPE_APPROVE:
                    xrSeriousIllegalPersonSpeList.setStatus(FlowConstant.LINK_STATUS_TWO); // 审批流程中把状态设置成 "审批"
                    break;
                case FlowConstant.LINK_TYPE_UP_EXAMINE:
                    xrSeriousIllegalPersonSpeList.setStatus(FlowConstant.LINK_STATUS_ONE); // 行政处罚需要上级审批
                    break;
                case FlowConstant.LINK_TYPE_END:
                    xrSeriousIllegalPersonSpeList.setStatus(FlowConstant.LINK_STATUS_THREE); // 审批流程中把状态设置成 "通过"
                    xrSeriousIllegalPersonSpeList.setDisplayed("1");
                    xrSeriousIllegalPersonSpeList.setFinished("1");
                    toEndSeriouslyList(xrSeriousIllegalPersonSpeList, user);
                    break;
                case FlowConstant.LINK_TYPE_NULLIFY:
                    xrSeriousIllegalPersonSpeList.setStatus(FlowConstant.LINK_STATUS_FIVE); // 审批流程中把状态设置成 "不通过"
                    xrSeriousIllegalPersonSpeList.setFinished("1");
                    if (seriousIllegalProcessDto.getOpinion() != null) {
                        xrSeriousIllegalPersonSpeList.setEndReason(seriousIllegalProcessDto.getOpinion().getOpinionContent());
                    }
                    xrSeriousIllegalPersonSpeList.setEndApply("2");
                    break;
                case FlowConstant.LINK_TYPE_EXAMINE_FINISH:
                case FlowConstant.LINK_TYPE_APPROVE_FINISH:
                case FlowConstant.LINK_TYPE_LAW_FINISH:
                case FlowConstant.LINK_TYPE_UP_EXAMINE_FINISH:
                case FlowConstant.LINK_TYPE_UP_APPROVE_FINISH:
                    xrSeriousIllegalPersonSpeList.setStatus(FlowConstant.LINK_STATUS_FOUR); // 审批流程中把状态设置成 "作废"
                    xrSeriousIllegalPersonSpeList.setEndReason(seriousIllegalProcessDto.getOpinion().getOpinionContent());
                    xrSeriousIllegalPersonSpeList.setFinished("1");
                    break;
                case FlowConstant.LINK_TYPE_EXAMINE_RETURN:
                    xrSeriousIllegalPersonSpeList.setStatus(FlowConstant.LINK_STATUS_ONE);
                    break;
                case FlowConstant.LINK_TYPE_HANDLE_RETURN:
                    xrSeriousIllegalPersonSpeList.setStatus(FlowConstant.LINK_STATUS_ZERO);
                    break;
                case FlowConstant.LINK_TYPE_LAW_RETURN:
                    xrSeriousIllegalPersonSpeList.setStatus(FlowConstant.LINK_STATUS_SEVEN);
                    break;
                default:
                    break;
            }
            xrSeriousIllegalPersonSpeList.setLaupTime(localDateTime);
            xrSeriousIllegalPersonSpeList.setIntoSponsorIllegal(user.getPrimaryKey());
            saveOrUpdate(xrSeriousIllegalPersonSpeList);
        }
        iXrTaskListService.updateWorkFlow(seriousIllegalProcessDto.getOpinion(), xrTaskList,
                seriousIllegalProcessDto.getNextNodeID(), seriousIllegalProcessDto.getNextPerformerIds(), null);

    }

    /**
     * 文书生成
     */
    private void toEndSeriouslyList(XrSeriousIllegalPersonSpeList xrSeriousIllegalPersonSpeList, AICUser user) {
        XrSeriousIllegalPersonList xrSeriousIllegalPersonList = new XrSeriousIllegalPersonList();
        xrSeriousIllegalPersonList.setIllegalListId(UUID.randomUUID().toString())
                .setBizSeq(xrSeriousIllegalPersonSpeList.getBizSeqNo())
                .setInv(xrSeriousIllegalPersonSpeList.getInv())
                .setCerType(xrSeriousIllegalPersonSpeList.getCerType())
                .setCerNo(xrSeriousIllegalPersonSpeList.getCerNo())
                .setSerIllRea(xrSeriousIllegalPersonSpeList.getSerillRea())
                .setSerIllReaCn(xrSeriousIllegalPersonSpeList.getSerillReaString())
                .setAbnTime(LocalDate.now());
        //判断列入机关，若是所一级，则改为其上级单位，即区县一级
        xrSeriousIllegalPersonList = iXrSeriousIllegalPersonListService.checkDecOrg(xrSeriousIllegalPersonList,user.getOrgID(),0);
        xrSeriousIllegalPersonList.setAreaCode(user.getRegionID().substring(0, 6))
                .setLostCreditExplain(xrSeriousIllegalPersonSpeList.getLostCreditExplain())
                .setIntoSponsorIllegal(user.getName())
                .setIntoSponsorIllegalId(user.getPrimaryKey())
                .setRemSponsorIllegal(xrSeriousIllegalPersonSpeList.getIntoSponsorIllegal())
                .setOperationStatus("0")
                .setIsHea(xrSeriousIllegalPersonSpeList.getIsHea())
                .setHeaOp(xrSeriousIllegalPersonSpeList.getHeaOp())
                .setJudDocNo(xrSeriousIllegalPersonSpeList.getJudDocNo())
                .setJudDocTitle(xrSeriousIllegalPersonSpeList.getJudDocTitle())
                .setDisplayed("1")//列入记录公示1：是 0：否
                .setIsHandling("0");

        //4.生成文书号
        TSWrit tsWritModel = new TSWrit();
        String tswritId = UUID.randomUUID().toString();
        tsWritModel.setWritsid(tswritId);
        String workNoType = WorkNoUtil.WORKNOTYPE_21;//列入严重违法失信名单 决定书文号
        tsWritModel.setWritsno(tsWorkNoService.generateSeriousIncludeDocNo(xrSeriousIllegalPersonSpeList.getAreaCode()));
        tsWritModel.setWritsname(WorkNoUtil.getWorkNoTypeName(workNoType));
        tsWritModel.setContent("当事人："+xrSeriousIllegalPersonSpeList.getInv() +
                "\n证件号码：" + xrSeriousIllegalPersonSpeList.getCerNo() +
                "\n" + xrSeriousIllegalPersonSpeList.getLostCreditExplain()
                + includeDocumentLastText(xrSeriousIllegalPersonSpeList));
        tsWritModel.setBizseq(xrSeriousIllegalPersonSpeList.getBizSeqNo());
        tsWritModel.setWritstype(workNoType);
        tsWritModel.setCreatetime(LocalDateTime.now());
        tsWritModel.setAreaCode(xrSeriousIllegalPersonSpeList.getAreaCode());
        tsWritService.save(tsWritModel);
        xrSeriousIllegalPersonSpeList.setWritsNo(tsWritModel.getWritsno())
                .setDecOrg(xrSeriousIllegalPersonList.getDecOrg())
                .setDecOrgCn(xrSeriousIllegalPersonList.getDecOrgCn());
        saveOrUpdate(xrSeriousIllegalPersonSpeList);
        xrSeriousIllegalPersonList.setIntoWritId(tswritId);//严重违法表里保存列入文书id
        iXrSeriousIllegalPersonListService.save(xrSeriousIllegalPersonList);
    }

    /**
     * 列入决定文书最后内容
     */
    private String includeDocumentLastText(XrSeriousIllegalPersonSpeList xrSeriousIllegalPersonSpeList) {
        LocalDate term = xrSeriousIllegalPersonSpeList.getAbnTime().plusYears(3);
        //查出区划和地市用于拼接复议诉讼机关
        String decOrgCity = StringUtils.substring(xrSeriousIllegalPersonSpeList.getAreaCode(), 0, 4) + "00";
        Gzaiccode basecodeCity = iGzaiccodeService.getOne(new LambdaQueryWrapper<Gzaiccode>()
                .eq(Gzaiccode::getScountrycode, decOrgCity));

        //行政复议机关
        String reconsiderationOrg = StringUtils.isEmpty(xrSeriousIllegalPersonSpeList.getReconsiderationOrg()) ? basecodeCity.getScountryextcode()+"人民政府" : xrSeriousIllegalPersonSpeList.getReconsiderationOrg();
        //诉讼机关
        String litiOrg = StringUtils.isEmpty(xrSeriousIllegalPersonSpeList.getLitiOrg()) ? basecodeCity.getScountryextcode()+"人民法院" : xrSeriousIllegalPersonSpeList.getLitiOrg();
        String text = "，现决定将你（单位）列入严重违法失信名单，通过国家企业信用信息公示系统向社会公示，并实施相应管理措施。列入期限自即日起至"
                + term.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日")) +
                "。期满一年后，你（单位）可依据《市场监督管理严重违法失信名单管理办法》第十六条、第十七条规定向我局申请提前移出严重违法失信名单，停止公示相关信息并解除相应管理措施。" +
                "\n你（单位）如不服本决定，可以自收到本决定书之日起六十日内向" +
                reconsiderationOrg + "申请行政复议；也可以在六个月内向" +
                litiOrg + "提起行政诉讼。";
        return text;
    }

    @Override
    public ApprovalFormDto getApprovalFormByBizSeqNo(String bizSeqNo, String cerNo, String illegalListId) {
        ApprovalFormDto approvalFormDto = new ApprovalFormDto();
        LambdaQueryWrapper<XrSeriousIllegalPersonSpeList> queryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(illegalListId)){
            queryWrapper.eq(XrSeriousIllegalPersonSpeList::getIllegalListId,illegalListId);
        } else {
            queryWrapper.eq(XrSeriousIllegalPersonSpeList::getBizSeqNo, bizSeqNo)
                    .eq(XrSeriousIllegalPersonSpeList::getCerNo, cerNo).last("limit 1");
        }
        XrSeriousIllegalPersonSpeList seriousIllegalPersonSpeList = getOne(queryWrapper);

        XrTaskList xrTaskList = iXrTaskListService.getOne(new QueryWrapper<XrTaskList>().lambda().eq(XrTaskList::getBizSeqNo, bizSeqNo));
        List<XrOpinion> data = this.iXrOpinionService.list(new LambdaQueryWrapper<XrOpinion>()
                .eq(XrOpinion::getTaskListId,xrTaskList.getTaskLikeId())
                .orderByDesc(XrOpinion::getUpdateTime));
        BeanUtils.copyProperties(seriousIllegalPersonSpeList, approvalFormDto);
        AICUser user = SSOUtil.getUser();
        approvalFormDto.setAreaName(user.getOrgName());
        approvalFormDto.setOpinion(data);

        String lostCreditExplain = "";
        TRBaseCode trBaseCode = trBaseCodeService.getOne(new LambdaQueryWrapper<TRBaseCode>()
                .eq(TRBaseCode::getCode, seriousIllegalPersonSpeList.getSerillRea())
                .eq(TRBaseCode::getCodeid, "CD73"));
        if(trBaseCode != null){
            lostCreditExplain = trBaseCode.getName();
        } else {
            lostCreditExplain = seriousIllegalPersonSpeList.getSerillReaString();
        }
        //用该字段存移出原因
        approvalFormDto.setLostCreditExplain(lostCreditExplain);

        //列入决定书
        TSWrit writ = tsWritService.getOne(new LambdaQueryWrapper<TSWrit>()
                .eq(TSWrit::getWritstype, WorkNoUtil.WORKNOTYPE_21)
                .eq(TSWrit::getBizseq, seriousIllegalPersonSpeList.getBizSeqNo()));
        HashMap<String, Object> incAbnDecision = new HashMap<>();
        approvalFormDto.setIncAbnDecisionMap(incAbnDecision);
        if (writ != null) {
            incAbnDecision.put("writsNo", writ.getWritsno());
            incAbnDecision.put("abnTime", writ.getCreatetime());
            incAbnDecision.put("content", writ.getContent());
            String areaName = user.getOrgName();
            if (areaName.contains("市场监督管理局")) {
                areaName = areaName.substring(0,areaName.indexOf("市场监督管理局"));
            }
            incAbnDecision.put("areaName", areaName);
            incAbnDecision.put("WritsType", writ.getWritstype());
            incAbnDecision.put("inv", seriousIllegalPersonSpeList.getInv());
            incAbnDecision.put("cerNo", seriousIllegalPersonSpeList.getCerNo());
            approvalFormDto.setIncAbnDecisionMap(incAbnDecision);
        }
        return approvalFormDto;
    }

}
