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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinaweal.aiccs.aiccs.abnormal.entity.*;
import com.chinaweal.aiccs.aiccs.abnormal.entity.dto.DissentApplyInfoTableDto;
import com.chinaweal.aiccs.aiccs.abnormal.entity.dto.EntWritsDto;
import com.chinaweal.aiccs.aiccs.abnormal.service.*;
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.service.TSTaskListService;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSBizSerIllegal;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSBizSerIllegalDiss;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSBizSerIllegalRem;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSSerIllegalList;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.dto.DissentApplyEntInfoDto;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.dto.ExamineInfoTableDto;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.dto.RemApplyMsgDto;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.dto.writ.IllegalDissentAcceptWritDto;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.dto.writ.IllegalDissentResultWritDto;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.dto.writ.IllegalRemoveDecisionWritDto;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.dto.writ.RemAcceptReceiptWritDto;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSBizSerIllegalDissService;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSBizSerIllegalRemService;
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.constant.TaskBusinessTypeConstant;
import com.chinaweal.aiccs.common.util.*;
import com.chinaweal.aiccs.common.util.filestorage.FileStorageService;
import com.chinaweal.aiccs.config.CommonConfig;
import com.chinaweal.aiccs.crgs.entbase.service.TCompanyDetailsService;
import com.chinaweal.aiccs.org.entity.OrgUnits;
import com.chinaweal.aiccs.org.service.AicorgService;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.aicorg.services.OrgUM;
import com.chinaweal.solr.entity.EBaseInfoSolrBean;
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 io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author Lee
 * @Since 2021/3/2 15:42
 */
@RestController
@RequestMapping("/writ")
public class WritController extends BaseController {
    @Autowired
    private TSWritService tsWritService;
    @Autowired
    private TSBizSpeListService tsBizSpeListService;
    @Autowired
    private TCompanyDetailsService tCompanyDetailsService;
    @Autowired
    private TSAbnListService tsAbnListService;
    @Autowired
    private TSBizRemListService tsBizRemListService;
    @Autowired
    private TSBizSerIllegalService bizSerIllegalService;
    @Autowired
    private OrgUM orgUM;
    @Autowired
    private TRBaseCodeService baseCodeService;
    @Autowired
    private TSBizSerIllegalRemService bizSerIllegalRemService;
    @Autowired
    private TSBizSerIllegalDissService bizSerIllegalDissService;
    @Autowired
    private TSTaskListService taskListService;
    @Autowired
    private TSOpinionService opinionService;
    @Autowired
    private EBaseinfoService eBaseinfoService;
    @Autowired
    private TSBizDissentService tsBizDissentService;
    @Resource
    private TSSerIllegalListService tsSerIllegalListService;
    @Autowired
    private AicorgService aicorgService;
    @Resource
    private FileStorageService fileStorageService;

    /**
     * 通过业务号id获取文书文号信息 企业异常列入
     * @param bizseq 业务号id
     * @param writstype 文书类型
     * @return
     */
    @GetMapping(value = "/getWritByBizseq")
    public RestResult<?> getWritByBizseq(String bizseq,String writstype){
        AssertUtils.isNotBlank(bizseq,writstype);
        ArrayList<HashMap<String, Object>> resultList = new ArrayList<>();
        ArrayList<Object> ids = new ArrayList<>();
        //业务表id 找到主键id 多个
        if(WorkNoUtil.WORKNOTYPE_11.equals(writstype)){//企业列入经营异常名录决定书
            QueryWrapper<TSBizSpeList> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(TSBizSpeList::getBizseq,bizseq)
                    .eq(TSBizSpeList::getIsRemove,"0")
                    .select(TSBizSpeList::getSpelistid);
            List<TSBizSpeList> speListsIds = tsBizSpeListService.list(wrapper);
            for (TSBizSpeList speListsId : speListsIds) {
                ids.add(speListsId.getSpelistid());
            }

        }else if(WorkNoUtil.WORKNOTYPE_15.equals(writstype)){//企业移出经营异常名录决定书

            QueryWrapper<TSBizRemList> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(TSBizRemList::getBizseq,bizseq)
                    .select(TSBizRemList::getAbnlistid);
            List<TSBizRemList> abnlistIds =tsBizRemListService.list(wrapper);
            for (TSBizRemList abnlistid : abnlistIds) {
                ids.add(abnlistid.getAbnlistid());
            }
        }

        //主键id就是异常表id
        List<TSAbnList> abnLists = tsAbnListService.list(new LambdaQueryWrapper<TSAbnList>().in(TSAbnList::getAbnlistid, ids));

        for (TSAbnList abnList : abnLists) {
            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("entname",abnList.getEntname());
            resultMap.put("specause",abnList.getSpecause());
            resultMap.put("remexcpres",abnList.getRemexcpres());
//            resultMap.put("ReconsiderationOrg",abnList.getReconsiderationOrg());//行政复议机关
            resultMap.put("remreasons",abnList.getRemreasons());

            TSWrit writQueryModel = new TSWrit();//文书号
            writQueryModel.setWritstype(writstype);
            writQueryModel.setPripid(abnList.getPripid());
            writQueryModel.setBizseq(bizseq);
            List<TSWrit> tsWritQueryModels = tsWritService.listTswrit(writQueryModel);
            if (CollectionUtils.isNotEmpty(tsWritQueryModels)) {
                resultMap.put("decisionContent",tsWritQueryModels.get(0).getContent());
                resultMap.put("wrirsno", tsWritQueryModels.get(0).getWritsno());
                resultMap.put("createtime",tsWritQueryModels.get(0).getCreatetime());
                resultMap.put("areacode",tsWritQueryModels.get(0).getAreaCode());
                String areaName = ConstantsUtil.getAreaName(tsWritQueryModels.get(0).getAreaCode());
                resultMap.put("areaname",areaName);
//                resultMap.put("writsname", tsWritQueryModels.get(0).getWritsno());
            }
            resultList.add(resultMap);
        }

//        List<TSBizSpeList> list = tsBizSpeListService.list(new LambdaQueryWrapper<TSBizSpeList>().eq(TSBizSpeList::getBizseq, bizseq));
//        ArrayList<HashMap<String, Object>> resultList = new ArrayList<>();
//        for (TSBizSpeList tsBizSpeListModel : list) {
//            HashMap<String, Object> resultMap = new HashMap<>();
//            TSWrit writQueryModel = new TSWrit();//文书号
//            writQueryModel.setWritstype(writstype);
//            writQueryModel.setPripid(tsBizSpeListModel.getPripid());
//            writQueryModel.setBizseq(tsBizSpeListModel.getBizseq());
//            List<TSWrit> tsWritQueryModels = tsWritService.listTswrit(writQueryModel);
//            if (CollectionUtils.isNotEmpty(tsWritQueryModels)) {
//                resultMap.put("wrirsno", tsWritQueryModels.get(0).getWritsno());
//  //                resultMap.put("writsname", tsWritQueryModels.get(0).getWritsno());
//            }
//            resultMap.put("entname",tsBizSpeListModel.getEntname());
//            resultMap.put("specause",tsBizSpeListModel.getSpecause());
//            resultList.add(resultMap);
//        }

       return RestResult.ok(resultList);
    }

