package com.chinaweal.aiccs.aiccs.seriousillegal.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chinaweal.aiccs.aiccs.abnormal.entity.Gzaiccode;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSAbnList;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSAttachment;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSBizSpeList;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSAttachmentService;
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.entity.dto.CorrectionsProcessDto;
import com.chinaweal.aiccs.aiccs.business.service.BizCorrectionsService;
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.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.base.controller.BaseController;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.util.ConstantsUtil;
import com.chinaweal.aiccs.common.util.StringUtils;
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.mybatis.plus.page.PageRequestDto;
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 io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 列严勘误业务Controller
 * @author <a href="https://blog.lroyia.top">lroyia</a>
 * @since 2021/4/25 16:11
 **/
@RestController
@RequestMapping("/corrections/illegal")
public class IllegalCorrectionsController extends BaseController {

    @Autowired
    private TSSerIllegalListService serIllegalListService;
    @Autowired
    private TRBaseCodeService baseCodeService;
    @Autowired
    private BizCorrectionsService bizCorrectionsService;
    @Autowired
    private TSTaskListService taskListService;
    @Autowired
    private TSTwfProcessNodeService twfProcessNodeService;
    @Autowired
    private AicorgService aicorgService;
    @Autowired
    private TUsersService tUsersService;
    @Autowired
    private TSAttachmentService attachmentService;
    @Autowired
    private WorkFlowService workFlowService;
    @Autowired
    private TUsersService usersService;
    @Autowired
    private TSBizSerIllegalService tsBizSerIllegalService;

