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

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
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.EBaseinfo;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSAbnList;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSWrit;
import com.chinaweal.aiccs.aiccs.abnormal.service.EBaseinfoService;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSAbnListService;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSWritService;
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.market.service.AreaSliceService;
import com.chinaweal.aiccs.aiccs.query.entity.TSEntBaseQuery;
import com.chinaweal.aiccs.aiccs.query.service.TSEntBaseQueryService;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSBizSerIllegal;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSBizSerIllegalReas;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSForIllOperatingList;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSSerIllegalList;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.dto.IllegalListByPripIdParam;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.dto.TSBizSerIllegalVO;
import com.chinaweal.aiccs.aiccs.seriousillegal.excelDto.IllegalExcelDto;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSBizSerIllegalService;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSForIllOperatingListService;
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.Constant;
import com.chinaweal.aiccs.common.util.*;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.youfool.framework.springboot.base.query.BaseQuery;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.function.CustomWrapperPackingFunction;
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.collections.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequestMapping("/serIllegalList")
public class SerIllegalListController extends BaseController {

    @Autowired
    private TSAbnListService tsAbnListService;
    @Autowired
    private TSBizSerIllegalService tsBizSerIllegalService;
    @Autowired
    private TSSerIllegalListService tsSerIllegalListService;
    @Autowired
    private TSWritService tsWritService;
    @Autowired
    private TSTaskListService taskListService;
    @Autowired
    private TSOpinionService opinionService;
    @Autowired
    private TSEntBaseQueryService entBaseQueryService;
    @Autowired
    private TRBaseCodeService baseCodeService;
    @Autowired
    private EBaseinfoService eBaseinfoService;
    @Autowired
    private TSForIllOperatingListService tsForIllOperatingListService;
    @Autowired
    private AreaSliceService areaSliceService;

    /**
     * 异常名录期限届满 主体查询
     */
    @RequestMapping(value = "/serIllegalListSearch.do", method = RequestMethod.POST)
    public RestResult<?> serIllegalListSearch(HttpServletRequest request, TSAbnList tsAbnListModel, int rows, int page) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        //只查 本机构做出决定的异常名录
        if (StringUtils.isNotBlank(aicUser.getRegionID())) {
            tsAbnListModel.setIntoDecorg(aicUser.getRegionID());
        }
        if (StringUtils.isNotBlank(tsAbnListModel.getRegno())) {
            // 因为TSAbnList没有uscc
            TSEntBaseQuery entInfo = entBaseQueryService.queryEntBaseInfoByRegno(tsAbnListModel.getRegno());
            tsAbnListModel.setRegno(entInfo.getRegNO());
        }