    /**
     * 列异异议相关文书，通过业务号id获取文书号及主体信息
     * @param bizseq 业务号id
     * @param writstype 文书类型
     * @return
     */
    @GetMapping(value = "/getNoticePrintInfo")
    public RestResult<?> getNoticePrintInfo(String bizseq,String writstype){
        AssertUtils.isNotBlank(bizseq,writstype);
        List<TSWrit> list = tsWritService.list(new LambdaQueryWrapper<TSWrit>().eq(TSWrit::getBizseq, bizseq).eq(TSWrit::getWritstype,writstype));
        ArrayList<HashMap<String, Object>> resultList = new ArrayList<>();
        for (TSWrit tsWritModel : list) {
            HashMap<String, Object> resultMap = new HashMap<>();
            EBaseinfo eBaseinfo = eBaseinfoService.getOne(new LambdaQueryWrapper<EBaseinfo>().eq(EBaseinfo::getPripid, tsWritModel.getPripid()));
            resultMap.put("entname",eBaseinfo.getEntname());
            resultMap.put("wrirsno",tsWritModel.getWritsno());
            resultMap.put("createtime",tsWritModel.getCreatetime());
            resultMap.put("areacode",tsWritModel.getAreaCode());
            resultMap.put("writsid",tsWritModel.getWritsid());
            if(WorkNoUtil.WORKNOTYPE_14.equals(writstype) && StringUtils.isNotEmpty(tsWritModel.getContent())){
                resultMap.put("content",tsWritModel.getContent().replace(BaseDataConstant.ABN_DISSENT_RESULT_NOTICE_CONTENT,StringUtils.EMPTY));
            }
//            else if(WorkNoUtil.WORKNOTYPE_13.equals(writstype) && StringUtils.isNotEmpty(tsWritModel.getContent())){
//                resultMap.put("content",tsWritModel.getContent().replace(BaseDataConstant.ABN_DISSENT_DISAGREE_ACCEPT_CONTENT,StringUtils.EMPTY));
//            }
            else {
                resultMap.put("content",tsWritModel.getContent());
            }
            String cityName = Constant.NM_REGION_CODE.get(tsWritModel.getAreaCode().substring(0,4)+"00");
            String areaName = Constant.NM_LOC_REGION_CODE.get(tsWritModel.getAreaCode());
            areaName = StringUtils.equals(tsWritModel.getAreaCode(),"150000") ? "内蒙古自治区" : cityName + areaName;
            resultMap.put("areaname",areaName);
            resultList.add(resultMap);
        }
        return RestResult.ok(resultList);
    }

    /**
     * 通过业务号id获取文书信息
     * @param bizSeqId 业务号
     * @return 获取结果
     * @author lroyia
     * @since 2021年3月15日 17:26:05
     */
    @GetMapping("getWritListByBizseqId")
    public RestResult<?> getWritListByBizseqId(String bizSeqId){
        return RestResult.ok(tsWritService.list(new LambdaQueryWrapper<TSWrit>().eq(TSWrit::getBizseq,bizSeqId)));
    }

    /**
     * 严重违法失信企业列入决定文书信息获取
     * @param bizSeqId 业务号
     * @return 获取结果
     * @author lroyia
     * @since 2021年3月15日 19:08:48
     */
    @ApiOperation("严重违法失信企业列入决定文书信息获取")
    @GetMapping("illegal/getInclusionDecisionWritByBizSeqId")
    public RestResult<?> getIllegalInclusionDecisionWritByBizSeqId(@ApiParam("业务号") String bizSeqId) {
        AssertUtils.isNotBlank(bizSeqId);
        TSSerIllegalList tsserillegallist = tsSerIllegalListService.getOne(new LambdaQueryWrapper<TSSerIllegalList>().eq(TSSerIllegalList::getBizseq, bizSeqId));
        TSBizSerIllegal tsBizSerIllegal = bizSerIllegalService.getOne(new LambdaQueryWrapper<TSBizSerIllegal>().eq(TSBizSerIllegal::getBizseq, bizSeqId));
        TSWrit tsWrit = tsWritService.getOne(new LambdaQueryWrapper<TSWrit>().eq(TSWrit::getBizseq, bizSeqId));
        EBaseinfo eBaseinfo = new EBaseinfo();
        // 可能还没保存到严总违法名单
        if (tsserillegallist == null) {
            eBaseinfo = eBaseinfoService.getById(tsBizSerIllegal.getPripid());
        } else {
            eBaseinfo = eBaseinfoService.getById(tsserillegallist.getPripid());
        }
        List<Map<String, Object>> result = new ArrayList<>();
        Map<String, Object> data = new LinkedHashMap<>();

        data.put("tsBizSerIllegal",tsBizSerIllegal);
        data.put("tsserillegallist",tsserillegallist);
        data.put("tsWrit",tsWrit);
        data.put("eBaseinfo",eBaseinfo);
        result.add(data);
        return RestResult.ok(result);
    }

