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

import cn.hutool.core.collection.CollUtil;
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.TSTaskList;
import com.chinaweal.aiccs.aiccs.business.entity.TSTwfProcessNode;
import com.chinaweal.aiccs.aiccs.business.service.TSTaskListService;
import com.chinaweal.aiccs.aiccs.business.service.TSTwfProcessNodeService;
import com.chinaweal.aiccs.aiccs.business.service.WorkFlowService;
import com.chinaweal.aiccs.aiccs.inspect.service.TSWorkNoService;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSSerIllegalList;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.dto.DissentIllegalAppDto;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSSerIllegalListService;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.util.*;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSBizSerIllegalDiss;
import com.chinaweal.aiccs.aiccs.seriousillegal.mapper.TSBizSerIllegalDissMapper;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSBizSerIllegalDissService;
import com.chinaweal.aiccs.org.service.AicorgService;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.aicorg.services.OrgUM;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.BaseServiceImpl;
import com.chinaweal.youfool.framework.springboot.rest.RestResult;
import com.chinaweal.youfool.framework.springboot.rest.ResultCode;
import com.chinaweal.youfool.framework.sso.util.SSOUtil;
import lombok.extern.slf4j.Slf4j;
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 org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 严重违法失信企业名单异议业务表 服务实现类
 * </p>
 *
 * @author <a href="https://blog.lroyia.top">lroyia</a>
 * @since 2021-01-26
 */
@Slf4j
@Service
public class TSBizSerIllegalDissServiceImpl extends BaseServiceImpl<TSBizSerIllegalDissMapper, TSBizSerIllegalDiss> implements TSBizSerIllegalDissService {

    @Autowired
    private TSTaskListService taskListService;
    @Autowired
    private TSWorkNoService workNoService;
    @Autowired
    private TSWritService tsWritService;
    @Autowired
    private TSHandInMatService tsHandInMatService;
    @Autowired
    private WorkFlowService workFlowService;
    @Autowired
    private TSTwfProcessNodeService tsTwfProcessNodeService;
    @Autowired
    private AicorgService aicorgService;
    @Autowired
    private TSSerIllegalListService tsSerIllegalListService;
    @Autowired
    private TSAbnListService tsAbnListService;
    @Lazy
    @Autowired
    private EBaseinfoService eBaseinfoService;
    @Lazy
    @Autowired
    private IGzaiccodeService iGzaiccodeService;
    @Autowired
    private OrgUM orgUM;

    @Override
    public List<TSBizSerIllegalDiss> selectbizDissentList(TSBizSerIllegalDiss tsBizDissentModel) {
        return baseMapper.selectbizDissentList(tsBizDissentModel);
    }

    @Override
    public TSBizSerIllegalDiss selectBizDissentByBizSeq(String bizseq) {
        return baseMapper.selectBizDissentByBizSeq(bizseq);
    }

    @Override
    public TSTaskList startBizDissentAccept(AICUser user, List<String> userIdList, TSTaskList taskListModel, TSBizSerIllegalDiss tsBizDissentModel) {
        if (StringUtils.isBlank(taskListModel.getTasklistid())) {
            saveOrUpdate(tsBizDissentModel);
            taskListModel = HandleWorkFlowUtil.createTaskList(taskListModel, user); //新生成待办
            String definedName = FlowUtil.SERILLEGALDISSENTWORKFLOW; //严重违法失信企业 异议流程模板
            if (CollUtil.isEmpty(userIdList) || userIdList.size() <= 1) {
                taskListService.startWorkFlow(taskListModel, user, definedName);
            } else {
                taskListService.startWorkFlow(taskListModel, userIdList, user.getRegionID().substring(0, 6), definedName);
            }
        }
        return taskListModel;
    }

