package com.chinaweal.aiccs.aiccs.fraudreg.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinaweal.aiccs.aiccs.abnormal.entity.EBaseinfo;
import com.chinaweal.aiccs.aiccs.abnormal.service.EBaseinfoService;
import com.chinaweal.aiccs.aiccs.auditing.service.TSOpinionService;
import com.chinaweal.aiccs.aiccs.business.entity.TSTaskList;
import com.chinaweal.aiccs.aiccs.business.service.TSTaskListService;
import com.chinaweal.aiccs.aiccs.business.service.WorkFlowService;
import com.chinaweal.aiccs.aiccs.fraudreg.dto.FraudProcessDto;
import com.chinaweal.aiccs.aiccs.fraudreg.entity.*;
import com.chinaweal.aiccs.aiccs.fraudreg.service.*;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.org.service.AicorgService;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.youfool.framework.springboot.base.query.BaseQuery;
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.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.chinaweal.aiccs.common.base.controller.BaseController;

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


/**
 * <p>
 * 撤销登记结果录入 控制器
 * </p>
 *
 * @author lwd
 * @since 2023-01-30
 */
@Api(tags = "1.撤销登记结果录入业务流程")
@ApiSort(1)
@RestController
@RequestMapping("/fraudreg/resultEntry")
public class TFraudEntryController extends BaseController{

    @Autowired
    private EBaseinfoService eBaseinfoService;

    @Autowired
    private AicorgService aicorgService;

    @Resource
    private ITFraudEntService itFraudEntService;

    @Resource
    private ITBizFraudService iTBizFraudService;

    @Resource
    private IFraudEntryService iFraudEntryService;

    @Resource
    private TSTaskListService taskListService;

    @Resource
    private IVFraudInfoService ivFraudInfoService;

    @Resource
    private RevokeFraudService revokeFraudService;

    @Resource
    private ITBizFraudService itBizFraudService;

    @Resource
    private ITFraudPersonService itFraudPersonService;

    @Resource
    private TSOpinionService tsOpinionService;

    @Resource
    private ITFraudCheckService itFraudCheckService;

    @Resource
    private WorkFlowService workFlowService;

    @Resource
    private EBaseinfoService eBaseInfoService;

    /**
     * 获取企业主体列表分页
     *
     * @author lwd
     * @since 2023-01-31
     */
    @ApiOperation(value = "1.获取企业主体列表分页", position = 1)
    @PostMapping(value = "ebaseinfoPage")
    public RestResult<?> ebaseinfoPage(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) throw new BusinessException("登录超时,请重新登录");
        Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();