    /**
     * 拟列严文书获取
     * @param bizSeqId
     * @return
     */
    @GetMapping("illegal/getIllegalInclusionWritByBizSeqId")
    public RestResult<?> getIllegalInclusionWritByBizSeqId(String bizSeqId){
        Map<String, Object> rs = new HashMap<>();
        List<Map<String, Object>> paperInfo = new ArrayList<>();
        List<TSBizSerIllegal> tsBizSerIllegals = bizSerIllegalService.list(
                new LambdaQueryWrapper<TSBizSerIllegal>().eq(TSBizSerIllegal::getBizseq, bizSeqId)
        );
        for (TSBizSerIllegal tsBizSerIllegal : tsBizSerIllegals) {
            Map<String, Object> map = new HashMap<>();
            TSWrit tsWrit = tsWritService.getOne(new LambdaQueryWrapper<TSWrit>()
                    .eq(TSWrit::getBizseq, tsBizSerIllegal.getBizseq()).eq(TSWrit::getPripid,tsBizSerIllegal.getPripid()));
            map.put("tsWrit", tsWrit);
            map.put("tsBizSerIllegal",tsBizSerIllegal);
            paperInfo.add(map);
        }
        TSBizSerIllegal tsBizSerIllegalOne = tsBizSerIllegals.get(0);
        String decorg = tsBizSerIllegalOne.getDecorg();
        OrgUnits orgUnits = aicorgService.queryByOrgNumber(decorg);
        String decorgCn = orgUnits.getOrgUnitName();
        if (!decorgCn.startsWith("广州市")) { // 兼容新旧组织架构
            decorgCn = "广州市" + decorgCn;
        }
        rs.put("paperInfo", paperInfo);
        rs.put("decorgCn", decorgCn);
        return RestResult.ok(rs);
    }

    /**
     * 严重违法失信企业移出决定文书信息获取
     * @param bizSeqId 业务号
     * @return 获取结果
     * @author lroyia
     * @since 2021年3月16日 10:15:21
     */
    @ApiOperation("严重违法失信企业列入决定文书信息获取")
    @GetMapping("illegal/getRemoveDecisionWritByBizSeqId")
    public RestResult<?> getIllegalRemoveDecisionWritByBizSeqId(@ApiParam("业务号") String bizSeqId){
        AssertUtils.isNotBlank(bizSeqId);
        List<TSBizSerIllegalRem> records = bizSerIllegalRemService.list(new LambdaQueryWrapper<TSBizSerIllegalRem>().eq(TSBizSerIllegalRem::getBizSeq, bizSeqId));
        if(CollectionUtils.isEmpty(records)) return OK;
        List<TSWrit> writList = tsWritService.list(new LambdaQueryWrapper<TSWrit>().eq(TSWrit::getBizseq, bizSeqId));

        // 地区编码列表
        Map<String, TRBaseCode> baseCodeMap = baseCodeService.getBaseCodeMapFormCache("CA01");
        // 列入移出原因
        Map<String, TRBaseCode> serCodeMap = baseCodeService.getBaseCodeMapFormCache("CD73");
        Map<String, TRBaseCode> remCodeMap = baseCodeService.getBaseCodeMapFormCache("CD74");
        // 封装结果
        List<IllegalRemoveDecisionWritDto> result = new ArrayList<>();
        for (TSBizSerIllegalRem each : records) {
            IllegalRemoveDecisionWritDto atom = new IllegalRemoveDecisionWritDto();
            atom.setEntname(each.getEntName());
            String regionId = each.getDecOrg();
            String cityId = regionId;
            if(!regionId.endsWith("00")){
                cityId = cityId.substring(0, 4) + "00";
            }
            TRBaseCode city = baseCodeMap.get(cityId);
            TRBaseCode region = baseCodeMap.get(regionId);
            atom.setCityName(city != null ? city.getName() : StringUtils.EMPTY);
            atom.setRegionCode(regionId);
            atom.setRegionName(region != null ? region.getName() : StringUtils.EMPTY);
            for (TSWrit tsWrit : writList) {
                if(each.getPriPID().equals(tsWrit.getPripid())){
                    atom.setWritNo(tsWrit.getWritsno());
                    break;
                }
            }
            atom.setRemoveExplain(each.getLostCreditExplainrem());
            atom.setIncDecDateStr(each.getAbnTime().format(DateTimeFormatter.ofPattern(DateUtils.DATE_DEFAULT_FORMAT)));
            atom.setRemDecDateStr(each.getApprovalDate().format(DateTimeFormatter.ofPattern(DateUtils.DATE_DEFAULT_FORMAT)));
            atom.setDecOrg(regionId);
            if(StringUtils.isNotBlank(each.getRemSponsorIllegal())){
                AICUser user = orgUM.login(each.getRemSponsorIllegal());
                if(user != null){
                    atom.setDecOrgName(user.getOrgName());
                }
            }
            atom.setSerillrea(each.getSerIllRea());
            TRBaseCode reasonCode = serCodeMap.get(each.getSerIllRea());
            if(reasonCode != null){
                atom.setSerillreaStr(reasonCode.getName());
            }
            atom.setRemExcpRes(each.getRemExcpRes());
            reasonCode = remCodeMap.get(each.getRemExcpRes());
            if(reasonCode != null){
                atom.setRemExcpResStr(reasonCode.getName());
            }
            atom.setPirpid(each.getPriPID());
            atom.setRegNo(each.getRegNO());
            result.add(atom);
        }
        return RestResult.ok(result);
    }

