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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chinaweal.aiccs.aiccs.abnormal.entity.*;
import com.chinaweal.aiccs.aiccs.abnormal.service.*;
import com.chinaweal.aiccs.aiccs.auditing.entity.TSOpinion;
import com.chinaweal.aiccs.aiccs.business.entity.BizCorrections;
import com.chinaweal.aiccs.aiccs.business.entity.TSTaskList;
import com.chinaweal.aiccs.aiccs.business.mapper.BizCorrectionsMapper;
import com.chinaweal.aiccs.aiccs.business.service.BizCorrectionsService;
import com.chinaweal.aiccs.aiccs.business.service.TSTaskListService;
import com.chinaweal.aiccs.aiccs.revoke.entity.BizRevEnt;
import com.chinaweal.aiccs.aiccs.revoke.entity.Revokelist;
import com.chinaweal.aiccs.aiccs.revoke.service.BizRevEntService;
import com.chinaweal.aiccs.aiccs.revoke.service.RevokelistService;
import com.chinaweal.aiccs.aiccs.revoke.service.TsbizrevlistService;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSBizSerIllegal;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSSerIllegalList;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSBizSerIllegalService;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSSerIllegalListService;
import com.chinaweal.aiccs.aiccs.system.entity.TRBaseCode;
import com.chinaweal.aiccs.aiccs.system.service.TRBaseCodeService;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.util.*;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.BaseServiceImpl;
import org.apache.commons.collections.CollectionUtils;
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.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 勘误业务记录表 服务实现类
 * </p>
 *
 * @author <a href="https://blog.lroyia.top">lroyia</a>
 * @since 2021-04-25
 */
@Service
public class BizCorrectionsServiceImpl extends BaseServiceImpl<BizCorrectionsMapper, BizCorrections> implements BizCorrectionsService {

    @Autowired
    private TSTaskListService taskListService;
    @Autowired
    private TSAbnListService abnListService;
    @Autowired
    private TSBizSpeListService tsBizSpeListService;
    @Autowired
    private TRBaseCodeService baseCodeService;
    @Autowired
    private TSAttachmentService attachmentService;
    @Autowired
    private TSWritService tsWritService;
    @Autowired
    private TSBizSerIllegalService tsBizSerIllegalService;
    @Autowired
    private TSSerIllegalListService tsSerIllegalListService;

    @Resource
    private RevokelistService revokelistService;
    @Resource
    private BizRevEntService bizRevEntService;
    @Resource
    private TSWritService writService;


    @Override
    public TSTaskList createTask(AICUser curUser, TSTaskList taskList, BizCorrections... corrections) {
        if (StringUtils.isBlank(taskList.getTasklistid())) {
            for (BizCorrections info : corrections) {
                info.setBizseq(taskList.getBizseqid()); // 流程启动人(主办人)
                info.setCreatorId(curUser.getPrimaryKey()); // 流程启动人(主办人)
                info.setState(Constant.TRUE_1_STR); // 流程启动把状态设置为 "处理中"
                saveOrUpdate(info);
            }
            String definedname = FlowUtil.PROBLEM_FEEDBACK_WORKFLOW;//问题上报模版
            //新待办
            taskList = HandleWorkFlowUtil.createTaskList(taskList, curUser);
            //开始工作流
            taskListService.startWorkFlow(taskList, curUser, definedname);
        }
        return taskList;
    }

