package com.chinaweal.aiccs.aiccs.abnormal.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSAbnList;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSBizDissent;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSBizRemList;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSBizSpeList;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSBizAbnRevokeService;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSBizDissentService;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSBizRemListService;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSBizSpeListService;
import com.chinaweal.aiccs.aiccs.auditing.entity.TSOpinion;
import com.chinaweal.aiccs.aiccs.auditing.service.TSOpinionService;
import com.chinaweal.aiccs.aiccs.business.entity.TSTaskList;
import com.chinaweal.aiccs.aiccs.business.entity.TSTwfProcessNode;
import com.chinaweal.aiccs.aiccs.business.rules.model.SequenceFlowModel;
import com.chinaweal.aiccs.aiccs.business.service.TSTaskListService;
import com.chinaweal.aiccs.aiccs.business.service.WorkFlowService;
import com.chinaweal.aiccs.common.base.controller.BaseController;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.util.ConstantsUtil;
import com.chinaweal.aiccs.common.util.FlowUtil;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.common.util.WorkFlowUtil;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import com.chinaweal.youfool.framework.springboot.rest.RestResult;
import com.chinaweal.youfool.framework.springboot.rest.ResultCode;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description 异常名录业务修改
 *
 * @author <a href="https://blog.lroyia.top">lroyia</a>
 * @since 2021/1/25 16:37
 **/
@RestController
@RequestMapping("/bizSpeListModify")
public class BizSpeListModifyController extends BaseController {
    @Autowired
    private TSBizSpeListService tsBizSpeListService;
    @Autowired
    private TSTaskListService taskListService;
    @Autowired
    private TSOpinionService opinionService;
    @Autowired
    private WorkFlowService workFlowService;
    @Autowired
    private TSBizDissentService tsBizDissentService;
    @Autowired
    private TSBizRemListService tsBizRemListService;
    @Autowired
    private TSBizAbnRevokeService tsbizAbnRevokeService;

    /**
     * 异常名录 异常业务查询
     */
    @PostMapping("/selectAbnListBussByPage.do")
    public RestResult<?> selectAbnListBussByPage(HttpServletRequest request, TSAbnList tsAbnListModel,
                                                 String acceptno, int rows, int page) {
//        AICUser aicUser = (AICUser) request.getSession().getAttribute(ConstantsUtil.USER_SESSION_NAME);
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        if (StringUtils.isNotBlank(aicUser.getRegionID())) {//只查询 本机构做出决定的 异常名录主体
            tsAbnListModel.setIntoDecorg(aicUser.getRegionID());
        }
        return RestResult.ok(tsBizSpeListService.selectAbnListBussByPage(new Page<>(page, rows), tsAbnListModel, acceptno));
    }

