package com.chinaweal.aiccs.aiccs.revoke.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSBizSpeList;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSWrit;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSWritService;
import com.chinaweal.aiccs.aiccs.asyncTask.RevokeAsyncTask;
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.service.TSTaskListService;
import com.chinaweal.aiccs.aiccs.business.service.WorkFlowService;
import com.chinaweal.aiccs.aiccs.inspect.service.TSWorkNoService;
import com.chinaweal.aiccs.aiccs.revoke.entity.*;
import com.chinaweal.aiccs.aiccs.revoke.entity.dto.BizRevCancelDto;
import com.chinaweal.aiccs.aiccs.revoke.entity.dto.RevokeListDto;
import com.chinaweal.aiccs.aiccs.revoke.service.*;
import com.chinaweal.aiccs.common.base.controller.BaseController;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.util.FlowUtil;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.common.util.WorkFlowUtil;
import com.chinaweal.aiccs.common.util.WorkNoUtil;
import com.chinaweal.aiccs.org.entity.OrgUnits;
import com.chinaweal.aiccs.org.entity.TUsers;
import com.chinaweal.aiccs.org.service.AicorgService;
import com.chinaweal.aiccs.org.service.TUsersService;
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 com.chinaweal.youfool.framework.springboot.util.AssertUtils;
import com.chinaweal.youfool.framework.sso.util.SSOUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Lee
 * @since 2021-08-27
 */
@RestController
@Transactional
@RequestMapping("/tsbizrevcancel")
public class TsbizrevcancelController extends BaseController {

    @Autowired
    private RevokelistService revokelistService;
    @Autowired
    private TsbizrevcancelService tsbizrevcancelService;
    @Autowired
    private TsbizrevlistService tsbizrevlistService;
    @Autowired
    private CaseService caseService;
    @Autowired
    private TSWritService tsWritService;
    @Autowired
    private TswritscontentService tswritscontentService;
    @Autowired
    private AicorgService aicorgService;
    @Autowired
    private TSWorkNoService workNoService;
    @Autowired
    private TSTaskListService taskListService;
    @Autowired
    private WorkFlowService workFlowService;
    @Autowired
    private TSOpinionService opinionService;
    @Autowired
    private TUsersService usersService;
    @Autowired
    private RevokeAsyncTask revokeAsyncTask;