        return RestResult.ok(tsAbnListService.selectTSAbnByTimeout(rows, page, tsAbnListModel));
    }


    /**
     * 协助执行列入严重违法失信 主体查询
     */
    @RequestMapping(value = "/findSerIllegalEnt.do", method = RequestMethod.POST)
    public RestResult<?> findSerIllegalEnt(HttpServletRequest request, TSEntBaseQuery entBaseQueryModel, int rows, int page) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        if (StringUtils.isNotBlank(aicUser.getRegionID())) { //只查询本机构监管的主体
            entBaseQueryModel.setLocalAdm(aicUser.getRegionID());
        }

        return RestResult.ok(tsSerIllegalListService.serIllegalListByPage(rows, page, entBaseQueryModel));
    }

    /**
     * 存在严重违法失信行为 主体查询
     * tsSerIllegalListModel 用来接收查询条件
     */
    @RequestMapping(value = "/findLostCreditActionEnt.do", method = RequestMethod.POST)
    public RestResult<?> findLostCreditActionEnt(HttpServletRequest request, TSSerIllegalList tsSerIllegalListModel,
                                                 int rows, int page) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null || StringUtils.isBlank(aicUser.getRegionID()))
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        if (StringUtils.isNotBlank(aicUser.getRegionID())) { //只查询本机构监管的主体
            tsSerIllegalListModel.setDecorg(aicUser.getRegionID());
        }

        return RestResult.ok(tsSerIllegalListService.findLostCreditEntByPage(rows, page, tsSerIllegalListModel));
    }


    /**
     * 打印文书页面
     */
    @RequestMapping(value = "/printTSWrit.do")
    public RestResult<?> printTSWrit(String printstatus, TSBizSerIllegal tsBizSerIllegalModel, String workflowid, String type) {
        //获取当前时间
        Map<String, Object> resultMap = new HashMap<>();
        if (printstatus.equals("1")) {//打印决定书
            tsBizSerIllegalModel = tsBizSerIllegalService.getById(tsBizSerIllegalModel.getIllegallistid());

            TSWrit writQueryModel = new TSWrit();//文书号
            writQueryModel.setWritstype(WorkNoUtil.WORKNOTYPE_21);
            writQueryModel.setPripid(tsBizSerIllegalModel.getPripid());
            writQueryModel.setBizseq(tsBizSerIllegalModel.getBizseq());
            List<TSWrit> tsWritQueryModels = tsWritService.listTswrit(writQueryModel);
            if (tsWritQueryModels.size() > 0) {
                resultMap.put("wrirsno", tsWritQueryModels.get(0).getWritsno());
            }
            LocalDate now = LocalDate.now();
            resultMap.put("tsBizSerIllegalModel", tsBizSerIllegalModel);
            resultMap.put("ReconsiderationOrgInfo", tsBizSerIllegalModel.getReconsiderationOrg()); //行政复议机关
            resultMap.put("nowTime", now);
            resultMap.put("fiveLaterTime", now.plusYears(5));
//            if(StringUtils.isNotBlank(tsBizSerIllegalModel.getAbnlistid())){ //经营名录期限届满 列入决定书
//                return "/supervision/seriousIllegal/brEntSerIllegal/print/writtenDecision01";
//            }else { //存在严重违法失信行为、协助执行 列入决定书
//                return "/supervision/seriousIllegal/brEntSerIllegal/print/writtenDecision02";
//            }
            return RestResult.ok(resultMap);

        } else if (printstatus.equals("3")) {//打印审批表
            TSTaskList taskListModel = taskListService.selectByWorkflowID(workflowid);
            StringBuilder regno = new StringBuilder();
            StringBuilder ename = new StringBuilder();
            TSBizSerIllegal paramModel = new TSBizSerIllegal();
            paramModel.setBizseq(taskListModel.getBizseqid());
            List<TSBizSerIllegal> list = tsBizSerIllegalService.selectBizSerIllegalModels(paramModel);
            if (CollectionUtils.isNotEmpty(list)) {
                for (int i = 0; i < list.size(); i++) {
                    if (i > 2) {
                        ename.append("等");
                        regno.append("等");
                        break;
                    }
                    if (i > 0) {
                        ename.append(", ");
                        regno.append(", ");
                    }
                    ename.append(list.get(i).getEntname());
                    regno.append(list.get(i).getUniscid() != null ? list.get(i).getUniscid() : list.get(i).getRegno());
                }
            }

            List<TSOpinion> opinionList = opinionService.selectByAuditingID(workflowid);
            resultMap.put("opinionList", opinionList);
            resultMap.put("regno", regno);
            resultMap.put("ename", ename);
            resultMap.put("list", list);
            resultMap.put("decorgString", list.get(0).getDecorg());
            resultMap.put("lostCreditExplain", list.get(0).getLostcreditexplain());
            return RestResult.ok(resultMap);
        }
        return RestResult.ok(resultMap);
    }

    /**
     * 严重违法失信企业记录常规分页查询
     *
     * @param pageRequestDto 分页参数
     * @return 分页结果
     * @author lroyia
     * @since 2021年3月9日 19:10:46
     */
    @PostMapping("illegalPage")
    public RestResult<IPage<TSSerIllegalList>> illegalListPage(@RequestBody PageRequestDto pageRequestDto) {
        AssertUtils.isNotNull(pageRequestDto);
        Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CD73");
        return RestResult.ok(tsSerIllegalListService.defaultPaging(pageRequestDto, w -> {
            LambdaQueryWrapper<TSSerIllegalList> wrapper = w.lambda();
            Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
            String searchUscc = StringUtils.tranObject(customParamMap.get("searchUscc"));
            String searchName = StringUtils.tranObject(customParamMap.get("searchName"));
            String abntime = StringUtils.tranObject(customParamMap.get("abntime"));
            String serillrea = StringUtils.tranObject(customParamMap.get("serillrea"));
            if (StringUtils.isNotBlank(searchUscc)) {
                //判断入参为统一码还是注册号
                if (StringUtils.isUscc(searchUscc)) {
                    wrapper.eq(TSSerIllegalList::getUniscid, searchUscc);
                } else {
                    wrapper.eq(TSSerIllegalList::getRegno, searchUscc);
                }
            }
            if (StringUtils.isNotBlank(searchName)) {
                wrapper.like(TSSerIllegalList::getEntname, searchName);
            }
            if (StringUtils.isNotBlank(abntime)) {
                wrapper.eq(TSSerIllegalList::getAbntime, abntime);
            }
            if (StringUtils.isNotBlank(serillrea)) {
                wrapper.eq(TSSerIllegalList::getSerillrea, serillrea);
            }
            // 判断是否查询现存名录
            String exists = StringUtils.tranObject(customParamMap.get("exists"));
            if (Constant.TRUE_1_STR.equals(exists)) {
                wrapper.isNotNull(TSSerIllegalList::getAbntime).isNull(TSSerIllegalList::getRemdate);
            }
        }, each -> {
            TRBaseCode baseCode = codeMap.get(each.getSerillrea());
            if (baseCode != null) {
                each.setSerillreaString(baseCode.getName());
            }
        }));
    }

    //严重违法失信 文书打印查询
    @RequestMapping(value = "/searchDocPrint.do")
    public String searchDocPrint() {
        return "/supervision/seriousIllegal/brEntSerIllegal/searchab_tstaskList";
    }

    /**
     * 查询待办列表 严重违法失信企业
     */
    @RequestMapping(value = "/searchTStaskSerIllegalPage.do", method = RequestMethod.POST)
    public RestResult<?> searchTStaskSerIllegalPage(HttpServletRequest request, TSTaskList tsTaskListModel, int rows, int page) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        String decorg = aicUser.getRegionID();//只查 本机构做出决定的记录
        return RestResult.ok(taskListService.searchTstaskByPage(new Page<>(page, rows), tsTaskListModel, "serIllegal", decorg));
    }

    /**
     * 严重违法失信企业名单 查询
     */
    @RequestMapping(value = "/selectTSSerIllegalList.do", method = RequestMethod.POST)
    public RestResult<?> selectTSSerIllegalList(HttpServletRequest request, TSSerIllegalList tsSerIllegalListModel, int rows, int page, String type) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        if (StringUtils.isNotBlank(aicUser.getRegionID())) tsSerIllegalListModel.setDecorg(aicUser.getRegionID());

        return RestResult.ok(tsSerIllegalListService.selectTSSerIllegalList(rows, page, tsSerIllegalListModel, type));
    }

    /**
     * 严重违法失信企业名单统计 查询
     */
    @RequestMapping(value = "/selectTSSerIllegalListCount.do", method = RequestMethod.POST)
    public RestResult<?> selectTSSerIllegalListCount(HttpServletRequest request, TSSerIllegalList tsSerIllegalListModel, int rows, int page, String regorgArrStr, String territorialArrStr) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        if (StringUtils.isNotBlank(aicUser.getRegionID())) tsSerIllegalListModel.setDecorg(aicUser.getRegionID());

        // 登记机关
        String[] regorgArr = null;
        if (StringUtils.isNotBlank(regorgArrStr)) {
            regorgArr = regorgArrStr.split(",");
        }
        // 属地管辖机关
        String[] territorialArr = null;
        if (StringUtils.isNotBlank(territorialArrStr)) {
            territorialArr = territorialArrStr.split(",");
        }
        return RestResult.ok(tsSerIllegalListService.selectTSSerIllegalListCountByPage(rows, page, tsSerIllegalListModel, regorgArr, territorialArr));
    }

    //获取所有 列入严重违法失信原因（1--11项）
    @RequestMapping(value = "/findSerIllegalReas.do", method = RequestMethod.GET)
    public RestResult<List<TSBizSerIllegalReas>> findSerIllegalReas() {
        return RestResult.ok(tsBizSerIllegalService.findSerIllegalReas());
    }

    //非异常名录 严重违法失信行为 查询（2--11项）
    @RequestMapping(value = "/getSerillreas.do", method = RequestMethod.GET)
    public RestResult<List<TSBizSerIllegalReas>> getSerillreas() {
        return RestResult.ok(tsBizSerIllegalService.getSerillreas(null));
    }


    @RequestMapping("/exportGetUp.do")
    public ResponseEntity<byte[]> exportGetUp(HttpServletRequest request, String regno, String entname, String abntime, String endabntime,
                                              String serillrea, String regorgArrStr, String territorialArrStr, @RequestHeader("User-Agent") String userAgent) throws Exception {

        AICUser userInfo = getLoginUser(request);

        int tempStart = StringUtils.isBlank(request.getParameter("formMap[start]")) ? 0 : Integer.valueOf(request.getParameter("formMap[start]"));
        int tempEnd = StringUtils.isBlank(request.getParameter("formMap[end]")) ? 0 : Integer.valueOf(request.getParameter("formMap[end]"));
        int total = StringUtils.isBlank(request.getParameter("formMap[total]")) ? 0 : Integer.valueOf(request.getParameter("formMap[total]"));

//        Date estDateNode=null;
//        if(StringUtils.isNotBlank(reportyear)){
//            Calendar c= Calendar.getInstance();
//            c.set(Calendar.YEAR,Integer.valueOf(reportyear)+1);
//            c.set(Calendar.MONTH,00);
//            c.set(Calendar.DAY_OF_MONTH,01);
//            estDateNode=c.getTime();
//        }

        /**导出项*/
        String property = request.getParameter("formMap[propertys]");
        String[] propertys = property.split(",");
        /**导出数据*/
        List<TSSerIllegalList> result;
        // 获取字段描述信息
        Map<String, String> fieldmap = ExportUtils.getSerIllegalListExportFieldmap();

        TSSerIllegalList illegalListModel = new TSSerIllegalList();
        if (StringUtils.isNotBlank(regno)) {
            illegalListModel.setRegno(regno);
        }
        if (StringUtils.isNotBlank(entname)) {
            illegalListModel.setEntname(entname);
        }
        if (StringUtils.isNotBlank(abntime)) {
            illegalListModel.setAbntime(LocalDate.parse(abntime, DateTimeFormatter.ofPattern(DateUtils.DATE_DEFAULT_FORMAT)));
        }
        if (StringUtils.isNotBlank(endabntime)) {
            illegalListModel.setEndAbnTime(LocalDate.parse(endabntime, DateTimeFormatter.ofPattern(DateUtils.DATE_DEFAULT_FORMAT)));
        }
        if (StringUtils.isNotBlank(serillrea)) {
            illegalListModel.setSerillrea(serillrea);
        }

        // 登记机关
        String[] regorgArr = null;
        if (StringUtils.isNotBlank(regorgArrStr)) {
            regorgArr = regorgArrStr.split(",");
        }
        // 属地管辖机关
        String[] territorialArr = null;
        if (StringUtils.isNotBlank(territorialArrStr)) {
            territorialArr = territorialArrStr.split(",");
        }

        IPage<TSSerIllegalList> tempLists = tsSerIllegalListService.selectTSSerIllegalListCountByPage(total, 1, illegalListModel, regorgArr, territorialArr);


        if (tempLists != null) {
            result = tempLists.getRecords();
        } else {
            return null;
        }
        result = result.subList(tempStart - 1, tempEnd);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            /**导出数据到Excel*/
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet excel = workbook.createSheet("严重违法失信企业名单统计信息导出");
            /**表头行*/
            HSSFRow headrow = excel.createRow(0);
            /**设置表头*/
            for (int i = 0; i < propertys.length; i++) {
                String pro = propertys[i];
                HSSFCell cell = headrow.createCell(i);
                cell.setCellValue(fieldmap.get(pro));
            }
            /**填值*/
            for (int i = 0; i < result.size(); i++) {
                TSSerIllegalList model = result.get(i);
                HSSFRow row = excel.createRow(i + 1);
                for (int j = 0; j < propertys.length; j++) {
                    HSSFCell cell = row.createCell(j);
                    String pro = propertys[j];
                    // 数据库存的编码转换页面上显示的内容
                    if ("serillrea".equals(pro)) {
                        pro += "String";
                    }
                    if ("remexcpres".equals(pro)) {
                        pro += "_String";
                    }
                    String methodString = "get" + pro.replaceFirst(pro.substring(0, 1), pro.substring(0, 1).toUpperCase());
                    Method method = model.getClass().getMethod(methodString);
                    Object value = method.invoke(model);
                    if (value instanceof Date) {
                        String datetString = DateUtils.getDateFormat((Date) value, DateUtils.DATE_DEFAULT_FORMAT);
                        cell.setCellValue(datetString);
                    } else {
                        cell.setCellValue(value != null ? value.toString() : "");
                    }
                }
            }
            String fileName = ExportUtils.createFileNmae("xls");
            workbook.write(bos);
            byte[] bytes = bos.toByteArray();
            fileName = WebUtil.encodeDownloadFileName(WebUtil.isMSIE(userAgent), fileName);
            HttpHeaders headers = new HttpHeaders();
            request.getSession().setAttribute("isFinished", "true");
            headers.setContentDispositionFormData("attachment", fileName);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
        } finally {
            if (bos != null) {
                bos.close();
            }
        }
        /*int size=50000;
        int page=(tempEnd-tempStart)/size+1;
        if(property!=null&&tempEnd!=0&&total!=0){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            ZipOutputStream zipOutputStream=null;
            response.setContentType("application/octet-stream");
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(sdf.format(new Date()) +".zip", "UTF-8"));
            zipOutputStream=new ZipOutputStream(response.getOutputStream());
            for(int i=1;i<=page;i++){
                int start=(i-1)*size+tempStart;
                int end=start+size>tempEnd?(tempEnd+1):start+size;
                List<String> headInfo= Arrays.asList(property.split(","));
                List<Map<String,Object>> list=null;
                if(status.endsWith("0")){
                    list=entBaseInfoService.notPresentReportYear(status,regorg,reportyear,start,end,estDateNode);
                }else{
                    list=entBaseInfoService.presentReportYear(status,regorg,reportyear,start,end,estDateNode);
                }
                //list = list.subList(start-1,end);
                HSSFWorkbook workbook=ExcelUtil.createExcel("65",headInfo,list);
                zipOutputStream.putNextEntry(new ZipEntry(start+"~"+end+".xls"));
                workbook.write(zipOutputStream);
                zipOutputStream.flush();
            }
            zipOutputStream.close();
            // return "success";
            // return "redirect:/entPriseType/selectannualreport_open.do?regorg="+regorg+"&reportyear="+reportyear+"&start="+start;

        }else{
            // return "redirect:/entPriseType/selectannualreport_open.do?regorg="+regorg+"&reportyear="+reportyear+"&start="+start;
        }*/
    }

    /**
     * 获取通过业务号id获取所有异常名录
     *
     * @param bizSeqId 业务号
     * @return 严重违法名录
     * @author lroyia
     * @since 2021年3月8日 17:50:25
     */
    @RequestMapping("list_by_bizseqid")
    public RestResult<List<TSBizSerIllegalVO>> getBizSpeListByBizSeqId(String bizSeqId) throws Exception {
        AssertUtils.isNotBlank(bizSeqId);
        List<TSBizSerIllegal> list = tsBizSerIllegalService.list(new LambdaQueryWrapper<TSBizSerIllegal>().eq(TSBizSerIllegal::getBizseq, bizSeqId));
        List<TSBizSerIllegalVO> listVOList = new ArrayList<>();
        list.forEach(each -> {
            TSBizSerIllegalVO listVO = new TSBizSerIllegalVO();
            BeanUtils.copyProperties(each, listVO);
            listVOList.add(listVO);
        });

        Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CD73");

        listVOList.forEach(each -> {
            EBaseinfo companyDetails = eBaseinfoService.getOne(new LambdaQueryWrapper<EBaseinfo>().eq(EBaseinfo::getPripid, each.getPripid()));
            TRBaseCode trBaseCode = codeMap.get(each.getSerillrea());
            if (trBaseCode != null) {
                each.setSerillreaString(trBaseCode.getName());
            }
            each.setAddress(companyDetails.getDom());
            each.setEstDate(companyDetails.getEstdate());
            each.setLerepname(companyDetails.getName());
            each.setEntTypeName(companyDetails.getEnttypeCn());

        });
        return RestResult.ok(listVOList);
    }

    @RequestMapping("list_by_bizseqidAndEntName")
    public RestResult<List<TSBizSerIllegalVO>> getBizSpeListByBizSeqIdAndEntName(String bizSeqId, String entName) throws Exception {
        AssertUtils.isNotBlank(bizSeqId);
        List<TSBizSerIllegal> list = tsBizSerIllegalService.list(new LambdaQueryWrapper<TSBizSerIllegal>().eq(TSBizSerIllegal::getBizseq, bizSeqId)
                .like(StringUtils.isNotBlank(entName), TSBizSerIllegal::getEntname, entName));
        List<TSBizSerIllegalVO> listVOList = new ArrayList<>();
        list.forEach(each -> {
            TSBizSerIllegalVO listVO = new TSBizSerIllegalVO();
            BeanUtils.copyProperties(each, listVO);
            listVOList.add(listVO);
        });

        Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CD73");

        listVOList.forEach(each -> {
            EBaseinfo companyDetails = eBaseinfoService.getOne(new LambdaQueryWrapper<EBaseinfo>().eq(EBaseinfo::getPripid, each.getPripid()));
            TRBaseCode trBaseCode = codeMap.get(each.getSerillrea());
            if (trBaseCode != null) {
                each.setSerillreaString(trBaseCode.getName());
            }
            each.setAddress(companyDetails.getDom());
            each.setEstDate(companyDetails.getEstdate());
            each.setLerepname(companyDetails.getName());
            each.setEntTypeName(companyDetails.getEnttypeCn());

        });
        return RestResult.ok(listVOList);
    }

    /**
     * 移除严重违法名录企业信息
     *
     * @param illegalListIds 移除信息id（多个用半角逗号隔开）
     * @return 操作结果
     * @author lroyia
     * @since 2021年3月8日 18:50:43
     */
    @ApiOperation("移除严重违法名录企业信息")
    @PostMapping("remove_by_illegallistid")
    public RestResult<?> removeByIllegalListId(@ApiParam("移除信息id（多个用半角逗号隔开）") String illegalListIds, String type) {
        AssertUtils.isNotBlank(illegalListIds);
        // 拟列严恢复线索状态
        if ("nly".equals(type)) {
            List<String> illIdList = Arrays.asList(illegalListIds.split(Constant.SEMICOLON));
            List<TSBizSerIllegal> tsBizSerIllegals = tsBizSerIllegalService.list(
                    new LambdaQueryWrapper<TSBizSerIllegal>().in(TSBizSerIllegal::getIllegallistid, illIdList));
            List<String> abnids = new ArrayList<>();
            for (TSBizSerIllegal tsBizSerIllegal : tsBizSerIllegals) {
                abnids.add(tsBizSerIllegal.getAbnlistid());
            }
            List<TSForIllOperatingList> tsForIllOperatingLists = tsForIllOperatingListService.list(
                    new LambdaQueryWrapper<TSForIllOperatingList>().in(TSForIllOperatingList::getAbnlistid, abnids)
            );
            for (TSForIllOperatingList tsForIllOperatingList : tsForIllOperatingLists) {
                tsForIllOperatingList.setOperationStatus("0"); // 录入状态
                tsForIllOperatingListService.updateById(tsForIllOperatingList);
            }
        }
        return RestResult.ok(tsBizSerIllegalService.removeByIds(Arrays.asList(illegalListIds.split(Constant.SEMICOLON))));
    }

    /**
     * 获取统一严重违法失信企业待办列表分页
     *
     * @param request        请求
     * @param pageRequestDto 分页参数与
     * @return 获取结果
     * @author lroyia
     * @since 2021年4月19日 17:23:44
     */
    @ApiOperation("获取统一严重违法失信企业待办列表分页")
    @PostMapping("getUniIllegalTaskListPage")
    public RestResult<?> getUniIllegalTaskListPage(HttpServletRequest request, @RequestBody PageRequestDto pageRequestDto) {
        AssertUtils.isNotNull(pageRequestDto);
        pageRequestDto.checkDefault(1, 10, null);
        Map<String, Object> paramMap = pageRequestDto.getParamMap();
        if (paramMap == null) {
            paramMap = new HashMap<>();
        }
        AICUser curUser = getLoginUser(request);
        paramMap.put("curUserId", curUser.getPrimaryKey());
        return RestResult.ok(tsSerIllegalListService.getUniIllegalTaskListPage(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), paramMap));
    }

    /**
     * 获取严重违法失信企业个人待办总量
     *
     * @param request 请求
     * @return 获取结果
     * @author lroyia
     * @since 2021年4月19日 17:37:37
     */
    @ApiOperation("查询严重违法失信企业个人待办总量")
    @GetMapping("getIllegalTaskListCount")
    public RestResult<?> getIllegalTaskListCount(HttpServletRequest request) {
        AICUser curUser = getLoginUser(request);
        Map<String, Object> params = new HashMap<>();
        params.put("curUserId", curUser.getPrimaryKey());
        return RestResult.ok(tsSerIllegalListService.getIllegalTaskListCount(params));
    }

    /**
     * 通过主体pripid获取主体相关严重违法失信企业名录信息
     *
     * @param pripid 主体pripid
     * @return 查询结果
     * @author lroyia
     * @since 2021年4月21日 15:25:20
     */
    @GetMapping("listIllegalRecord")
    @ApiOperation("通过主体pripid获取")
    public RestResult<?> listIllegalRecord(@ApiParam("主体pripid") String pripid) {
        AssertUtils.isNotBlank(pripid);
        List<TSSerIllegalList> list = tsSerIllegalListService.list(new LambdaQueryWrapper<TSSerIllegalList>().eq(TSSerIllegalList::getPripid, pripid).orderByDesc(TSSerIllegalList::getAbntime));
        if (CollectionUtils.isNotEmpty(list)) {
            Map<String, TRBaseCode> moveInRea = baseCodeService.getBaseCodeMapFormCache("CD73");
            Map<String, TRBaseCode> moveOutRea = baseCodeService.getBaseCodeMapFormCache("CD74");

            for (TSSerIllegalList each : list) {
                if (StringUtils.isNotBlank(each.getSerillrea())) {
                    TRBaseCode code = moveInRea.get(each.getSerillrea());
                    if (code != null) {
                        each.setSerillreaString(code.getName());
                    }
                }
                if (StringUtils.isNotBlank(each.getRemexcpres())) {
                    TRBaseCode code = moveOutRea.get(each.getRemexcpres());
                    if (code != null) {
                        each.setRemexcpresString(code.getName());
                    }
                }
            }
        }
        return RestResult.ok(list);
    }

    @RequestMapping("querySerllegaHistoryInfo")
    public RestResult<?> querySerllegaHistoryInfo(String sapprovecode) {
        return tsBizSerIllegalService.querySerllegaHistoryInfo(sapprovecode);
    }

    @RequestMapping("querySerllegaHistoryEnt")
    public RestResult<?> querySerllegaHistoryEnt(@RequestBody PageRequestDto pageRequestDto) {
        return tsBizSerIllegalService.querySerllegaHistoryEnt(pageRequestDto);
    }

    @ApiOperation(value = "严重违法失信名录查询功能接口")
    @PostMapping("/illegalSearch")
    public RestResult<IPage<TSSerIllegalList>> listEntInfo(@RequestBody PageRequestDto pageRequestDto) {

        IPage<TSSerIllegalList> data = tsSerIllegalListService.defaultPaging(pageRequestDto, queryWrapper -> {

            Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
            Map<String, Object> paramMap = pageRequestDto.getParamMap();

            queryWrapper.clear();
            //统一码或者是注册号
            if (paramMap.containsKey("uniscid")) {
                String uniscid = paramMap.get("uniscid").toString();
                if (StringUtils.isUscc(uniscid)) {
                    queryWrapper.lambda().eq(TSSerIllegalList::getUniscid, uniscid);

                } else {
                    queryWrapper.lambda().eq(TSSerIllegalList::getRegno, uniscid);

                }
            }

            //企业名称
            if (paramMap.containsKey("entname")) {
                String entname = paramMap.get("entname").toString();
                queryWrapper.lambda().eq(TSSerIllegalList::getEntname, entname);
            }

            //列入原因
            if (paramMap.containsKey("serillrea")) {
                String serillrea = paramMap.get("serillrea").toString();
                queryWrapper.lambda().eq(TSSerIllegalList::getSerillrea, serillrea);
            }


            // 列入时间
            if (customParamMap.containsKey("abntime")) {
                ArrayList abnTimeList = (ArrayList) customParamMap.get("abntime");
                if (abnTimeList != null && !abnTimeList.isEmpty()) {
                    queryWrapper.lambda().between(TSSerIllegalList::getAbntime, abnTimeList.get(0), abnTimeList.get(1));
                }
            }

            // 移出时间
            if (customParamMap.containsKey("remdate")) {
                ArrayList remDateList = (ArrayList) customParamMap.get("remdate");
                if (remDateList != null && !remDateList.isEmpty()) {
                    queryWrapper.lambda().between(TSSerIllegalList::getRemdate, remDateList.get(0), remDateList.get(1));
                }
            }

            // 管理片区
            if (customParamMap.containsKey("sliceId")) {
                ArrayList sliceIdList = (ArrayList) customParamMap.get("sliceId");
                if (!sliceIdList.isEmpty()) {
                    // 获取sliceIdList最后一位
                    String sliceId = sliceIdList.get(sliceIdList.size() - 1).toString();
                    List<String> idsByParentId = areaSliceService.getIdsByParentId(sliceId);     //获取所有子片区id
                    idsByParentId.add(sliceId);     //加上父id
                    String values = "";     //拼接片区id
                    for (int i = 0; i < idsByParentId.size(); i++) {
                        if (i == 0) values += "(";
                        values += "'" + idsByParentId.get(i) + "'";
                        if (i != idsByParentId.size() - 1) values += ",";
                        if (i == idsByParentId.size() - 1) values += ")";
                    }
                    queryWrapper.lambda().exists(String.format("select 1 from e_baseinfo e where tsserillegallist.pripid = e.pripid and e.sareacode_temp in %s", values));
                }
            }
            // 主体类型
            if (customParamMap.containsKey("entType")) {
                String entType = customParamMap.get("entType").toString();
                if (StringUtils.isNotBlank(entType)) {
                    if (entType.equals("0"))     //企业
                        queryWrapper.lambda().exists("select 1 from e_baseinfo e where tsserillegallist.pripid = e.pripid and e.enttype not in ('8000','8100','8200','8300','9000','9100','9200','9910','99100','99101','99102','99103','9999')");
                    else if (entType.equals("1"))    //个体户
                        queryWrapper.lambda().exists("select 1 from e_baseinfo e where tsserillegallist.pripid = e.pripid and e.enttype in ('9910','99100','99101','99102','99103','9999')");
                    else if (entType.equals("2"))    //农合
                        queryWrapper.lambda().exists("select 1 from e_baseinfo e where tsserillegallist.pripid = e.pripid and e.enttype in ('9100','9200')");
                }
            }

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


    /**
     * 综合查询 - 严重违法失信名录导出
     *
     * @param pageRequestDto
     * @param response
     * @return
     */
    @PostMapping("/exportIllegalSearch")
    public void exportIllegalSearch(@RequestBody PageRequestDto pageRequestDto, HttpServletResponse response) throws IOException {
        AssertUtils.isNotNull(pageRequestDto);

        //  pageRequestDto.setPageSize(5000) defaultPaging方法无法查询最大5000条数据（限制了只有500条），所以这里使用自定义的方法
        CustomWrapperPackingFunction<TSSerIllegalList> customWrapperPackingFunction = queryWrapper -> {
            queryWrapper.select("(select sareaname_temp from e_baseinfo e where e.pripid = tsserillegallist.pripid) as slice, tsserillegallist.*");
            Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();

            // 列入时间
            if (customParamMap.containsKey("abntime")) {
                ArrayList abnTimeList = (ArrayList) customParamMap.get("abntime");
                if (abnTimeList != null && !abnTimeList.isEmpty()) {
                    queryWrapper.lambda().select().between(TSSerIllegalList::getAbntime, abnTimeList.get(0), abnTimeList.get(1));
                }
            }

            // 移出时间
            if (customParamMap.containsKey("remdate")) {
                ArrayList remDateList = (ArrayList) customParamMap.get("remdate");
                if (remDateList != null && !remDateList.isEmpty()) {
                    queryWrapper.lambda().between(TSSerIllegalList::getRemdate, remDateList.get(0), remDateList.get(1));
                }
            }

            // 管理片区
            if (customParamMap.containsKey("sliceId")) {
                ArrayList sliceIdList = (ArrayList) customParamMap.get("sliceId");
                if (!sliceIdList.isEmpty()) {
                    // 获取sliceIdList最后一位
                    String sliceId = sliceIdList.get(sliceIdList.size() - 1).toString();
                    List<String> idsByParentId = areaSliceService.getIdsByParentId(sliceId);     //获取所有子片区id
                    idsByParentId.add(sliceId);     //加上父id
                    String values = "";     //拼接片区id
                    for (int i = 0; i < idsByParentId.size(); i++) {
                        if (i == 0) values += "(";
                        values += "'" + idsByParentId.get(i) + "'";
                        if (i != idsByParentId.size() - 1) values += ",";
                        if (i == idsByParentId.size() - 1) values += ")";
                    }
                    queryWrapper.lambda().exists(String.format("select 1 from e_baseinfo e where tsserillegallist.pripid = e.pripid and e.sareacode_temp in %s", values));
                }
            }
            // 主体类型
            if (customParamMap.containsKey("entType")) {
                String entType = customParamMap.get("entType").toString();
                if (StringUtils.isNotBlank(entType)) {
                    if (entType.equals("0"))         //企业
                        queryWrapper.lambda().exists("select 1 from e_baseinfo e where tsserillegallist.pripid = e.pripid and e.enttype not in ('8000','8100','8200','8300','9000','9100','9200','9910','99100','99101','99102','99103','9999')");
                    else if (entType.equals("1"))    //个体户
                        queryWrapper.lambda().exists("select 1 from e_baseinfo e where tsserillegallist.pripid = e.pripid and e.enttype in ('9910','99100','99101','99102','99103','9999')");
                    else if (entType.equals("2"))    //农合
                        queryWrapper.lambda().exists("select 1 from e_baseinfo e where tsserillegallist.pripid = e.pripid and e.enttype in ('9100','9200')");
                }
            }
            queryWrapper.lambda().last("limit 30000");
        };
        // 包装条件
        QueryWrapper<TSSerIllegalList> wrapper = new QueryWrapper<>();
        pageRequestDto.packingParam(wrapper);
        customWrapperPackingFunction.packing(wrapper);

        List<TSSerIllegalList> data = tsSerIllegalListService.list(wrapper);

        // 转换为导出对象
        List<IllegalExcelDto> rs = BeanUtil.copyToList(data, IllegalExcelDto.class);

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("严重违法失信名录名单", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        ExcelWriter excelWriter = null;
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            excelWriter = EasyExcel.write(bos, IllegalExcelDto.class).inMemory(true).build();
            excelWriter.write(rs, EasyExcel.writerSheet("严重违法失信名录信息").registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build());
            // 结束
            excelWriter.finish();
            response.getOutputStream().write(bos.toByteArray());
        } finally {
            // 结束
            if (excelWriter != null) excelWriter.finish();
        }
    }

    /**
     * 查询市场主体的列严记录分页
     *
     * @param pageQuery 分页参数
     * @return 分页结果
     */
    @ApiOperation("查询市场主体的列严记录分页")
    @PostMapping("getIllegalListByPripId")
    public RestResult<IPage<TSSerIllegalList>> getIllegalListByPripId(@RequestBody @ApiParam(value = "分页参数", required = true) BaseQuery<IllegalListByPripIdParam> pageQuery) {
        IllegalListByPripIdParam param = pageQuery.getEntity(IllegalListByPripIdParam.class);
        return RestResult.ok(tsSerIllegalListService.lambdaQuery().eq(TSSerIllegalList::getPripid, param.getPripid())
                .eq(StringUtils.isNotBlank(param.getOperationStatus()), TSSerIllegalList::getOperationStatus, param.getOperationStatus())
                .page(new Page<>(pageQuery.getCurrent(), pageQuery.getSize())));
    }
}