    @Override
    public TSTaskList nextProcess(AICUser user, TSTaskList taskList, TSOpinion opinionModel, String nextNodeID, String[] nextPerformerids, String[] nextPerformerNames, BizCorrections... corrections) {
        try {
            String state = "1";
            if (FlowUtil.PROBLEM_FEEDBACK_WORKFLOW_OVERFEEDBACK.equals(nextNodeID) || FlowUtil.PROBLEM_FEEDBACK_WORKFLOW_OVERKWFINISH.equals(nextNodeID)) {
                // 不通过
                state = "0";
            } else if (FlowUtil.PROBLEM_FEEDBACK_WORKFLOW_ENDFEEDBACK.equals(nextNodeID)) {
                // 通过
                state = "2";
            }
            Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CD71");
            Map<String, TRBaseCode> illegalCodeMap = baseCodeService.getBaseCodeMapFormCache("CD73");
            LocalDateTime now = LocalDateTime.now();
            for (BizCorrections each : corrections) {
                each.setState(state);
                // 如果通过办结，则更新对应的列入业务信息
                if("2".equals(state)){
                    String busId = each.getBusId();
                    if(Constant.FALSE_0_STR.equals(each.getBustype())){ // 列异勘误
                        //将勘误信息更新到tsabnlist和tsbizspelist
                        TSAbnList tsAbnList = abnListService.getById(busId);
                        tsAbnList.setSpecause(each.getReason());
                        TRBaseCode code = codeMap.get(each.getReason());
                        if (code != null) {
                            tsAbnList.setSpereasons(code.getName());
                        }
                        tsAbnList.setLauptime(now);
                        abnListService.updateById(tsAbnList);

                        TSBizSpeList tsBizSpeList = tsBizSpeListService.getById(busId);
                        tsBizSpeList.setSpecause(each.getReason());
                        tsBizSpeList.setDecisionContent(each.getDecisionContent());
                        tsBizSpeList.setRemark(each.getRemark());
                        tsBizSpeList.setLauptime(now);
                        tsBizSpeList.setCorrectBizseq(each.getBizseq());// 勘误通过，关联上勘误业务号
                        tsBizSpeListService.updateById(tsBizSpeList);
                        // TODO 文书内容的更新
                        String intowritid = tsAbnList.getIntowritid();// 列异文书id
                        if(StringUtils.isNotEmpty(intowritid)){
                            TSWrit tsWrit = new TSWrit();
                            tsWrit.setWritsid(intowritid);
                            tsWrit.setContent(each.getDecisionContent());
                            tsWrit.setLauptime(now);
                            tsWritService.updateById(tsWrit);
                        }

                    } else if (Constant.TRUE_1_STR.equals(each.getBustype())) { // 列严勘误
                        //将勘误信息更新到tsserillegallist 和 tsbizserillegal
                        TSBizSerIllegal bizSerIllegal = new TSBizSerIllegal();
                        bizSerIllegal.setIllegallistid(busId);
                        bizSerIllegal.setSerillrea(each.getReason());
                        bizSerIllegal.setLostcreditexplain(each.getFactDesc());
                        bizSerIllegal.setLauptime(now);
                        bizSerIllegal.setCorrectBizseq(each.getBizseq());// 勘误通过，关联上勘误业务号
                        tsBizSerIllegalService.updateById(bizSerIllegal);

                        TSSerIllegalList serIllegalList = new TSSerIllegalList();
                        serIllegalList.setIllegallistid(busId);
                        serIllegalList.setSerillrea(each.getReason());
                        TRBaseCode code = illegalCodeMap.get(each.getReason());
                        if (code != null) {
                            serIllegalList.setLostcreditexplain(code.getName());
                        }
                        serIllegalList.setLauptime(now);
                        tsSerIllegalListService.updateById(serIllegalList);
                        // 文书内容更新
                        TSSerIllegalList illegalListDB = tsSerIllegalListService.getById(serIllegalList.getIllegallistid());
                        String intowritid = illegalListDB.getIntowritid();
                        if(StringUtils.isNotEmpty(intowritid)) {
                            TSWrit tsWrit = new TSWrit();
                            tsWrit.setWritsid(intowritid);
                            tsWrit.setContent(illegalListDB.getEntname() +
                                    "（统一社会信用代码/注册号："
                                    + (illegalListDB.getUniscid() != null ? illegalListDB.getUniscid() : illegalListDB.getRegno()) + "）："
                                    + illegalListDB.getLostcreditexplain()
                                    + includeDocumentLastText(illegalListDB));
                            tsWrit.setLauptime(now);
                            tsWritService.updateById(tsWrit);
                        }
                    } else if ("2".equals(each.getBustype())) { // 批量吊销勘误
                        Revokelist revokelist = revokelistService.getById(each.getBusId());
                        BizRevEnt bizRevEnt = bizRevEntService.getById(each.getBusId());
                        List<TSWrit> tsWritList = writService.lambdaQuery().eq(TSWrit::getBizseq, bizRevEnt.getBizseq()).eq(TSWrit::getPripid, bizRevEnt.getPripid()).list();
                        // 勘误吊销决定日期
                        if (each.getRevokeDecDate() != null) {
                            revokelist.setRevokedate(each.getRevokeDecDate());
                            TSWrit tsWrit = tsWritList.stream().filter(i -> i.getWritstype().equals(WorkNoUtil.WORKNOTYPE_33)).findFirst().get();
                            tsWrit.setCreatetime(each.getRevokeDecDate());
                            tsWrit.setLauptime(now);
                            revokelist.setLauptime(LocalDateTime.now());
                            writService.updateById(tsWrit);
                            revokelistService.updateById(revokelist);
                        }
                        // 勘误听证公告日期
                        if (each.getRevokeHearDate() != null) {
                            TSWrit tsWrit = tsWritList.stream().filter(i -> i.getWritstype().equals(WorkNoUtil.WORKNOTYPE_32)).findFirst().get();
                            tsWrit.setCreatetime(each.getRevokeHearDate());
                            tsWrit.setLauptime(now);
                            writService.updateById(tsWrit);
                        }
                    }
                }
                if(StringUtils.isNotBlank(each.getCorrectionsId())){
                    updateById(each);
                }
            }
            taskListService.updateWorkFlow(user, opinionModel, taskList, nextNodeID, nextPerformerids, nextPerformerNames);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("勘误流程审核出错");
        }
        return taskList;
    }