    @Transactional
    @Override
    public TSTaskList saveBizDissentAuditProcess(AICUser user, TSTaskList taskListModel, TSBizSerIllegalDiss tsBizDissentModel, TSOpinion opinionModel, String nextNodeID, String[] nextPerformerids, String[] nextPerformerNames) {

        String regionCode = aicorgService.getRegionCodeByUser(user);
        // 接收人为空
        if (nextPerformerids.length == 0) {
            TSTwfProcessNode processNode = workFlowService.findCurrentNode(taskListModel.getWorkflowid());
            int order = WorkFlowUtil.checkNextOrder(processNode.getCurrentnode(), nextNodeID);
            // 回退时 获取上一个节点处理人
            if (order < 0){
                List<TSTwfProcessNode> tsTwfProcessNodes = tsTwfProcessNodeService.queryByPROCESSIDAndCURRENTNODE(taskListModel.getWorkflowid(),nextNodeID);
                String nextPerformerid = tsTwfProcessNodes.get(0).getCurruserid();
                String nextPerformerName = tsTwfProcessNodeService.queryRealName(tsTwfProcessNodes.get(0).getCurruserid());
                nextPerformerids = nextPerformerid.split(";");
                nextPerformerNames = nextPerformerName.split(";");
            } else {
                if (FlowUtil.DISSENTWORKFLOW_APPROVEDISSENTENTER.equals(nextNodeID)) { // 前往核准经办
                    List<TSTwfProcessNode> tsTwfProcessNodes = tsTwfProcessNodeService.queryByPROCESSIDAndCURRENTNODE(
                            taskListModel.getWorkflowid(),FlowUtil.DISSENTWORKFLOW_ACCEPTDISSENTENTER);
                    String nextPerformerid = tsTwfProcessNodes.get(0).getCurruserid();
                    String nextPerformerName = tsTwfProcessNodeService.queryRealName(tsTwfProcessNodes.get(0).getCurruserid());
                    nextPerformerids = nextPerformerid.split(";");
                    nextPerformerNames = nextPerformerName.split(";");
                }
            }
        }
        if (FlowUtil.DISSENTWORKFLOW_HANDLEDISSENTACCEPT.equals(nextNodeID)
                || FlowUtil.DISSENTWORKFLOW_OVERFINISH.equals(nextNodeID)) { // 前往受理审批环节
            updateById(tsBizDissentModel);
        }
        if (FlowUtil.DISSENTWORKFLOW_HANDLEDISSENTAPPROVE.equals(nextNodeID)) { // 前往核准审批环节
            updateById(tsBizDissentModel);
        }
        if (FlowUtil.DISSENTWORKFLOW_OVERDISSENTENTER.equals(nextNodeID)) { // 不受理并结束流程
            tsBizDissentModel.setApprovalDate(LocalDate.now());
            updateById(tsBizDissentModel);
            TSWrit tsWritModel = new TSWrit();
            tsWritModel.setWritsid(UUID.randomUUID().toString());
            String workNoType = WorkNoUtil.WORKNOTYPE_23;
            tsWritModel.setWritstype(workNoType);
            tsWritModel.setWritsname(WorkNoUtil.getWorkNoTypeName(workNoType));
            //文号格式：9位工商代码+6位流水号
            String writsno = workNoService.getOperatingWrirsno(workNoType, regionCode);
            tsWritModel.setWritsno(writsno);
            tsWritModel.setBizseq(tsBizDissentModel.getBizSeq());
            tsWritModel.setPripid(tsBizDissentModel.getPriPID());
            tsWritModel.setCreatetime(LocalDateTime.now());
            tsWritModel.setAreaCode(regionCode);
            tsWritService.save(tsWritModel);
        }
        if (FlowUtil.DISSENTWORKFLOW_ENDDISSENT.equals(nextNodeID)) {//完结通过时
            TSWrit tsWritModel = new TSWrit();
            tsWritModel.setWritsid(UUID.randomUUID().toString());
            String workNoType = "";
            if (StringUtils.isNotBlank(tsBizDissentModel.getAcceptStat()) && tsBizDissentModel.getAcceptStat().equals(Constant.FALSE_0_STR)) {//生成文书号
                workNoType = WorkNoUtil.WORKNOTYPE_23;// 列入严重违法失信名单 异议不予受理通知书
            } else {
                workNoType = WorkNoUtil.WORKNOTYPE_24;//列入严重违法失信名单 异议核实结果告知书
            }
            tsWritModel.setWritstype(workNoType);
            tsWritModel.setWritsname(WorkNoUtil.getWorkNoTypeName(workNoType));
            //文号格式：9位工商代码+6位流水号
            String writsno = workNoService.getOperatingWrirsno(workNoType, regionCode);
            tsWritModel.setWritsno(writsno);
            tsWritModel.setBizseq(tsBizDissentModel.getBizSeq());
            tsWritModel.setPripid(tsBizDissentModel.getPriPID());
            tsWritModel.setCreatetime(LocalDateTime.now());
            tsWritModel.setAreaCode(regionCode);
            tsWritService.save(tsWritModel);

            tsBizDissentModel.setApprovalDate(LocalDate.now()); //核准时间
            updateById(tsBizDissentModel);

            // 受理状态为1，同意受理
            if (tsBizDissentModel.getAcceptStat().equals("1")) {
                // 列严记录改为撤销状态
                TSSerIllegalList tsSerIllegalList = tsSerIllegalListService.getById(tsBizDissentModel.getIllegalListID());
                tsSerIllegalList.setOperationStatus("3");
                tsSerIllegalList.setIsrev("1");
                tsSerIllegalListService.updateById(tsSerIllegalList);
                // 判断是否为满3年列入，如果是，恢复列异记录
                if ("被列入经营异常名录届满3年仍未履行相关义务的".equals(tsSerIllegalList.getLostcreditexplain())
                        && StringUtils.isNotBlank(tsSerIllegalList.getAbnlistid())) {
                    TSAbnList tsAbnList = tsAbnListService.getById(tsSerIllegalList.getAbnlistid());
                    tsAbnList.setOperatestatus("1");
                    tsAbnList.setRemdate(null);
                    tsAbnList.setRemreasons(null);
                    tsAbnListService.updateById(tsAbnList);
                }
            }
        }

        if (FlowUtil.DISSENTWORKFLOW_APPROVEDISSENTENTER.equals(nextNodeID)) {
            TSWrit tsWritModel = new TSWrit();
            tsWritModel.setWritsid(UUID.randomUUID().toString());
            String workNoType = WorkNoUtil.WORKNOTYPE_22;//列入严重违法失信名单 异议受理通知书
            String writsno = workNoService.getOperatingWrirsno(workNoType, regionCode);
            tsWritModel.setWritstype(workNoType);
            tsWritModel.setWritsname(WorkNoUtil.getWorkNoTypeName(workNoType));
            tsWritModel.setBizseq(tsBizDissentModel.getBizSeq());
            tsWritModel.setWritsno(writsno);
            tsWritModel.setPripid(tsBizDissentModel.getPriPID());
            tsWritModel.setCreatetime(LocalDateTime.now());
            tsWritModel.setAreaCode(regionCode);
            tsWritService.save(tsWritModel);
            tsBizDissentModel.setAcceptStat(Constant.TRUE_1_STR);
            updateById(tsBizDissentModel);
        }
        taskListService.updateWorkFlow(user, opinionModel, taskListModel, nextNodeID, nextPerformerids, nextPerformerNames);
        return taskListModel;
    }