    /**
     * entertype：individual、farmer、enterprise
     * 异常名录修改业务 启动待办
     */
    @PostMapping("/toModify.do")
    public RestResult<?> toModify(HttpServletRequest request, TSTaskList taskListModel, String bizSeq, String spelistid, String entertype) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) throw new BusinessException("登录超时，请重新登录");
        Map<String, Object> resultMap = new HashMap<>();
        if (StringUtils.isBlank(taskListModel.getTasklistid())) { //新增待办
            List<TSTaskList> taskListModelList = taskListService.selectByBizSeqID(bizSeq);
            if (CollectionUtils.isEmpty(taskListModelList)) throw new BusinessException("原待办缺失bizseq=" + bizSeq);

            String bustype = taskListModelList.get(0).getBustype();//原待办业务类型 BusType
            if (BaseDataConstant.EXPTLIST_TYPE_INDIVIDUAL_TAG.equals(bustype)) {
                bustype = BaseDataConstant.BUSINESS_TYPE_INDIVIDUAL_MODIFY;//个体户经营异常修改
                entertype = "individual";
            } else if (BaseDataConstant.EXPTLIST_TYPE_FARMER_ADD.equals(bustype)) {
                bustype = BaseDataConstant.BUSINESS_TYPE_FARMER_MODIFY; //农合经营异常修改
                entertype = "farmer";
            } else {
                bustype = BaseDataConstant.BUSINESS_TYPE_ENTERPRISE_MODIFY; //企业经营异常修改
                entertype = "enterprise";
            }

            TSBizSpeList oldBizSpeModel = tsBizSpeListService.getById(spelistid);//原记录
            if (oldBizSpeModel != null) {
                String bizseq = oldBizSpeModel.getSpelistid(); //原记录的id 作为新记录的业务号

                List<TSBizSpeList> bizSpeList = new ArrayList<>();
                TSBizSpeList tsBizSpeListModel = new TSBizSpeList();//新记录
                tsBizSpeListModel.setBizseq(bizseq);
                tsBizSpeListModel.setPripid(oldBizSpeModel.getPripid());
                tsBizSpeListModel.setRegno(oldBizSpeModel.getRegno());
                tsBizSpeListModel.setEntname(oldBizSpeModel.getEntname());
                tsBizSpeListModel.setEnttype(oldBizSpeModel.getEnttype());
                tsBizSpeListModel.setDecorg(oldBizSpeModel.getDecorg());//做出决定的机关
                bizSpeList.add(tsBizSpeListModel);//只增加一条记录，即还不能批量修改

                //添加待办
                taskListModel.setBizseqid(bizseq);
                taskListModel.setBustype(bustype);
                taskListModel.setBusname(oldBizSpeModel.getEntname());
                taskListModel = tsBizSpeListService.saveAbnListAccept(aicUser, taskListModel, bizSpeList);
            }
        }

        TSTaskList taskListModel1 = taskListService.selectByTasklistID(taskListModel.getTasklistid());
        TSBizSpeList paramModel = new TSBizSpeList();
        paramModel.setBizseq(taskListModel1.getBizseqid());
        List<TSBizSpeList> list = tsBizSpeListService.selectBSPexptlist(paramModel);
        if (CollectionUtils.isNotEmpty(list)) resultMap.put("newBizSpeModel", list.get(0));//新记录

        TSBizSpeList bizSpeListModel = tsBizSpeListService.getById(taskListModel1.getBizseqid());
        if (bizSpeListModel != null) {
            //判断所要修改的记录 是否因【无法联系】被列入，若是则页面中列入原因过滤掉该原因选项
            if ((BaseDataConstant.BUSINESS_TYPE_ENTERPRISE_MODIFY.equals(taskListModel1.getBustype()) && "4".equals(bizSpeListModel.getSpecause()))
                    || (BaseDataConstant.BUSINESS_TYPE_INDIVIDUAL_MODIFY.equals(taskListModel1.getBustype()) && "3".equals(bizSpeListModel.getSpecause()))
                    || (BaseDataConstant.BUSINESS_TYPE_FARMER_MODIFY.equals(taskListModel1.getBustype()) && "3".equals(bizSpeListModel.getSpecause()))) {

                resultMap.put("isHaveLost", "have");
            }
            resultMap.put("oldBizSpeModel", bizSpeListModel);//旧记录
        }

        List<SequenceFlowModel> nextSequenceFlowList = workFlowService.findNextSequenceFlowList(taskListModel1.getWorkflowid());
        TSTwfProcessNode currentNode = workFlowService.findCurrentNode(taskListModel1.getWorkflowid());
        String opinionType = BaseDataConstant.getOpinionTypeByWorkFlowNode(currentNode.getCurrentnode());
        if (opinionType == null) opinionType = "1";
        resultMap.put("opinionList", opinionService.selectByAuditingID(taskListModel1.getWorkflowid()));
        resultMap.put("nextSequenceFlowList", nextSequenceFlowList);
        resultMap.put("tasklistid", taskListModel1.getTasklistid());
        resultMap.put("newBizSeq", taskListModel1.getBizseqid());
        resultMap.put("currentNode", currentNode.getCurrentnode());
        resultMap.put("currentLinkTypeID", opinionType);
        resultMap.put("currentNodeName", WorkFlowUtil.getNodeName(currentNode.getCurrentnode()));
        resultMap.put("entertype", entertype);
        return RestResult.ok(resultMap);
    }

    /**
     * 经营异常名录修改  审批流程
     */
    @RequestMapping("/saveBizModify.do")
    public RestResult<?> saveBizModify(HttpServletRequest request, TSBizSpeList tsBizSpeListModel, TSOpinion opinionModel,
                                       String tasklistid, String nextPerformerids, String nextPerformerNames, String nextNodeID, String entertype) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) throw new BusinessException("登录超时，请重新登录");
        Map<String, Object> resultMap = new HashMap<>();

        //更新 异常名录业务表
        if (StringUtils.isNotBlank(tsBizSpeListModel.getBizseq())) {
            TSBizSpeList paramModel = new TSBizSpeList();
            paramModel.setBizseq(tsBizSpeListModel.getBizseq());
            List<TSBizSpeList> tsBizSpeList = tsBizSpeListService.selectBSPexptlist(paramModel);
            for (TSBizSpeList bizSpeListModel : tsBizSpeList) {
                if (FlowUtil.EXPTLISTWORKFLOW_HANDLEEXPTLIST.equals(nextNodeID)) {
                    bizSpeListModel.setSpereasons(tsBizSpeListModel.getSpereasons());
                    bizSpeListModel.setReconsiderationOrg(tsBizSpeListModel.getReconsiderationOrg());
                    bizSpeListModel.setGovernmentOrg(tsBizSpeListModel.getGovernmentOrg());
                    bizSpeListModel.setLitiOrg(tsBizSpeListModel.getLitiOrg());
                    bizSpeListModel.setSpecause(tsBizSpeListModel.getSpecause());
                }
            }
            String[] ids = org.apache.commons.lang.StringUtils.split(nextPerformerids, ",");
            String[] names = org.apache.commons.lang.StringUtils.split(nextPerformerNames, ",");
            TSTaskList taskListModel = taskListService.selectByTasklistID(tasklistid);
            tsBizSpeListService.saveAbnModifyAuditProcess(aicUser, taskListModel, tsBizSpeList, opinionModel, nextNodeID, ids, names);
            if (ids.length == 1 && org.apache.commons.lang.StringUtils.equals(aicUser.getPrimaryKey(), ids[0])) {
                resultMap.put("bizseq", tsBizSpeListModel.getBizseq());
                resultMap.put("tasklistid", tasklistid);
                resultMap.put("nextNodeID", nextNodeID);
                resultMap.put("entertype", entertype);
            }
        }
        return RestResult.ok(resultMap);
    }

    /**
     * 启动修改前 校验
     */
    @PostMapping("/validateBiz.do")
    public RestResult<?> validateBiz(HttpServletRequest request, String bizSeq, String spelistid) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) throw new BusinessException("登录超时，请重新登录");

        //校验是否存在 异议待办
        TSBizDissent bizDissentModel = new TSBizDissent();
        bizDissentModel.setAbnlistid(spelistid); //异常名录表生成记录时：tsAbnListModel.setAbnlistid(bizSpeListModel.getSpelistid());
        List<TSBizDissent> tsBizDissentList = tsBizDissentService.selectbizDissentList(bizDissentModel);
        if (CollectionUtils.isNotEmpty(tsBizDissentList)) {
            for (TSBizDissent tsBizDissentModel : tsBizDissentList) {
                List<TSTaskList> tsTaskListModels = taskListService.selectByBizSeqID(tsBizDissentModel.getBizseq());
                for (TSTaskList tsTaskListModel : tsTaskListModels) {
                    if (tsTaskListModel.getBusstatus().equals(BaseDataConstant.BUSINESS_STATUS_TRANSACT)) { //存在待办未办结
                        throw new BusinessException("该记录正在进行异议申请业务，请先完成");
                    }
                }
            }
        }

        //校验是否存在 移出待办
        TSBizRemList tsBizRemListModel = new TSBizRemList();
        tsBizRemListModel.setAbnlistid(spelistid);
        List<TSBizRemList> tsBizRemListModelList = tsBizRemListService.selectBRMexptlist(tsBizRemListModel);
        if (CollectionUtils.isNotEmpty(tsBizRemListModelList)) {
            for (TSBizRemList bizRemListModel : tsBizRemListModelList) {
                if (bizRemListModel.getRemreasons() == null || bizRemListModel.getApprovaldate() == null) {
                    throw new BusinessException("该记录正在进行移出业务，请先完成");
                }
            }
        }

        //校验是否存在 撤销待办
        boolean b = tsbizAbnRevokeService.validateBizRevoke(spelistid, BaseDataConstant.BUSINESS_TYPE_REVOKEABN);
        if (!b) throw new BusinessException("该记录正在进行撤销业务，请先完成");

        //校验是否存在 修改待办
        List<TSTaskList> taskListModels = taskListService.selectByBizSeqID(spelistid);
        for (TSTaskList taskListModel : taskListModels) {
            if (taskListModel.getBusstatus().equals(BaseDataConstant.BUSINESS_STATUS_TRANSACT)) { //存在修改待办  未办结
                throw new BusinessException("该记录正在进行修改业务，请先完成");
            }
        }

        return OK;
    }
}