    /**
     * 严重违法失信企业名录异议受理通知书信息获取
     * @param bizSeqId 业务号
     * @return 获取结果
     * @author lroyia
     * @since 2021年3月16日 14:17:27
     */
    @ApiOperation("严重违法失信企业名录异议受理通知书信息获取")
    @GetMapping("illegal/getDissentAcceptWritByBizSeqId")
    public RestResult<?> getIllegalDissentAcceptWritByBizSeqId(@ApiParam("业务号") String bizSeqId){
        AssertUtils.isNotBlank(bizSeqId);
        List<TSBizSerIllegalDiss> list = bizSerIllegalDissService.list(new LambdaQueryWrapper<TSBizSerIllegalDiss>().eq(TSBizSerIllegalDiss::getBizSeq, bizSeqId));
        List<IllegalDissentAcceptWritDto> result = new ArrayList<>();
        for (TSBizSerIllegalDiss each : list) {
            Boolean isaccept = Constant.TRUE_1_STR.equals(each.getAcceptStat());
            OrgUnits orgUnits = aicorgService.queryByOrgNumber(each.getAreaCode());
            IllegalDissentAcceptWritDto atom = new IllegalDissentAcceptWritDto();
            result.add(atom);
            atom.setEntname(each.getEntName());
            atom.setPirpid(each.getPriPID());
            atom.setRegNo(each.getRegNO());
            atom.setIsAccept(each.getAcceptStat());
            atom.setDecOrgName(orgUnits != null ? orgUnits.getOrgUnitName() : "广州市市场监督管理局");
            TSWrit writ = null;
            if (isaccept) { // 受理
                writ = tsWritService.getOne(new LambdaQueryWrapper<TSWrit>().eq(TSWrit::getBizseq, bizSeqId).in(TSWrit::getWritstype, WorkNoUtil.WORKNOTYPE_22));
            } else {
                writ = tsWritService.getOne(new LambdaQueryWrapper<TSWrit>().eq(TSWrit::getBizseq, bizSeqId).in(TSWrit::getWritstype, WorkNoUtil.WORKNOTYPE_23));
            }
            atom.setLauptime(writ.getLauptime());
            atom.setWritNo(writ.getWritsno());
            atom.setIsAccept(isaccept ? Constant.TRUE_1_STR : Constant.FALSE_0_STR);
        }
        return RestResult.ok(result);
    }

    /**
     * 严重违法失信企业名录异议核实结果告知书信息获取
     * @param bizSeqId 业务号
     * @return 获取结果
     * @author lroyia
     * @since 2021年3月16日 15:27:51
     */
    @ApiOperation("严重违法失信企业名录异议核实结果告知书信息获取")
    @GetMapping("illegal/getDissentResultWritByBizSeqId")
    public RestResult<?> getIllegalDissentResultWritByBizSeqId(@ApiParam("业务号") String bizSeqId){
        AssertUtils.isNotBlank(bizSeqId);
        List<TSBizSerIllegalDiss> list = bizSerIllegalDissService.list(new LambdaQueryWrapper<TSBizSerIllegalDiss>().eq(TSBizSerIllegalDiss::getBizSeq, bizSeqId));
        TSWrit writ = tsWritService.getOne(new LambdaQueryWrapper<TSWrit>().eq(TSWrit::getBizseq, bizSeqId).eq(TSWrit::getWritstype, WorkNoUtil.WORKNOTYPE_24));
        List<IllegalDissentResultWritDto> result = new ArrayList<>();
        for (TSBizSerIllegalDiss each : list) {
            OrgUnits orgUnits = aicorgService.queryByOrgNumber(each.getAreaCode());
            IllegalDissentResultWritDto atom = new IllegalDissentResultWritDto();
            result.add(atom);
            atom.setEntname(each.getEntName());
            atom.setPirpid(each.getPriPID());
            atom.setRegNo(each.getRegNO());
            atom.setDecOrgName(orgUnits!=null ? orgUnits.getOrgUnitName() : "广州市市场监督管理局");
            atom.setWritNo(writ.getWritsno());
            atom.setResult(writ.getContent());
            atom.setWritsid(writ.getWritsid());
            atom.setLauptime(writ.getLauptime());
        }
        return RestResult.ok(result);
    }