        IPage<EBaseinfo> listPage = eBaseinfoService.comprehensiveQuery(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()),customParamMap);

        return RestResult.ok(listPage);

    }


    /**
     * 判断该企业是否有在办撤销案件
     *
     * @author lwd
     * @since 2023-01-31
     */
    @ApiOperation(value = "2.判断该企业是否有在办撤销案件", position = 2)
    @PostMapping(value = "ebaseinfoTFraudCheck")
    public RestResult<?> ebaseinfoTFraudCheck(@RequestParam String uscc, @RequestParam String entName) {

        TFraudEnt tFraudEnt = new TFraudEnt();

        //判断入参为统一码还是注册号
        if (StringUtils.isNotBlank(uscc)) {
            if(StringUtils.isUscc(uscc)){
                tFraudEnt.setUniScId(uscc);
            }else {
                tFraudEnt.setRegNo(uscc);
            }
        }

        tFraudEnt.setEntName(entName);
        BaseQuery<TFraudEnt> query = new BaseQuery<>();
        query.setEntity(tFraudEnt);

        //判断企业是否有在办撤销案件
        IPage<TFraudEnt> tFraudEntIPage = itFraudEntService.listTFraudEntByEntName(query);

        if (tFraudEntIPage.getRecords().size() > 0){

            for (int i = 0; i < tFraudEntIPage.getRecords().size(); i++) {
                TBizFraud tBizFraud = iTBizFraudService.getTBizFraudByBizSeq(tFraudEntIPage.getRecords().get(i).getBizSeq());
                if (tBizFraud != null){
                    if ("1".equals(tBizFraud.getStatus()) || "2".equals(tBizFraud.getStatus())){
                        return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR,tFraudEntIPage.getRecords().get(i));
                    }
                }
            }

        }

        return RestResult.ok();

    }

    /**
     * 启动撤销案件录入结果流程待办
     *
     * @author lwd
     * @since 2023-01-31
     */
    @ApiOperation(value = "3.启动撤销案件录入结果流程待办", position = 3)
    @PostMapping("/startTaskEasyTFraud")
    public RestResult<?> startTaskEasyTFraud(@RequestParam String uscc, @RequestParam String entName, HttpServletRequest request) {

        return RestResult.ok(iFraudEntryService.startTaskEasyTFraud(uscc, entName,getLoginUser(request)));
    }

    @ApiOperation(value = "4.撤销案件录入结果流程控制", position = 4)
    @PostMapping("/processControlEasyTFraud")
    public RestResult<?> processControlEasyTFraud(@RequestBody @Validated FraudProcessDto fraudProcessDto, BindingResult bindingResult, HttpServletRequest request) {
        AssertUtils.isBndingValidit(bindingResult);

        List<TSTaskList> listTask = taskListService.selectByBizSeqID(fraudProcessDto.getBizSeq());
        AssertUtils.isTrue(!listTask.isEmpty(), ResultCode.DATA_NONE);

        String msg = iFraudEntryService.processControlEasyTFraud(fraudProcessDto, listTask.get(0), getLoginUser(request));
        if(!msg.equals("success")) return RestResult.error(ResultCode.INTERFACE_OUTER_INVOKE_ERROR,msg);
        return RestResult.ok();
    }

    @ApiOperation(value = "5.分页查询已完成撤销案件", position = 5)
    @PostMapping("/overTfraudPage")
    public RestResult<IPage<VFraudInfo>> overTfraudPage(@RequestBody PageRequestDto pageRequestDto) {


        IPage<VFraudInfo> data = ivFraudInfoService.defaultPaging(pageRequestDto, wrapper -> {

            Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
            if(customParamMap == null) return;


            wrapper.lambda().eq(VFraudInfo::getStatus,"3");
            wrapper.lambda().notExists("select 1 from revoke_tbiz_fraud r where v_fraud_info.uniScId = r.unisCid and v_fraud_info.bizSeq = r.bizseqOld and r.status = '3'");
            //判断入参为统一码还是注册号
            if (StringUtils.isNotBlank((CharSequence) customParamMap.get("searchUscc"))){
                if (StringUtils.isUscc((String) customParamMap.get("searchUscc"))){
                    wrapper.lambda().eq(VFraudInfo::getUniScId,customParamMap.get("searchUscc"));
                }else {
                    wrapper.lambda().eq(VFraudInfo::getRegNo,customParamMap.get("searchUscc"));
                }
            }

            //企业名称
            if (StringUtils.isNotBlank((CharSequence) customParamMap.get("entName"))){
                wrapper.lambda().like(VFraudInfo::getEntName,customParamMap.get("entName"));
            }

            //撤销决定原因
            if (StringUtils.isNotBlank((CharSequence) customParamMap.get("handleResult"))){
                wrapper.lambda().like(VFraudInfo::getHandleResult,customParamMap.get("handleResult"));
            }

//            //业务类型
//            if (StringUtils.isNotBlank((CharSequence) customParamMap.get("businessType"))){
//                wrapper.lambda().eq(VFraudInfo::getBusinessType,customParamMap.get("businessType"));
//            }

            //决定日期自定义处理
            String judDate = StringUtils.tranObject(customParamMap.get("judDate"));
            if(StringUtils.isNotBlank(judDate)){
                String judDate1  =judDate.split(",")[0].substring(1,judDate.split(",")[0].length());
                String judDate2  =judDate.split(",")[1].substring(0,judDate.split(",")[1].length()-1);
                wrapper.lambda().ge(VFraudInfo::getJudDate, judDate1).le(VFraudInfo::getJudDate, judDate2);
            }

        }, null);
        return RestResult.ok(data);
    }


    /**
     * 启动撤销案件流程待办
     *
     * @author lwd
     * @since 2023-02-13
     */
    @ApiOperation(value = "6.启动撤销案件流程待办", position = 6)
    @PostMapping("/startTaskRevokeTFraud")
    public RestResult<?> startTaskRevokeTFraud(@RequestParam String uscc, @RequestParam String bizSeq, HttpServletRequest request) {

        return RestResult.ok(revokeFraudService.startTaskRevokeTFraud(uscc, bizSeq,getLoginUser(request)));
    }

    /**
     * 获取撤销业务相关业务信息
     *
     * @author lwd
     * @since 2023-02-13
     */
    @ApiOperation(value = "7.获取撤销业务相关业务信息", position = 7)
    @GetMapping("/getCxBusFraudInfo")
    public RestResult<Map<String, Object>> getCxBusFraudInfo(@RequestParam @ApiParam("业务主键") String bizSeq,
                                                           @RequestParam @ApiParam("工作流id") String workflowId,
                                                           @RequestParam @ApiParam("是否只读 0-否 1-是") String readOnly) {
        AssertUtils.isNotBlank(bizSeq, workflowId,bizSeq);
        Map<String, Object> result = new HashMap<>();
        LambdaQueryWrapper<RevokeTBizFraud> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(RevokeTBizFraud:: getBizSeq ,bizSeq);
        RevokeTBizFraud revokeTBizFraud = revokeFraudService.getOne(lambdaQueryWrapper);
        result.put("bizFraudInfo", itBizFraudService.getTBizFraudByBizSeq(revokeTBizFraud.getBizseqOld()));
        result.put("fraudEntInfo", itFraudEntService.getByBizSeq(revokeTBizFraud.getBizseqOld()));
        result.put("fraudPersonInfo", itFraudPersonService.getByBizSeq(revokeTBizFraud.getBizseqOld()));
        result.put("opinions", tsOpinionService.getOpinionsWithOrg(workflowId));
        result.put("revokeTBizFraudInfo", revokeTBizFraud);
        result.put("entInfo", eBaseInfoService.getEntBaseInfoByCode(revokeTBizFraud.getUnisCid() == null ? revokeTBizFraud.getUnisCid():revokeTBizFraud.getRegNo()));
        if ("0".equals(readOnly)) result.put("nextSequenceFlowList", workFlowService.findNextSequenceFlowList(workflowId));
        return RestResult.ok(result);
    }

    /**
     * 撤销撤销案件流程控制
     *
     * @author lwd
     * @since 2023-02-15
     */
    @ApiOperation(value = "8.撤销撤销案件流程控制", position = 8)
    @PostMapping("/processControlrevokeTFraud")
    public RestResult<?> processControlrevokeTFraud(@RequestBody @Validated FraudProcessDto fraudProcessDto, BindingResult bindingResult, HttpServletRequest request) {
        AssertUtils.isBndingValidit(bindingResult);

        List<TSTaskList> listTask = taskListService.selectByBizSeqID(fraudProcessDto.getBizSeq());
        AssertUtils.isTrue(!listTask.isEmpty(), ResultCode.DATA_NONE);

        String msg = revokeFraudService.processControlrevokeTFraud(fraudProcessDto, listTask.get(0), getLoginUser(request));
        if(!msg.equals("success")) return RestResult.error(ResultCode.INTERFACE_OUTER_INVOKE_ERROR,msg);
        return RestResult.ok();
    }

    /**
     * 判断该企业是否有可以办理撤销撤销案件
     *
     * @author lwd
     * @since 2023-02-16
     */
    @ApiOperation(value = "9.判断该企业是否有可以办理撤销撤销案件", position = 9)
    @PostMapping(value = "ebaseinfoRevokeTFraudCheck")
    public RestResult<?> ebaseinfoRevokeTFraudCheck(@RequestParam String uscc, @RequestParam String bizSeq) {

        RevokeTBizFraud revokeTBizFraud = new RevokeTBizFraud();


                 //获取对应的撤销业务
        LambdaQueryWrapper<TBizFraud> lambdaQueryWrappera = new LambdaQueryWrapper();
        lambdaQueryWrappera.eq(TBizFraud :: getBizSeq ,bizSeq);
        TBizFraud tBizFraud = itBizFraudService.getOne(lambdaQueryWrappera);

                 // 封装参数
        LambdaQueryWrapper<EBaseinfo> wrappera = new LambdaQueryWrapper<>();
        wrappera.eq(EBaseinfo::getUniscid,uscc);
        // 查询基本信息
        EBaseinfo eBaseinfo = eBaseInfoService.getOne(wrappera);
        if ("2".equals(tBizFraud.getBusinessType())){

            if (!"1".equals(eBaseinfo.getRegstate())){
                return RestResult.error(ResultCode.SPECIFIED_QUESTIONED_USER_NOT_EXIST,"该企业状态不允许撤销撤销变更");
            }
        }else if ("3".equals(tBizFraud.getBusinessType())){
            if (!"1".equals(eBaseinfo.getRegstate()) && !"2".equals(eBaseinfo.getRegstate())){
                return RestResult.error(ResultCode.SPECIFIED_QUESTIONED_USER_NOT_EXIST,"该企业状态不允许撤销撤销注销");
            }
        }

        LambdaQueryWrapper<RevokeTBizFraud> wrapper = new LambdaQueryWrapper<>();
        //判断入参为统一码还是注册号
        if (StringUtils.isNotBlank(uscc)) {
            if(StringUtils.isUscc(uscc)){
                revokeTBizFraud.setUnisCid(uscc);
                wrapper.eq(RevokeTBizFraud::getUnisCid,uscc);
            }else {
                wrapper.eq(RevokeTBizFraud::getRegNo,uscc);
            }
        }
        wrapper.eq(RevokeTBizFraud::getBizseqOld,bizSeq);

        //判断企业是否有在办撤销撤销案件
        List<RevokeTBizFraud> revokeTBizFraudList = revokeFraudService.list(wrapper);

        if (revokeTBizFraudList.size() > 0){

            for (int i = 0; i < revokeTBizFraudList.size(); i++) {
                RevokeTBizFraud revokeTBizFraud1 = revokeTBizFraudList.get(i);
                if (revokeTBizFraud1 != null){
                    if ("1".equals(revokeTBizFraud1.getStatus()) || "2".equals(revokeTBizFraud1.getStatus())){
                        return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR,revokeTBizFraud1);
                    }else if ("3".equals(revokeTBizFraud1.getStatus())){
                        return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR,revokeTBizFraud1);
                    }
                }
            }

        }

        return RestResult.ok();

    }
}