    @Override
    public boolean updateBizFile(String correctBizseq, String oldBizseq, String newBizseq, String type) {
        boolean flag = false;
        if(StringUtils.isNotEmpty(oldBizseq) && StringUtils.isNotEmpty(newBizseq)){
            List<TSAttachment> oldFileList = new ArrayList<>();
            if(StringUtils.isNotEmpty(correctBizseq)){// 若勘误过，则拿最新勘误的附件
                TSAttachment attachment = new TSAttachment();
                attachment.setBizseq(correctBizseq);
                attachment.setAttachtype("1");//标记为“1”为勘误流程中的新材料
                oldFileList = attachmentService.selectwritByPage(attachment);
            }else {// 没有则拿列异时的附件
                if(type.equals("abn")) {
                    oldFileList = attachmentService.getAbnIncFileList(oldBizseq);
                }else if (type.equals("illegal")){
                    oldFileList = attachmentService.getIllegalIncFileList(oldBizseq);
                }
            }
            if(CollectionUtils.isEmpty(oldFileList)){// 找不到附件，则没有原材料
                return true;
            }
            for (TSAttachment tsAttachment : oldFileList) {
                // 原材料
                tsAttachment.setAttachmentid(UUID.randomUUID().toString());
                tsAttachment.setBizseq(newBizseq);
                tsAttachment.setAttachtype("0");//标记为“0”作为勘误流程的原材料
                flag = attachmentService.save(tsAttachment);
                if (!flag) throw new BusinessException("更新原材料文件失败");
                // 可增删材料列表
                tsAttachment.setAttachmentid(UUID.randomUUID().toString());
                tsAttachment.setAttachtype("1");//标记为“1”作为勘误流程中的新材料
                flag = attachmentService.save(tsAttachment);
                if (!flag) throw new BusinessException("更新新材料文件失败");
            }
        }

        return flag;
    }

    /**
     * 列入决定文书最后内容
     *
     * @return
     */
    private String includeDocumentLastText(TSSerIllegalList tsSerIllegalList) {
        LocalDate term = tsSerIllegalList.getAbntime().plusYears(3);
        String city = Constant.NM_REGION_CODE.get(tsSerIllegalList.getDecorg().substring(0,4));
        String government = city + "人民政府";
//        if (!tsSerIllegalList.getDecorg().equals("440101")) {
////            LambdaQueryWrapper<Gzaiccode> lqw = Wrappers.lambdaQuery();
////            lqw.eq(Gzaiccode::getScountrycode, tsSerIllegalList.getDecorg());
////            Gzaiccode gzaiccode = iGzaiccodeService.getOne(lqw);
//
//            String shortName = Constant.NM_LOC_REGION_CODE.get(tsSerIllegalList.getDecorg());
//            government = "广州市" + (StringUtils.isEmpty(shortName)? "":shortName) + "人民政府";
//        }
        String text = "，现决定将你（单位）列入严重违法失信名单，通过国家企业信用信息公示系统向社会公示，并实施相应管理措施。列入期限自即日起至"
                + term.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日")) +
                "。期满一年后，你（单位）可依据《市场监督管理严重违法失信名单管理办法》第十六条、第十七条规定向我局申请提前移出严重违法失信名单，停止公示相关信息并解除相应管理措施。" +
                "\n你（单位）如不服本决定，可以自收到本决定书之日起六十日内向"
                + government +
                "申请行政复议；也可以在六个月内向"+ city +"人民法院提起行政诉讼。";
        return text;
    }
}