    /**
     * 严重违法失信企业名录异议主体信息获取
     * @param bizSeqId 业务号
     * @return 获取结果
     * @author lroyia
     * @since 2021年3月16日 16:16:26
     */
    @ApiOperation("严重违法失信企业名录异议主体信息获取")
    @GetMapping("illegal/getDissentApplyEntInfo")
    public RestResult<?> getDissentApplyEntInfo(@ApiParam("业务号") String bizSeqId){
        AssertUtils.isNotBlank(bizSeqId);
        List<TSBizSerIllegalDiss> entList = bizSerIllegalDissService.list(new LambdaQueryWrapper<TSBizSerIllegalDiss>().eq(TSBizSerIllegalDiss::getBizSeq, bizSeqId));
        if(CollectionUtils.isEmpty(entList)) return OK;

        List<String> pripidList = entList.stream().map(TSBizSerIllegalDiss::getPriPID).collect(Collectors.toList());
        List<TSWrit> writList = tsWritService.list(new LambdaQueryWrapper<TSWrit>().in(TSWrit::getPripid, pripidList).eq(TSWrit::getWritstype, WorkNoUtil.WORKNOTYPE_21).orderByDesc(TSWrit::getLauptime));
        List<DissentApplyEntInfoDto> result = new ArrayList<>();
        for (TSBizSerIllegalDiss each : entList) {
            DissentApplyEntInfoDto atom = new DissentApplyEntInfoDto();
            result.add(atom);
            atom.setEntName(each.getEntName());
            atom.setRegNo(each.getRegNO());
            atom.setContacts(each.getContacts());
            atom.setPripid(each.getPriPID());
            atom.setTelephone(each.getTelephone());
            atom.setLeRepName(each.getLeRepName());
            atom.setDissentExplain(each.getDissentExplain());
            for (TSWrit writ : writList) {
                if(writ.getPripid().equals(each.getPriPID())){
                    atom.setIncWritNo(writ.getWritsno());
                    break;
                }
            }
        }
        return RestResult.ok(result);
    }

    /**
     * 获取审批表信息
     * @param bizSeqId 审批表信息
     * @return 获取结果
     * @author lroyia
     * @since 2021年3月16日 19:11:18
     */
    @ApiOperation("获取审批表信息")
    @GetMapping("illegal/getExamineTableInfo")
    public RestResult<?> getExamineTableInfo(@ApiParam("业务号") String bizSeqId){
        TSTaskList taskList = taskListService.getOne(new LambdaQueryWrapper<TSTaskList>().eq(TSTaskList::getBizseqid, bizSeqId));
        List<TSOpinion> opinionList = opinionService.list(new LambdaQueryWrapper<TSOpinion>().eq(TSOpinion::getWorkflowid, taskList.getWorkflowid()).orderByDesc(TSOpinion::getOpiniontype, TSOpinion::getLauptime));
        String firstOpinion = null;
        String lastOpinion = null;
        if(CollectionUtils.isNotEmpty(opinionList)){
            String tempType = opinionList.get(0).getOpiniontype();
            firstOpinion = StringUtils.tranObject(opinionList.get(0).getOpinioncontent());
            for (TSOpinion tsOpinion : opinionList) {
                if(tsOpinion.getOpiniontype().equals(tempType)){
                    lastOpinion = firstOpinion;
                    firstOpinion = StringUtils.tranObject(tsOpinion.getOpinioncontent());
                }
            }
        }
        List<ExamineInfoTableDto> result = new ArrayList<>();
        if(taskList.getBustype().equals(TaskBusinessTypeConstant.ILLEGAL_APPROVAL) || taskList.getBustype().equals(TaskBusinessTypeConstant.ILLEGAL_APPROVAL_DRAFT)){
            List<TSBizSerIllegal> list = bizSerIllegalService.list(new LambdaQueryWrapper<TSBizSerIllegal>().eq(TSBizSerIllegal::getBizseq, bizSeqId));
            List<TSWrit> writList = tsWritService.list(new LambdaQueryWrapper<TSWrit>()
                    .in(TSWrit::getPripid, list.stream().map(TSBizSerIllegal::getPripid).collect(Collectors.toList()))
                    .eq(TSWrit::getWritstype, WorkNoUtil.WORKNOTYPE_21).orderByDesc(TSWrit::getLauptime));
            for (TSBizSerIllegal each : list) {
                ExamineInfoTableDto atom = new ExamineInfoTableDto();
                atom.setFirstOpinion(firstOpinion);
                atom.setLastOpinion(lastOpinion);
                atom.setExplain(each.getLostcreditexplain());
                atom.setRegNo(each.getUniscid() != null ? each.getUniscid() : each.getRegno());
                atom.setEntName(each.getEntname());
                if(CollectionUtils.isNotEmpty(writList)){
                    for (TSWrit tsWrit : writList) {
                        if(!tsWrit.getPripid().equals(each.getPripid())) continue;
                        atom.setIncWritNo(tsWrit.getWritsno());
                        break;
                    }
                }
                result.add(atom);
            }
        }else if(taskList.getBustype().equals(TaskBusinessTypeConstant.ILLEGAL_DISSENT)){
            List<TSBizSerIllegalDiss> list = bizSerIllegalDissService.list(new LambdaQueryWrapper<TSBizSerIllegalDiss>().eq(TSBizSerIllegalDiss::getBizSeq, bizSeqId));
            List<TSWrit> writList = tsWritService.list(new LambdaQueryWrapper<TSWrit>()
                    .in(TSWrit::getPripid, list.stream().map(TSBizSerIllegalDiss::getPriPID).collect(Collectors.toList()))
                    .eq(TSWrit::getWritstype, WorkNoUtil.WORKNOTYPE_21).orderByDesc(TSWrit::getLauptime));
            for (TSBizSerIllegalDiss each : list) {
                OrgUnits orgUnits = aicorgService.queryByOrgNumber(each.getAreaCode());
                ExamineInfoTableDto atom = new ExamineInfoTableDto();
                atom.setFirstOpinion(firstOpinion);
                atom.setLastOpinion(lastOpinion);
                atom.setExplain(each.getDissentExplain());
                atom.setRegNo(each.getRegNO());
                atom.setEntName(each.getEntName());
                atom.setDecOrgName(orgUnits != null ? orgUnits.getOrgUnitName() : "广州市市场监督管理局");
                if(CollectionUtils.isNotEmpty(writList)){
                    for (TSWrit tsWrit : writList) {
                        if(!tsWrit.getPripid().equals(each.getPriPID())) continue;
                        atom.setIncWritNo(tsWrit.getWritsno());
                        break;
                    }
                }
                result.add(atom);
            }
        }else if(taskList.getBustype().equals(TaskBusinessTypeConstant.ILLEGAL_REMOVE)){
            List<TSBizSerIllegalRem> list = bizSerIllegalRemService.list(new LambdaQueryWrapper<TSBizSerIllegalRem>().eq(TSBizSerIllegalRem::getBizSeq, bizSeqId));
            List<TSWrit> writList = tsWritService.list(new LambdaQueryWrapper<TSWrit>()
                    .in(TSWrit::getPripid, list.stream().map(TSBizSerIllegalRem::getPriPID).collect(Collectors.toList()))
                    .eq(TSWrit::getWritstype, WorkNoUtil.WORKNOTYPE_21).orderByDesc(TSWrit::getLauptime));
            for (TSBizSerIllegalRem each : list) {
                ExamineInfoTableDto atom = new ExamineInfoTableDto();
                atom.setFirstOpinion(firstOpinion);
                atom.setLastOpinion(lastOpinion);
                atom.setExplain(each.getLostCreditExplainrem());
                atom.setRegNo(each.getRegNO());
                atom.setEntName(each.getEntName());
                if(CollectionUtils.isNotEmpty(writList)){
                    for (TSWrit tsWrit : writList) {
                        if(!tsWrit.getPripid().equals(each.getPriPID())) continue;
                        atom.setIncWritNo(tsWrit.getWritsno());
                        break;
                    }
                }
                result.add(atom);
            }
        }
        return RestResult.ok(result);
    }