    @Override
    public void saveBizDissentApply(TSBizSerIllegalDiss tsBizDissentModel, List<TSHandInMat> tsHandInMatModels) {
        List<TSHandInMat> handInMatList = tsHandInMatService.selecthandInMatList(tsBizDissentModel.getBizSeq());
        //先删后加
        if (CollectionUtils.isNotEmpty(handInMatList)) {
            for (TSHandInMat handInMat1 : handInMatList) {
                tsHandInMatService.removeById(handInMat1.getSerialid());
            }
        }
        for (TSHandInMat handInMat : tsHandInMatModels) {
            tsHandInMatService.saveOrUpdate(handInMat);
        }
        //更新异议表
        updateById(tsBizDissentModel);
    }

    @Override
    public void startAppDissent(DissentIllegalAppDto dissentIllegalAppDto) {
        String bizSeq = dissentIllegalAppDto.getBizSeq();
        TSSerIllegalList serIllegalList = tsSerIllegalListService.getById(dissentIllegalAppDto.getIllegalListID());
        EBaseinfo eBaseInfo = eBaseinfoService.getById(serIllegalList.getPripid());

        //添加异议表数据
        TSBizSerIllegalDiss tsBizDissentModel = new TSBizSerIllegalDiss();
        tsBizDissentModel.setBizSeq(bizSeq);
        tsBizDissentModel.setIllegalListID(serIllegalList.getIllegallistid());
        tsBizDissentModel.setPriPID(serIllegalList.getPripid());
        tsBizDissentModel.setRegNO(serIllegalList.getRegno());
        tsBizDissentModel.setEntName(serIllegalList.getEntname());
        tsBizDissentModel.setLeRepName(eBaseInfo.getName());
        tsBizDissentModel.setStatus("9");
        tsBizDissentModel.setAppOrPc("1");
        tsBizDissentModel.setApplicant(dissentIllegalAppDto.getApplicant());
        tsBizDissentModel.setApplicantId(dissentIllegalAppDto.getApplicantId());
        tsBizDissentModel.setApplicantNo(dissentIllegalAppDto.getApplicantNo());
        tsBizDissentModel.setContacts(dissentIllegalAppDto.getApplicant());
        tsBizDissentModel.setTelephone(dissentIllegalAppDto.getApplicantNo());

        String permission = "illegalRemoveAccept";
        List<String> userIdList = iGzaiccodeService.byPermissionListHandleUserList(serIllegalList.getPripid(), permission, serIllegalList.getDecorg(), null)
                .stream().map(AICUser::getPrimaryKey).collect(Collectors.toList());
        if (userIdList.isEmpty()) {
            log.error("分派失败，受理人列表为空,tsSerIllegalListModel为：{} ,权限为：{}", tsBizDissentModel, "illegalRemoveAccept");
            throw new BusinessException("受理人列表为空！");
        } else {
            TSTaskList taskListModel = new TSTaskList();
            //添加待办
            taskListModel.setBizseqid(bizSeq);
            taskListModel.setBustype(BaseDataConstant.SERILLEGAL_TYPE_OBJECTION);
            taskListModel.setBusname(tsBizDissentModel.getEntName());
            AICUser aicUser = orgUM.findUserByPrimaryKey(userIdList.get(0));
            tsBizDissentModel.setAreaCode(aicUser.getRegionID());
            taskListModel = startBizDissentAccept(aicUser, userIdList, taskListModel, tsBizDissentModel);
            //移动端过来的数据要更新为申请人的信息
            taskListModel.setSenderuserid("");
            taskListModel.setSenderorgid("");
            taskListModel.setSendername(dissentIllegalAppDto.getApplicant());
            taskListService.updateById(taskListModel);
        }
    }
}