    /**
     * 列严记录分页
     * @param pageRequestDto 分页参数
     * @param request   请求
     * @return  分页结果
     * @author lroyia
     * @since  2021年4月25日 16:16:21
     */
    @ApiOperation("列严记录分页")
    @PostMapping("listPage")
    public RestResult<?> abnormalListPage(@ApiParam("分页参数") @RequestBody PageRequestDto pageRequestDto, HttpServletRequest request){
        AssertUtils.isNotNull(pageRequestDto);
        AICUser user = getLoginUser(request);
        if (user == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        pageRequestDto.checkDefault(1, 10, "lauptime");
        String orgCode = aicorgService.getRegionCodeByUser(user);
        String[] decOrgList = ConstantsUtil.getDecOrgList(orgCode);
        Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CD73");
        return RestResult.ok(serIllegalListService.defaultPaging(pageRequestDto,  w -> {
                    LambdaQueryWrapper<TSSerIllegalList> wrapper = w.lambda();
                    wrapper.in(TSSerIllegalList::getDecorg,decOrgList);
                Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
                if (MapUtils.isEmpty(customParamMap)) return;
                String entname = StringUtils.tranObject(customParamMap.get("entName"));
                String searchCode = StringUtils.tranObject(customParamMap.get("searchCode"));
                String sourceType = StringUtils.tranObject(customParamMap.get("sourceType"));

                wrapper.like(StringUtils.isNotEmpty(entname),TSSerIllegalList::getEntname,entname);
                // 暂时只做“满3年列异”业务的勘误
                wrapper.in(TSSerIllegalList::getSerillrea,"01","0001");
//                wrapper.exists(StringUtils.isNotEmpty(sourceType),
//                        String.format("select 1 from tsbizserillegal " +
//                                "where tsbizserillegal.bizseq = tsserillegallist.bizseq and tsbizserillegal.sourceType = '%s'", sourceType)
//                        );
                if(StringUtils.isNotEmpty(searchCode)){
                    if(StringUtils.isUscc(searchCode)){
                        wrapper.eq(TSSerIllegalList::getUniscid,searchCode);
                    }else {
                        wrapper.eq(TSSerIllegalList::getRegno,searchCode);
                    }
                }
                }, each -> {
            TRBaseCode code = codeMap.get(each.getSerillrea());
            if(code != null){
                each.setSerillreaString(code.getName());
            }
        }));
    }

    /**
     * 列严勘误流程待办创建
     *
     * @param listId  异议列表id
     * @param request 请求
     * @return 创建结果
     * @author lroyia
     * @since 2021年4月25日 19:16:51
     */
    @ApiOperation("列严勘误流程待办创建")
    @PostMapping("createTask")
    @Transactional(rollbackFor = Exception.class)
    public RestResult<?> createTask(@ApiParam("异议列表id") String listId, HttpServletRequest request) {
        // 参数校验
        AssertUtils.isNotBlank(listId);
        TSSerIllegalList illList = serIllegalListService.getById(listId);
        if (illList == null) return RestResult.error(ResultCode.PARAM_IS_INVALID);

        // 在办业务验证
        int existsBus = bizCorrectionsService.count(new LambdaQueryWrapper<BizCorrections>()
                .eq(BizCorrections::getBusId, illList.getIllegallistid())
                .eq(BizCorrections::getState, Constant.TRUE_1_STR));
        if (existsBus > 0) {
            return RestResult.error(ResultCode.DATA_ALREADY_EXISTED,"该记录已发起勘误流程");
        }

        AICUser curUser = getLoginUser(request);
        TSBizSerIllegal bizSerIllegal = tsBizSerIllegalService.getById(listId);

        String bizseq = UUID.randomUUID().toString();
        BizCorrections bizCorrections = new BizCorrections()
                .setBizseq(bizseq)
                .setBustype(Constant.TRUE_1_STR)
                .setBusId(listId)
                .setPFactDesc(bizSerIllegal.getLostcreditexplain())
                .setFactDesc(bizSerIllegal.getLostcreditexplain())
                .setPReason(illList.getSerillrea())
//                .setReason(illList.getSerillrea())
                .setEntname(illList.getEntname())
                .setPripid(illList.getPripid())
                .setRegno(illList.getRegno())
                .setState(Constant.TRUE_1_STR);
        boolean save = bizCorrectionsService.save(bizCorrections);
        if(!save){
            throw new BusinessException("发起勘误流程失败");
        }
        // 拷贝原业务附件，作为勘误流程的“原材料”，后续上传的作为新材料
        boolean update = bizCorrectionsService.updateBizFile(bizSerIllegal.getCorrectBizseq(), bizSerIllegal.getBizseq(), bizseq,"illegal");
        if(!update) {
            throw new BusinessException("发起勘误流程失败");
        }
        // 创建勘误
        TSTaskList taskListModel = new TSTaskList();
        taskListModel.setBizseqid(bizseq);
        taskListModel.setBustype(BaseDataConstant.CORRECTIONS_ILLEGAL_BIZ);// 勘误流程
        taskListModel.setBusname(illList.getEntname() + "列严勘误");
        bizCorrectionsService.createTask(curUser, taskListModel, bizCorrections);
        if (StringUtils.isNotBlank(taskListModel.getTasklistid())) {
            Map<String, Object> result = new HashMap<>();
            result.put("tasklistid", taskListModel.getTasklistid());
            result.put("bizseq", bizseq);
            result.put("workflowId", taskListModel.getWorkflowid());
            return RestResult.ok(result);
        }
        throw new BusinessException("发起勘误流程失败");
    }

    /**
     * 进入下一个勘误流程
     *
     * @param processDto 流转信息
     * @return 处理结果
     * @author lroyia
     * @since 2021年4月26日 14:22:42
     */
    @PostMapping("nextProcess")
    @ApiOperation("进入下一个勘误流程")
    @Transactional(rollbackFor = Exception.class)
    public RestResult<?> nextProcess(@ApiParam("流转信息") CorrectionsProcessDto processDto, HttpServletRequest request) {
        // 参数校验
        AssertUtils.isNotNull(processDto);
        AssertUtils.isNotBlank(processDto.getNextNodeId(), processDto.getBizseq(),
                processDto.getNextUserIds(), processDto.getNextUserNames(),
                processDto.getOpiniontype(), processDto.getCurNodeId(),
                processDto.getOpinioncontent(), processDto.getTasklistid(), processDto.getWorkflowId());

        AICUser curUser = getLoginUser(request);

        // 读取必须参数
        String link = String.format("%s_%s", processDto.getCurNodeId(), processDto.getNextNodeId());
        String[] ids = null;
        String[] names = null;
        if("approvelist_handleFeedback".equals(link) || "handleFeedback_feedbackEnter".equals(link)){
            String userId = workFlowService.findLastTwfprocessnodeByProcessidAndNodename(processDto.getWorkflowId(), processDto.getCurNodeId(), processDto.getNextNodeId());
            if (StringUtils.isEmpty(userId)){
                return RestResult.error(ResultCode.DATA_NONE);
            }

            TUsers userInfo = usersService.selectTusersById(userId);
            ids = new String[]{userInfo.getUserid()};
            names = new String[]{userInfo.getRealname()};
        }else {
            ids = StringUtils.split(processDto.getNextUserIds(), ",");
            names = StringUtils.split(processDto.getNextUserNames(), ",");
        }
        TSTaskList taskListModel = taskListService.selectByTasklistID(processDto.getTasklistid());
        TSOpinion opinionModel = new TSOpinion()
                .setHandler(curUser.getName())
                .setHandlerid(curUser.getPrimaryKey())
                .setWorkflowid(taskListModel.getWorkflowid())
                .setOpiniontype(processDto.getOpiniontype())
                .setHandledate(LocalDateTime.now())
                .setOpinioncontent(processDto.getOpinioncontent());
        List<BizCorrections> corrections = bizCorrectionsService.list(new LambdaQueryWrapper<BizCorrections>().eq(BizCorrections::getBizseq, taskListModel.getBizseqid()));
        if (StringUtils.isNotBlank(processDto.getReason()) && StringUtils.isNotBlank(processDto.getFactDesc())) {
            for (BizCorrections each : corrections) {
                each.setFactDesc(processDto.getFactDesc());
                each.setReason(processDto.getReason());
            }
        }
        // 处理流程
        bizCorrectionsService.nextProcess(curUser, taskListModel, opinionModel, processDto.getNextNodeId(), ids, names, corrections.toArray(new BizCorrections[0]));
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("bizseq", taskListModel.getBizseqid());
        resultMap.put("workflowid", taskListModel.getWorkflowid());
        resultMap.put("nextNodeID", processDto.getNextNodeId());
        resultMap.put("tasklistid", processDto.getTasklistid());

        return RestResult.ok(resultMap);
    }

    /**
     * 加载原列严业务附件清单
     * @param busId        列严业务表主键id
     * @return
     */
    @PostMapping("loadOldFileList")
    public RestResult<?> loadOldFileList(String busId){
        AssertUtils.isNotEmpty(busId);
        TSSerIllegalList serIllegalList = serIllegalListService.getById(busId);
        String bizseq = serIllegalList.getBizseq();
        List<TSAttachment> attachmentList = attachmentService.getIllegalIncFileList(bizseq);
        for (TSAttachment tsAttachment : attachmentList) {
            if(StringUtils.isBlank(tsAttachment.getTemppath())){
                tsAttachment.setTemppath(tsAttachment.getFileurl());
            }
        }
        return RestResult.ok(attachmentList);
    }
}