    /**
     * 获取移出严重违法失信企业名单申请表信息
     * @param bizSeqId 移出业务的业务号
     * @return 获取结果
     * @author lroyia
     * @since 2021年3月18日 10:06:43
     */
    @ApiOperation("获取移出严重违法失信企业名单申请表信息")
    @GetMapping("illegal/getRemoveApplyMsg")
    public RestResult<?> getIllegalRemoveApplyMsg(@ApiParam("业务号") String bizSeqId){
        AssertUtils.isNotBlank(bizSeqId);
        // 查询列出信息
        List<TSBizSerIllegalRem> removeRecords = bizSerIllegalRemService.list(new LambdaQueryWrapper<TSBizSerIllegalRem>().eq(TSBizSerIllegalRem::getBizSeq, bizSeqId));
        if(CollectionUtils.isEmpty(removeRecords)) return OK;

        // 取出pripid，查询对应的主体详情，补充主体信息
        List<String> pripidList = removeRecords.stream().map(TSBizSerIllegalRem::getPriPID).collect(Collectors.toList());
        List<EBaseinfo> eBaseinfoList = eBaseinfoService.list(new LambdaQueryWrapper<EBaseinfo>().in(EBaseinfo::getPripid, pripidList));

        // 封装结果
        Map<String, TRBaseCode> reasonMap = baseCodeService.getBaseCodeMapFormCache("CD73");
        List<RemApplyMsgDto> result = new ArrayList<>();
        for (TSBizSerIllegalRem each : removeRecords) {
            RemApplyMsgDto atom = new RemApplyMsgDto();
            result.add(atom);
            atom.setEntname(each.getEntName());
            atom.setPirpid(each.getPriPID());
            atom.setRegNo(each.getRegNO());
            atom.setAbnTimeStr(each.getAbnTime().format(DateTimeFormatter.ofPattern(DateUtils.DATE_DEFAULT_FORMAT)));
            TRBaseCode reasonCode = reasonMap.get(each.getSerIllRea());
            if(reasonCode != null){
                atom.setSerillreaStr(reasonCode.getName());
            }
            for (EBaseinfo eBaseinfo : eBaseinfoList) {
                if(!eBaseinfo.getPripid().equals(each.getPriPID())) continue;
                atom.setAddress(eBaseinfo.getAddress());
                atom.setPostCode(eBaseinfo.getPostalcode());
                atom.setContacts(eBaseinfo.getName());
                atom.setLeRepName(eBaseinfo.getName());
                break;
            }
        }

        return RestResult.ok(result);
    }

    /**
     * 获取移出受理回执文书的信息
     * @param bizSeqId 业务号
     * @return 获取结果
     * @author lroyia
     * @since 2021年3月18日 15:30:07
     */
    @ApiOperation("获取移出受理回执文书的信息")
    @GetMapping("illegal/getRemAcceptReceiptWritMsg")
    public RestResult<?> getIllegalRemAcceptReceiptWritMsg(@ApiParam("业务号") String bizSeqId){
        AssertUtils.isNotBlank(bizSeqId);
        TSTaskList taskList = taskListService.getOne(new LambdaQueryWrapper<TSTaskList>().eq(TSTaskList::getBizseqid, bizSeqId));
        if(taskList == null) return RestResult.error(ResultCode.DATA_NONE);

        // 获取受理人信息
        List<TSOpinion> opinionList = opinionService.list(new LambdaQueryWrapper<TSOpinion>().eq(TSOpinion::getWorkflowid, taskList.getWorkflowid()).orderByAsc(TSOpinion::getOpiniontype).orderByDesc(TSOpinion::getLauptime));
        String accepterName = null;
        String acceptDateStr = null;
        for (TSOpinion each : opinionList) {
            if(each.getOpiniontype().equals(Constant.TRUE_1_STR)){
                accepterName = each.getHandler();
                acceptDateStr = each.getHandledate().format(DateTimeFormatter.ofPattern(DateUtils.DATE_DEFAULT_FORMAT));
                break;
            }
        }

        // 封装结果
        List<TSBizSerIllegalRem> remList = bizSerIllegalRemService.list(new LambdaQueryWrapper<TSBizSerIllegalRem>().eq(TSBizSerIllegalRem::getBizSeq, bizSeqId));
        List<TSWrit> writList = tsWritService.list(new LambdaQueryWrapper<TSWrit>().eq(TSWrit::getBizseq, bizSeqId).eq(TSWrit::getWritstype, WorkNoUtil.WORKNOTYPE_26));
        List<RemAcceptReceiptWritDto> result = new ArrayList<>();
        for (TSBizSerIllegalRem each : remList) {
            RemAcceptReceiptWritDto atom = new RemAcceptReceiptWritDto();
            result.add(atom);
            atom.setAccepter(accepterName);
            atom.setAcceptDateStr(acceptDateStr);
            atom.setEntname(each.getEntName());
            atom.setPirpid(each.getPriPID());
            atom.setRegNo(each.getRegNO());
            for (TSWrit tsWrit : writList) {
                if(!tsWrit.getPripid().equals(each.getPriPID())) continue;
                atom.setWritNo(tsWrit.getWritsno());
                break;
            }
        }
        return RestResult.ok(result);
    }