    /**
     * 撤销复议诉讼开启待办
     * @param request
     * @param revlistid
     * @param type
     * @return
     */
    @PostMapping("/startBizRevCancel")
    public RestResult<?> startBizRevCancel(HttpServletRequest request, String revlistid, String type) {
        AICUser user = getLoginUser(request);
        if (user == null) throw new BusinessException("登录超时，请重新登录");
        AssertUtils.isNotBlank(revlistid);

        Revokelist revokelistDB = revokelistService.getById(revlistid);
        if (revokelistDB == null){
            return RestResult.error(ResultCode.DATA_NONE);
        }

        String bizseq = UUID.randomUUID().toString();
        //添加待办启动流程
        TSTaskList taskListModel = new TSTaskList();
        taskListModel.setBizseqid(bizseq);
        if ("1".equals(type)) {
            taskListModel.setBustype(BaseDataConstant.REVOKE_TYPE_BATCHREVOKE_CANCEL);//批量吊銷--撤销
        } else if ("2".equals(type)) {
            taskListModel.setBustype(BaseDataConstant.REVOKE_TYPE_BATCHREVOKE_REVIEW);//批量吊銷--复议
        } else {
            taskListModel.setBustype(BaseDataConstant.REVOKE_TYPE_BATCHREVOKE_LITIGATION);//批量吊銷--诉讼
        }
        taskListModel.setBusname(revokelistDB.getEntname());

        //添加撤销业务表数据
        Tsbizrevcancel tsbizrevcancelModel = new Tsbizrevcancel();
        tsbizrevcancelModel.setRevlistid(revlistid);
        tsbizrevcancelModel.setBizseq(bizseq);
        tsbizrevcancelModel.setPripid(revokelistDB.getPripid());
        tsbizrevcancelModel.setHandletype(type);

        taskListModel = tsbizrevcancelService.startBizRevCancelAccept(user, taskListModel, tsbizrevcancelModel);
        if (StringUtils.isNotBlank(taskListModel.getTasklistid())) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("tasklistid", taskListModel.getTasklistid());
            resultMap.put("bizseq", bizseq);
            resultMap.put("workFlowId", taskListModel.getWorkflowid());
            return RestResult.ok(resultMap);
        }
        throw new BusinessException("内部服务出错，请联系管理员!");
    }

    /**
     * 撤销复议诉讼流程 下一步
     * @param request
     * @param tsbizrevcancelModel
     * @param opinionModel
     * @param tasklistid
     * @param nextPerformerids
     * @param nextPerformerNames
     * @param nextNodeID
     * @return
     */
    @PostMapping(value = "/next")
    public RestResult<?> next(HttpServletRequest request, Tsbizrevcancel tsbizrevcancelModel, TSOpinion opinionModel,
                                       String tasklistid, String nextPerformerids, String nextPerformerNames, String nextNodeID, String isNext) {
        AICUser user = getLoginUser(request);
        if (user == null) throw new BusinessException("登录超时，请重新登录");
        Map<String, Object> resultMap = new HashMap<>();
        //更新 撤销复议诉讼业务表
        if (tsbizrevcancelModel != null && StringUtils.isNotBlank(tsbizrevcancelModel.getBizseq())) {
            Tsbizrevcancel tsbizrevcancelDB = tsbizrevcancelService.getOne(new LambdaQueryWrapper<Tsbizrevcancel>().eq(Tsbizrevcancel::getBizseq, tsbizrevcancelModel.getBizseq()));
            //下一步为审核
            if (FlowUtil.REVOKECANCELWORKFLOW_HANDLEREVCANCEL.equals(nextNodeID)) {
                tsbizrevcancelDB.setCancelwritsno(tsbizrevcancelModel.getCancelwritsno());
                tsbizrevcancelDB.setCancelwritscontent(tsbizrevcancelModel.getCancelwritscontent());
                tsbizrevcancelDB.setHandledecorg(tsbizrevcancelModel.getHandledecorg());
                tsbizrevcancelDB.setHandlerdate(tsbizrevcancelModel.getHandlerdate());
            }
            TSTaskList taskListModel = taskListService.selectByTasklistID(tasklistid);
            if(StringUtils.isBlank(nextPerformerids)) {
                TSTwfProcessNode processNode = workFlowService.findCurrentNode(taskListModel.getWorkflowid());
                int order = WorkFlowUtil.checkNextOrder(processNode.getCurrentnode(), nextNodeID);

                // 通过order判断为回退还是前进 >0前进
                if(order >0){
                    LambdaQueryWrapper<TSOpinion> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(TSOpinion::getWorkflowid, taskListModel.getWorkflowid())
                            .eq(TSOpinion::getOpiniontype, "0")// 经办为0
                            .orderByDesc(TSOpinion::getLauptime);
                    List<TSOpinion> list = opinionService.list(wrapper);
                    if (org.apache.commons.collections4.CollectionUtils.isEmpty(list)) {
                        return RestResult.error(ResultCode.DATA_NONE);
                    }
                    nextPerformerids = list.get(0).getHandlerid();
                    nextPerformerNames = list.get(0).getHandler();
                }
                // 回退时 获取上一流程节点处理人
                if (order < 0){
                    String userId = workFlowService.findLastTwfprocessnodeByProcessidAndNodename(taskListModel.getWorkflowid(), processNode.getCurrentnode(), nextNodeID);
                    if (StringUtils.isEmpty(userId)){
                        return RestResult.error(ResultCode.DATA_NONE);
                    }
                    LambdaQueryWrapper<TUsers> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(TUsers::getUserid,userId);
                    TUsers userInfo = usersService.getOne(wrapper);
                    nextPerformerids = userInfo.getUserid();
                    nextPerformerNames = userInfo.getRealname();
                }
            }
            String[] ids = StringUtils.split(nextPerformerids, Constant.COMMA);
            String[] names = StringUtils.split(nextPerformerNames, Constant.COMMA);
            try {
                //审批时才调用。且不是第二次进入该方法时
                if(FlowUtil.REVOKECANCELWORKFLOW_ENDREVCANCEL.equals(nextNodeID) && !"1".equals(isNext)){
                    //根据吊销id查询吊销信息
                    Revokelist revokelistDB = revokelistService.getById(tsbizrevcancelDB.getRevlistid());
                    OrgUnits orgUnits = aicorgService.queryByOrgNumber(tsbizrevcancelDB.getHandledecorg());
                    AICUser aicUser = SSOUtil.getUser();
                    CancelRevokelist cancelRevoke = new CancelRevokelist();
                    cancelRevoke.setRevcancelid(tsbizrevcancelDB.getRevcancelid())
                            .setPripid(tsbizrevcancelDB.getPripid())
                            .setUniscid(revokelistDB.getUniscid())
                            .setEntname(revokelistDB.getEntname())
                            .setCancelapprdocno(tsbizrevcancelDB.getCancelwritsno())
                            .setCancelapprdept(orgUnits.getOrgUnitName())
                            .setUsername("信用监管系统")
                            .setHandlerid(aicUser.getPrimaryKey())
                            .setHandlername(aicUser.getEname())
                            .setCancelapprdeptid(tsbizrevcancelDB.getHandledecorg());
                    //调用泰富撤销吊销接口
                    String result = revokeAsyncTask.tfCancelRevocation(cancelRevoke);
                    if(!"success".equals(result)){  //接口调用失败
                        String errorMsg = getRevokeCancelExcode(result);
                        return RestResult.error(ResultCode.INTERFACE_OUTER_INVOKE_ERROR,errorMsg);
                    }
                }

                tsbizrevcancelService.saveRevokeCancelProcess(user, taskListModel, tsbizrevcancelDB, opinionModel, nextNodeID, ids, names);
                if (ids.length == 1 && StringUtils.equals(user.getPrimaryKey(), ids[0])) {
                    resultMap.put("bizseq", tsbizrevcancelModel.getBizseq());
                    resultMap.put("nextNodeId", nextNodeID);
                    resultMap.put("taskListId", tasklistid);
                    resultMap.put("workFlowId", taskListModel.getWorkflowid());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return RestResult.ok(resultMap);
    }
    /**
     * 获取撤销决定页面详情
     * @param request
     * @param bizseq
     * @return
     */
    @PostMapping("getRevCancelInfo")
    public RestResult<?> getRevCancelInfo(HttpServletRequest request, String bizseq){
        AICUser user = getLoginUser(request);
        if (user == null) throw new BusinessException("登录超时，请重新登录");
        AssertUtils.isNotBlank(bizseq);
        BizRevCancelDto bizRevCancelDto = new BizRevCancelDto();
        Tsbizrevcancel tsbizrevcancelDB = tsbizrevcancelService.getOne(new LambdaQueryWrapper<Tsbizrevcancel>().eq(Tsbizrevcancel::getBizseq, bizseq));
        String revlistid = tsbizrevcancelDB.getRevlistid();
        Revokelist revokelistDB = revokelistService.getById(revlistid);

        bizRevCancelDto.setEntname(revokelistDB.getEntname());
        bizRevCancelDto.setRegno(revokelistDB.getRegno());
        bizRevCancelDto.setUniscid(revokelistDB.getUniscid());
        bizRevCancelDto.setPripid(revokelistDB.getPripid());
        // 获取案件编号，案件名
        TsCase aCase = caseService.getOne(new LambdaQueryWrapper<TsCase>().eq(TsCase::getCaseNo, revokelistDB.getCaseno()));
        bizRevCancelDto.setCaseNo(aCase.getCaseNo());
        bizRevCancelDto.setCaseName(aCase.getCaseName());
        // 获取处罚决定书信息
        TSWrit decWrits = tsWritService.getById(revokelistDB.getWritsid());
        bizRevCancelDto.setPunishDecDate(decWrits.getCreatetime().toLocalDate());
        bizRevCancelDto.setPunishDecWritsNo(decWrits.getWritsno());
        Tsbizrevlist bizrevlistParam = new Tsbizrevlist();
        bizrevlistParam.setRevlistid(revlistid);
//        Tsbizrevlist tsbizrevlist = tsbizrevlistService.getOne(new LambdaQueryWrapper<Tsbizrevlist>().eq(Tsbizrevlist::getRevlistid, revlistid));
        List<Tsbizrevlist> bizRevEntList = tsbizrevlistService.getBizRevEntList(bizrevlistParam);
        Tsbizrevlist tsbizrevlist = bizRevEntList.get(0);
        List<Tswritscontent> tswritscontentList = tswritscontentService.list(new LambdaQueryWrapper<Tswritscontent>().eq(Tswritscontent::getBizseq, tsbizrevlist.getBizseq())
                .eq(Tswritscontent::getWritsType, WorkNoUtil.WORKNOTYPE_33).orderByAsc(Tswritscontent::getParagraphNo));
        bizRevCancelDto.setPunishDecContent(decWrits.getContent());
        //生成撤销文书号，保存至业务表
        String writstype = "";
        if("1".equals(tsbizrevcancelDB.getHandletype())){
            writstype = WorkNoUtil.WORKNOTYPE_34;
        }else if("2".equals(tsbizrevcancelDB.getHandletype())){
            writstype = WorkNoUtil.WORKNOTYPE_35;
        }else if("3".equals(tsbizrevcancelDB.getHandletype())){
            writstype = WorkNoUtil.WORKNOTYPE_36;
        }
        String wrirsno = tsbizrevcancelDB.getCancelwritsno();
        if(StringUtils.isEmpty(wrirsno)) {
            String code = aicorgService.getRegionCodeByUser(user);
            wrirsno = workNoService.getOperatingWrirsno(writstype, code);
            tsbizrevcancelDB.setCancelwritsno(wrirsno);
            tsbizrevcancelService.updateById(tsbizrevcancelDB);
        }
        bizRevCancelDto.setCancelwritsno(wrirsno);
        bizRevCancelDto.setHandledecorg(tsbizrevcancelDB.getHandledecorg());
        bizRevCancelDto.setHandlerdate(tsbizrevcancelDB.getHandlerdate());
        bizRevCancelDto.setCancelwritscontent(tsbizrevcancelDB.getCancelwritscontent());
        return RestResult.ok(bizRevCancelDto);
    }

    /**
     * 根据撤销吊销接口的异常代码显示对应的提示语
     */
    private String getRevokeCancelExcode(String excode){
        String msg = "";
        switch (excode){
            case "001":
                msg = "未找到对应的主体，请核实该主体是否真实存在。";
                break;
            case "002":
                msg = "该主体不是吊销状态，不允许撤销吊销，请核查是否已经撤销吊销或已注销或已清算。";
                break;
            default:
                msg = "撤销吊销失败，请联系系统工程师进一步排查原因。";
                break;
        }
        return msg + "点击“确定”，结束流程；点击“取消”，关闭弹窗。";
    }

}