    /**
     * 获取列入经营异常名录异议表信息
     * @param bizseq 业务号
     * @param type 表格类型
     * @return
     */
    @ApiOperation("获取列入经营异常名录异议表信息")
    @GetMapping("abnormal/getAbnDissentApplyTabInfo")
    public RestResult<?> getAbnDissentApplyTabInfo(@ApiParam("业务号") String bizseq,@ApiParam("表格类型") String type){
        AssertUtils.isNotBlank(bizseq,type);
        //封装主体信息
        TSBizDissent bizDissent = tsBizDissentService.getOne(new LambdaQueryWrapper<TSBizDissent>().eq(TSBizDissent::getBizseq, bizseq));
        if(bizDissent == null){
            return RestResult.error(ResultCode.DATA_NONE);
        }
        DissentApplyInfoTableDto dissentApplyInfoTableDto = new DissentApplyInfoTableDto();
        BeanUtils.copyProperties(bizDissent, dissentApplyInfoTableDto);
        //获取封装文书号
        List<TSWrit> writList = tsWritService.list(new LambdaQueryWrapper<TSWrit>().eq(TSWrit::getPripid, bizDissent.getPripid()).eq(TSWrit::getWritstype, WorkNoUtil.WORKNOTYPE_11).orderByDesc(TSWrit::getLauptime));
        if (writList.size() > 0) {
            dissentApplyInfoTableDto.setWritsno(writList.get(0).getWritsno());
        }
        //封装意见
        TSTaskList taskList = taskListService.getOne(new LambdaQueryWrapper<TSTaskList>().eq(TSTaskList::getBizseqid, bizseq));
        List<TSOpinion> opinionList = opinionService.list(new LambdaQueryWrapper<TSOpinion>().eq(TSOpinion::getWorkflowid, taskList.getWorkflowid()).orderByDesc(TSOpinion::getLauptime, TSOpinion::getOpiniontype));
        //申请表
        if(type.equals("apply")) {
            //申请受理意见
            if (CollectionUtils.isNotEmpty(opinionList)) {
                boolean flag0 = false;
                boolean flag1 = false;
                for (TSOpinion item : opinionList) {
                    if ("1".equals(item.getOpiniontype()) && !flag1) {
                        dissentApplyInfoTableDto.setLastOpinion(item.getOpinioncontent());
                        dissentApplyInfoTableDto.setLastHandler(item.getHandler());
                        dissentApplyInfoTableDto.setLastHandleDate(item.getHandledate().toLocalDate());
                        flag1 = true;
                    } else if ("0".equals(item.getOpiniontype()) && !flag0) {
                        dissentApplyInfoTableDto.setFirstOpinion(item.getOpinioncontent());
                        dissentApplyInfoTableDto.setFirstHandler(item.getHandler());
                        dissentApplyInfoTableDto.setFirstHandleDate(item.getHandledate().toLocalDate());
                        flag0 = true;
                    }
                }

            }

        //审批表
        }else if(type.equals("approval")){
            //审批意见
            if (CollectionUtils.isNotEmpty(opinionList)) {
                boolean flag2 = false;
                boolean flag3 = false;
                boolean flag4 = false;
                for (TSOpinion item : opinionList) {
                    if ("5".equals(item.getOpiniontype()) && !flag3) {
                        dissentApplyInfoTableDto.setLastOpinion(item.getOpinioncontent());
                        dissentApplyInfoTableDto.setLastHandler(item.getHandler());
                        dissentApplyInfoTableDto.setLastHandleDate(item.getHandledate().toLocalDate());
                        flag3 = true;
                    } else if ("3".equals(item.getOpiniontype()) && !flag2) {
                        dissentApplyInfoTableDto.setFirstOpinion(item.getOpinioncontent());
                        dissentApplyInfoTableDto.setFirstHandler(item.getHandler());
                        dissentApplyInfoTableDto.setFirstHandleDate(item.getHandledate().toLocalDate());
                        flag2 = true;
                    } else if ("4".equals(item.getOpiniontype()) && !flag4) {
                        dissentApplyInfoTableDto.setReviewOpinion(item.getOpinioncontent());
                        dissentApplyInfoTableDto.setReviewHandler(item.getHandler());
                        dissentApplyInfoTableDto.setReviewHandleDate(item.getHandledate().toLocalDate());
                        flag4 = true;
                    }
                }

            }
        }
        return RestResult.ok(dissentApplyInfoTableDto);
    }

    /**
     * 主体文书查询
     * @param pageRequestDto 主体文书封装Dto
     * @return
     */
    @PostMapping("getEntWritsList")
    public RestResult<?> getEntWritsList(@RequestBody PageRequestDto pageRequestDto){
        EntWritsDto entWritsDto = new EntWritsDto();
        Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
        String searchCode = "";
        String searchEntName = "";
        String searchWritsNo = "";


        if(customParamMap != null){
            searchCode = StringUtils.tranObject(customParamMap.get("searchCode"));
            searchEntName = StringUtils.tranObject(customParamMap.get("searchEntName"));
            searchWritsNo = StringUtils.tranObject(customParamMap.get("searchWritsNo"));
        }
        if(StringUtils.isNotBlank(searchCode) || StringUtils.isNotBlank(searchEntName)) {
            EBaseinfo eBaseinfoParams = new EBaseinfo();
            if (StringUtils.isNotBlank(searchCode)) {
                if (StringUtils.isUscc(searchCode)) {
                    eBaseinfoParams.setUniscid(searchCode);
                } else {
                    eBaseinfoParams.setRegno(searchCode);
                }
            }
            if(StringUtils.isNotBlank(searchEntName)){
                eBaseinfoParams.setEntname(searchEntName);
            }
            Page page1 = eBaseinfoService.solrQueryPripidByEntName(new Page<>(1, -1, false), eBaseinfoParams);
            Page page = eBaseinfoService.solrQueryPripidByEntName(new Page<>(1, page1.getTotal(), false), eBaseinfoParams);
            List records = page.getRecords();
            if(CollectionUtils.isNotEmpty(records)){
                String[] pripidArray = new String[records.size()];
                EBaseInfoSolrBean eBaseinfo;
                for (int i = 0; i < records.size(); i++) {
                    eBaseinfo = (EBaseInfoSolrBean) records.get(i);
                    pripidArray[i] = eBaseinfo.getPripid();
                }
                entWritsDto.setPripids(pripidArray);
            }else {
                return RestResult.ok(new Page<EntWritsDto>());
            }
        }
        entWritsDto.setWritsno(searchWritsNo);

        IPage<EntWritsDto> page = tsWritService.selectEntWrits(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), entWritsDto);
        List<EntWritsDto> records = page.getRecords();
        if(CollectionUtils.isNotEmpty(records)){
            for (EntWritsDto record : records) {
                LambdaQueryWrapper<EBaseinfo> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(EBaseinfo::getPripid,record.getPripid());
                EBaseinfo baseinfo = eBaseinfoService.getOne(wrapper, false);
                record.setUniscid(baseinfo.getUniscid());
                record.setRegno(baseinfo.getRegno());
                record.setEntname(baseinfo.getEntname());
            }
        }
        return RestResult.ok(page);
    }

    /**
     * 文书预览
     * @param tempPath  文书存放路径
     * @param bizseq   业务号
     * @return
     */
    @PostMapping("word2Pdf")
    public RestResult<?> word2Pdf(String tempPath,String bizseq,String writstype){
        if(StringUtils.isNotBlank(tempPath)) {
            if (WorkNoUtil.WORKNOTYPE_11.equals(writstype)
                    || WorkNoUtil.WORKNOTYPE_15.equals(writstype)
                    || WorkNoUtil.WORKNOTYPE_52.equals(writstype)
                    || WorkNoUtil.WORKNOTYPE_53.equals(writstype)
                    || WorkNoUtil.WORKNOTYPE_54.equals(writstype)
                    || WorkNoUtil.WORKNOTYPE_55.equals(writstype)
                    || WorkNoUtil.WORKNOTYPE_56.equals(writstype)
                    || WorkNoUtil.WORKNOTYPE_57.equals(writstype)
                    || WorkNoUtil.WORKNOTYPE_58.equals(writstype)
                    || WorkNoUtil.WORKNOTYPE_59.equals(writstype)
                    || WorkNoUtil.WORKNOTYPE_60.equals(writstype)
                    || WorkNoUtil.WORKNOTYPE_61.equals(writstype)
                    || WorkNoUtil.WORKNOTYPE_62.equals(writstype)
                    || WorkNoUtil.WORKNOTYPE_63.equals(writstype)
            ) { //列异在文书表里保存的是pdf路径
                return RestResult.ok(tempPath);
            } else if (WorkNoUtil.WORKNOTYPE_32.equals(writstype) || WorkNoUtil.WORKNOTYPE_33.equals(writstype)) {
                String wordPath = tempPath;
                File file = new File(wordPath);
                if (!file.exists()) {
                    return RestResult.error(ResultCode.PARAM_IS_INVALID,"访问路径错误或文件不存在！");
                }
                String fileName = wordPath.substring(wordPath.lastIndexOf(File.separator) + 1, wordPath.lastIndexOf(Constant.DOT));
                String pdfTemppath = bizseq + File.separator + "PDF" + File.separator + fileName + ".pdf";
                String pdfPath = CommonConfig.getUploadPath() + File.separator + pdfTemppath;
                File pdfFile = new File(pdfPath);

                if (!pdfFile.exists()) {
                    pdfFile.getParentFile().mkdirs();
                    PdfUtil.convertDocx2Pdf(wordPath, pdfPath);
                }
                return RestResult.ok(pdfTemppath);
            } else {
                return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR,"不支持该文书类型！");
            }
        }
        return RestResult.error(ResultCode.PARAM_IS_BLANK);
    }

    /**
     * 附件下载 返回文件流
     * @throws IOException
     */
    @PostMapping("downloadTSWrits")
    public void downloadTSWrits(String writsid, HttpServletResponse response) throws IOException {
        TSWrit tsWrit = tsWritService.getById(writsid);
        response.setHeader("Content-Disposition", "attachment;  filename=\"" + new String(tsWrit.getWritsname().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1) + "\"");
        fileStorageService.writeToStream(tsWrit.getPath(), response.getOutputStream());
    }

}
