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


import cn.hutool.core.util.URLUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinaweal.aiccs.aiccs.abnormal.entity.EBaseinfo;
import com.chinaweal.aiccs.aiccs.abnormal.entity.Gzaiccode;
import com.chinaweal.aiccs.aiccs.abnormal.entity.XrSuperviseDeptLog;
import com.chinaweal.aiccs.aiccs.abnormal.entity.dto.ComprehensiveStat;
import com.chinaweal.aiccs.aiccs.abnormal.entity.dto.ToIncludeAbnDto;
import com.chinaweal.aiccs.aiccs.abnormal.entity.vo.QzzxEntDto;
import com.chinaweal.aiccs.aiccs.abnormal.entity.vo.RegulatoryVO;
import com.chinaweal.aiccs.aiccs.abnormal.mapper.RegulatoryMapper;
import com.chinaweal.aiccs.aiccs.abnormal.mapper.ToincludeabnMapper;
import com.chinaweal.aiccs.aiccs.abnormal.service.*;
import com.chinaweal.aiccs.aiccs.entbase.entity.TREntPriseType;
import com.chinaweal.aiccs.aiccs.entbase.service.TREntPriseTypeService;
import com.chinaweal.aiccs.aiccs.market.service.AreaSliceService;
import com.chinaweal.aiccs.aiccs.system.entity.TRBaseCode;
import com.chinaweal.aiccs.aiccs.system.service.TRBaseCodeService;
import com.chinaweal.aiccs.aiceps.annual.entity.TREntBaseInfoSplit;
import com.chinaweal.aiccs.aiceps.annual.service.TREntBaseInfoSplitService;
import com.chinaweal.aiccs.common.base.controller.BaseController;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.enums.OpPositionEnum;
import com.chinaweal.aiccs.common.util.DateUtils;
import com.chinaweal.aiccs.common.util.MapUtils;
import com.chinaweal.aiccs.common.util.OpLogUtil;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.crgs.moveinDetails.service.EAlterRecoderService;
import com.chinaweal.aiccs.crgs.service.EContactCrgsService;
import com.chinaweal.aiccs.org.entity.OrgUnits;
import com.chinaweal.aiccs.org.service.AicorgService;
import com.chinaweal.aiccs.org.service.TUsersService;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.solr.entity.EBaseInfoSolrBean;
import com.chinaweal.solr.template.SolrSearchTemplate;
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.chinaweal.youfool.framework.sso.util.SSOUtil;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.solr.core.query.Criteria;
import org.springframework.data.solr.core.query.Query;
import org.springframework.data.solr.core.query.SimpleQuery;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

import static com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Lee
 * @since 2021-03-15
 */
@Api(tags = "企业信息相关接口")
@ApiSort(1)
@RestController
@RequestMapping("/eBaseinfo")
@Slf4j
public class EBaseinfoController extends BaseController {

    @Autowired
    private EBaseinfoService eBaseinfoService;
    @Autowired
    private TRBaseCodeService baseCodeService;
    @Resource
    private RegulatoryMapper regulatoryMapper;
    @Resource
    private ToincludeabnMapper toincludeabnMapper;
    @Resource
    private IGzaiccodeService iGzaiccodeService;
    @Resource
    private TUsersService tUsersService;
    @Resource
    private TREntPriseTypeService entPriseTypeService;
    @Resource
    private SolrSearchTemplate solrSearchTemplate;
    @Autowired
    private AicorgService aicorgService;
    @Autowired
    private TREntBaseInfoService trEntBaseInfoService;
    @Autowired
    private AreaSliceService areaSliceService;
    @Autowired
    private TREntBaseInfoSplitService trEntBaseInfoSplitService;
    @Autowired
    private EAlterRecoderService eAlterRecoderService;
    @Resource
    private EAlterRecoderTempService eAlterRecoderTempService;

    @ApiOperation(value = "获取企业主体信息 ", position = 1)
    @GetMapping("/getEntBaseInfoByCode")
    public RestResult<?> getEntBaseInfoByCode(@RequestParam @ApiParam("统一社会信用代码/注册号") String code,String entname) {

        if (StringUtils.isBlank(entname) && StringUtils.isBlank(code)) {
            throw new BusinessException(ResultCode.PARAM_IS_BLANK);
        }
        EBaseinfo eBaseinfo = null;
        LambdaQueryWrapper<EBaseinfo> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(code)) {
            wrapper.eq(EBaseinfo::getUniscid, code);
            eBaseinfo = eBaseinfoService.getOne(wrapper);
        }
        if (eBaseinfo == null && StringUtils.isNotBlank(code)) {
            LambdaQueryWrapper<EBaseinfo> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(EBaseinfo::getRegno, code);
            eBaseinfo = eBaseinfoService.getOne(wrapper1);
        }

        if (eBaseinfo == null ) {
            LambdaQueryWrapper<EBaseinfo> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.eq(EBaseinfo::getEntname, entname);
            eBaseinfo = eBaseinfoService.getOne(wrapper2);
        }
        if (eBaseinfo == null) {
            throw new BusinessException(ResultCode.DATA_NONE);
        }

        // 中文渲染
        // 经营状态
        Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CA19");
        TRBaseCode trBaseCode = codeMap.get(eBaseinfo.getRegstate());
        if (trBaseCode != null) {
            eBaseinfo.setRegstateCn(trBaseCode.getName());
        }
        // 登记机关
        if (eBaseinfo.getRegorg() != null) {
            String regorgName = baseCodeService.getRegorgName(eBaseinfo.getRegorg());
            if (regorgName != null) {
                eBaseinfo.setRegorgCn(regorgName);
            }

        }

        return RestResult.ok(eBaseinfo);
    }

    @ApiOperation(value = "获取企业主体信息根据企业名称", position = 2)
    @PostMapping("/solrListByEntName")
    public RestResult<?> solrListByEntName(@RequestBody PageRequestDto pageRequestDto) {
        AssertUtils.isNotBlank(pageRequestDto.getParamMap().get("entName").toString());

        //查solr
        SimpleQuery query = new SimpleQuery("*:*");
        query.setDefaultOperator(Query.Operator.AND);
        query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.ENT_NAME).is(pageRequestDto.getParamMap().get("entName").toString())));

        query.setOffset(Long.valueOf(pageRequestDto.getCurPage()) - 1);
        query.setRows(pageRequestDto.getPageSize());
        org.springframework.data.domain.Page<EBaseInfoSolrBean> rsPage = solrSearchTemplate.getPageByQuery(query, EBaseInfoSolrBean.class);
        Page rs = new Page<>();
        rs.setRecords(rsPage.getContent());
        rs.setTotal(rsPage.getTotalElements());
        rs.setSize(rsPage.getSize());
        rs.setPages(rsPage.getNumber() + 1);
        return RestResult.ok(rs);

    }


    /**
     * 查询经营列入经营列表
     *
     * @param pageRequestDto 分页参数
     * @return 查询结果
     * @author Lee
     * @since 2021年7月30日 03点23分
     */
    @ApiOperation("查询经营列入经营列表")
    @PostMapping("common_paging")
    public RestResult<?> toIncludeAbnPage(@RequestBody PageRequestDto pageRequestDto) {
        AICUser curUser = SSOUtil.getUser();
        if (curUser == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }
        if (MapUtils.isEmpty(pageRequestDto.getCustomParamMap())) {
            Map<String, Object> customParamMap = new HashMap<>();
            pageRequestDto.setCustomParamMap(customParamMap);
        }
        Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
        // 搜索统一码和注册号
        String searchUscc = StringUtils.tranObject(customParamMap.get("searchUscc"));
        //判断入参为统一码还是注册号
        if (StringUtils.isNotBlank(searchUscc)) {
            if (StringUtils.isUscc(searchUscc)) {
                customParamMap.put("uniscid", searchUscc);
            } else {
                customParamMap.put("regno", searchUscc);
            }
        }
        IPage<ToIncludeAbnDto> page = null;
        String searchtype = StringUtils.tranObject(customParamMap.get("searchtype"));
        String suporg = aicorgService.getRegionCodeByOrgLevel(curUser);
        customParamMap.put("suporg", suporg);
        page = toincludeabnMapper.listByEb(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), customParamMap);

        if (CollectionUtils.isNotEmpty(page.getRecords())) {
            for (ToIncludeAbnDto record : page.getRecords()) {
                //登记机关
                if (StringUtils.isEmpty(record.getRegorgCn())) {
                    record.setRegorgCn(iGzaiccodeService.getNameByCode(record.getRegorg()));
                }
                //受理机关
                if (StringUtils.isEmpty(record.getAcceptregorgCn())) {
                    record.setAcceptregorgCn(iGzaiccodeService.getNameByCode(record.getAcceptRegorg()));
                }
                //属地监管机关
                if (StringUtils.isEmpty(record.getSuporgCn())) {
                    record.setSuporgCn(iGzaiccodeService.getNameByCode(record.getSuporg()));
                }
                // 是否为动态监管批量
                if ("1".equals(record.getIsbatch())) {
                    record.setUniscid(record.getUniscid() + "等（批量）");
                    record.setEntname(record.getEntname() + "等（批量）");
                }
            }
        }

        return RestResult.ok(page);
    }


    /**
     * 获取包含主体惩戒状态的主体信息
     *
     * @param pripid  主体pripid
     * @param uniscid 主体统一码
     * @param regNo   主体注册号
     * @return 主体信息 EBaseinfo
     * @author lroyia
     * @since 2021年3月23日 14:09:08
     */
    @ApiOperation("获取包含主体惩戒状态的主体信息")
    @GetMapping("getEntBaseWithStatus")
    public RestResult<EBaseinfo> getEntBaseWithStatus(@ApiParam("主体pripid") String pripid, @ApiParam("主体统一码") String uniscid, @ApiParam("主体注册号") String regNo) {
        if (StringUtils.isBlank(pripid) && StringUtils.isBlank(uniscid) && StringUtils.isBlank(regNo))
            return RestResult.error(ResultCode.PARAM_IS_BLANK);

        MapUtils.MapBuilder<String, String> builder = MapUtils.buildMap();
        // 封装参数
        LambdaQueryWrapper<EBaseinfo> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(pripid)) {
            wrapper.eq(EBaseinfo::getPripid, pripid);
            builder.add("pripid", pripid);
        }
        if (StringUtils.isNotBlank(uniscid)) {
            wrapper.eq(EBaseinfo::getUniscid, uniscid);
            builder.add("uniscid", uniscid);
        }
        if (StringUtils.isNotBlank(regNo)) {
            wrapper.eq(EBaseinfo::getRegno, regNo);
            builder.add("regNo", regNo);
        }

        // 搜索日志
        OpLogUtil.selectLog(OpPositionEnum.CREDIT_REPAIR_SEARCH, builder.build());
        // 查询基本信息
        EBaseinfo one = eBaseinfoService.getOne(wrapper);
        if (one != null) {
            eBaseinfoService.getEBaseInfoStatus(one);
        }

        // 附加状态信息
        return RestResult.ok(one);
    }

    /**
     * 主体基本信息
     *
     * @param pripid 主体pripid
     * @return 获取结果
     * @author lroyia
     * @since 2021年4月21日 14:12:55
     */
    @ApiOperation("获取主体基本信息")
    @GetMapping("getEntBaseByPripid")
    public RestResult<?> getEntBaseByPripid(@ApiParam("主体pripid") String pripid) {
        AssertUtils.isNotBlank(pripid);
        EBaseinfo eBaseinfo = eBaseinfoService.getById(pripid);
        // 中文渲染
        if (eBaseinfo != null) {
            // 经营状态
            Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CA19");
            TRBaseCode code = codeMap.get(eBaseinfo.getRegstate());
            if (code != null) {
                eBaseinfo.setRegstateCn(code.getName());
            }
            // 登记机关
            if (eBaseinfo.getRegorg() != null) {
                String regorgName = baseCodeService.getRegorgName(eBaseinfo.getRegorg());
                if (regorgName != null) {
                    eBaseinfo.setRegorgCn(regorgName);
                }
            }
            //商事主体类型
            TREntPriseType trEntPriseType = entPriseTypeService.getEntPriseTypeFromCache(eBaseinfo.getEnttype());
            if (trEntPriseType != null) {
                eBaseinfo.setEnttypeCn(trEntPriseType.getDisplayvalue());
            }
            // 监管机关
            if (eBaseinfo.getRegulatory() != null) {
                String regulatoryName = baseCodeService.getRegorgName(eBaseinfo.getRegulatory());
                if (regulatoryName != null) {
                    eBaseinfo.setRegulatoryName(regulatoryName);
                }
            }
            if (eBaseinfo.getSuporg() != null) {
                String suporgName = baseCodeService.getSuporg(eBaseinfo.getSuporg());
                if (eBaseinfo.getRegulatoryNameTemp() != null) {
                    eBaseinfo.setSuporgCn(eBaseinfo.getRegulatoryNameTemp());
                }else {
                    if (suporgName != null) {
                        eBaseinfo.setSuporgCn(suporgName);
                    }
                }
            }


            List<TREntBaseInfoSplit> list = trEntBaseInfoSplitService.getYbList(eBaseinfo.getPripid());
            String reporyear = "";
            if (list != null && list.size() > 0) {
                for (TREntBaseInfoSplit split : list) {
                    reporyear = split.getReportyear();
                }
            }
            eBaseinfo.setReportYear(reporyear);

        }
        return RestResult.ok(eBaseinfo);
    }

    /**
     * 主体信息分页
     *
     * @param request        请求信息
     * @param pageRequestDto 分页参数
     * @return 分页结果
     * @author lroyia
     * @since 2021年4月21日 10:45:13
     */
    @ApiOperation("主体信息分页")
    @PostMapping("entInfoPage")
    public RestResult<?> complexEntInfoPage(HttpServletRequest request, @ApiParam("分页参数") @RequestBody PageRequestDto pageRequestDto) {
        AssertUtils.isNotNull(pageRequestDto);
        Map<String, Object> paramMap = pageRequestDto.getParamMap();
        if (paramMap == null) {
            paramMap = new HashMap<>();
        }
        return RestResult.ok(eBaseinfoService.getComplexEntInfoPage(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), paramMap));
    }

    @PostMapping("queryRegulatory")
    public RestResult<?> queryRegulatory(HttpServletRequest httpServletRequest) {
        AICUser aicUser = getLoginUser(httpServletRequest);
        List<Map> resultList = new ArrayList<>();

        List<RegulatoryVO> parentRs = regulatoryMapper.queryParentRegulatory();

        for (RegulatoryVO parentRegulatory : parentRs) {
            Map<String, Object> parentMap = new HashMap<>();
            parentMap.put("value", parentRegulatory.getOrgNUmber());
            parentMap.put("label", parentRegulatory.getOrgUnitName());
            String orgNumber = parentRegulatory.getOrgNUmber();
            List<Map> list = new ArrayList<>();
            if (StringUtils.isNotBlank(orgNumber) && !orgNumber.equals("150000")) {
                String param = orgNumber.substring(0, 6);
                List<RegulatoryVO> sonRs = regulatoryMapper.querySonRegulatory(param);
                for (RegulatoryVO sonRegulatory : sonRs) {
                    if (orgNumber.equals(sonRegulatory.getOrgNUmber())) {
                        continue;
                    }
                    Map<String, Object> map = new HashMap<>();
                    map.put("value", sonRegulatory.getOrgNUmber());
                    map.put("label", sonRegulatory.getOrgUnitName());
                    list.add(map);
                }
            }
            parentMap.put("children", list);
            resultList.add(parentMap);
        }
        return RestResult.ok(resultList);
    }

    @RequestMapping("comprehensiveQuery")
    public RestResult<?> comprehensiveQuery(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) throw new BusinessException("登录超时，请重新登录");
        Gzaiccode gzaiccode = tUsersService.findOrganization(aicUser.getPrimaryKey());
        Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
        String searchUscc = StringUtils.tranObject(customParamMap.get("searchUscc"));
        if (StringUtils.isNotBlank(searchUscc)) {
            if (StringUtils.isUscc(searchUscc)) {
                customParamMap.put("uniscid", searchUscc);
            } else {
                customParamMap.put("regno", searchUscc);
            }
        }
        String type = StringUtils.tranObject(customParamMap.get("type"));
        String isGRDZ = StringUtils.tranObject(customParamMap.get("isGRDZ"));
        String yearReport = StringUtils.tranObject(customParamMap.get("yearReport"));

        IPage<EBaseinfo> page = null;

        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("entNameJQ")))) {
            page = eBaseinfoService.defaultPaging(pageRequestDto, queryWrapper -> {
                queryWrapper.lambda().eq(EBaseinfo::getEntname, customParamMap.get("entNameJQ").toString());
            }, null);
        }

        if (page == null) {
            // 判断是否查信用信用修复移出时间
            Object searchRemDate = customParamMap.get("searchRemDate");

            if (StringUtils.isNotEmpty(isGRDZ)) {
                if ("GRDZ".equals(isGRDZ)) {
                    customParamMap.put("sole", Constant.REVOKE_SOLE_CODE);
                } else if ("NOGRDZ".equals(isGRDZ)) {
                    customParamMap.put("company", Constant.REVOKE_COMPANY_CODE);
                }
            }
            //片区查询属地监管机关
            if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("regulatory")))) {
                List<String> regulatory = (List<String>) customParamMap.get("regulatory");
                if (regulatory.size() > 0) {
                    String suporg = regulatory.get(regulatory.size() - 1);
                    List<String> idsByParentId = areaSliceService.getIdsByParentId(suporg);     //获取所有子片区id
                    idsByParentId.add(suporg);      //加上父id
                    customParamMap.put("regulatoryList", idsByParentId);
                }
            }
            //登记机关
            if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("regorg")))) {
                List<String> regorg = (List<String>) customParamMap.get("regorg");
                if (regorg.size() > 0) {
                    customParamMap.put("regorgFinal", regorg.get(regorg.size() - 1));   //找出机关列表中的最后一个
                }
            }
            //成立日期
            Object searchDate = customParamMap.get("establishDate");
            if (searchDate instanceof List) {
                List<String> list = (List<String>) searchDate;
                customParamMap.put("eststartDate", list.get(0));
                customParamMap.put("estendDate", list.get(1));
            }
            //核准日期
            Object apprDate = customParamMap.get("apprDate");
            if (apprDate instanceof List) {
                List<String> list = (List<String>) apprDate;
                customParamMap.put("apprDatestart", list.get(0));
                customParamMap.put("apprDateend", list.get(1));
            }
            customParamMap.put("yearReport", yearReport);
            if ("abn".equals(type)) {// 实地查无列异两年以上
                LocalDate date = LocalDate.now().minusYears(2);
                //customParamMap.put("regorg", gzaiccode.getScountrycode());
                customParamMap.put("abntime", DateUtils.localDateFormat(date, DateUtils.DATE_DEFAULT_FORMAT));

                page = eBaseinfoService.getSDCWandTwoYearsPage(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), customParamMap);
            } else if ("wnb2".equals(type)) {// 连续两年未年报
                // 获取当前日期
                LocalDate currentDate = LocalDate.now();
                int year = currentDate.getYear();
                // 构造6月30日的日期,6月30号为年报提交日期
                LocalDate endDate = LocalDate.of(year, 6, 30);
                String[] reportYear;
                if (currentDate.isBefore(endDate)) {
                    reportYear = new String[]{String.valueOf(year - 2), String.valueOf(year - 3)};
                } else {
                    reportYear = new String[]{String.valueOf(year - 1), String.valueOf(year - 2)};
                }
                List<String> listyear = Arrays.asList(reportYear);
                customParamMap.put("reportYear", listyear);
                customParamMap.put("yearSize", 2);
                IPage<EBaseInfoSolrBean> pages = eBaseinfoService.comprehensiveQuery(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), customParamMap);
                if (pages != null && CollectionUtils.isNotEmpty(pages.getRecords())) {
                    //封装主体类型名称
                    pages.getRecords().forEach(each -> {
                        TREntPriseType code = entPriseTypeService.getEntPriseTypeFromCache(each.getEnttype());
                        if (code != null) {
                            each.setEnttypeCn(code.getDisplayvalue());
                        }
                        String level = eBaseinfoService.getLevelFromCrgs(each.getPripid());
                        if (StringUtils.isNotBlank(level)) {
                            each.setLevel(level);
                        }
                    });
                }
                return RestResult.ok(pages);
//                page = eBaseinfoService.getNoReportPage(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), customParamMap);
            }
//        else if("wnb5".equals(type)) {// 连续五年未年报
//            int year = LocalDate.now().getYear();
//            String[] reportYear = new String[]{String.valueOf(year-1),String.valueOf(year-2),String.valueOf(year-3),String.valueOf(year-4),String.valueOf(year-5)};
//            customParamMap.put("reportYear",reportYear);
//            customParamMap.put("yearSize",5);
//            page = eBaseinfoService.getNoReportPage(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), customParamMap);
//        }
            else if ("wnbSdcw".equals(type)) {// 两年未年报实地查无
                // 获取当前日期
                LocalDate currentDate = LocalDate.now();
                int year = currentDate.getYear();
                // 构造6月30日的日期,6月30号为年报提交日期
                LocalDate endDate = LocalDate.of(year, 6, 30);
                String[] reportYear;
                if (currentDate.isBefore(endDate)) {
                    reportYear = new String[]{String.valueOf(year - 2), String.valueOf(year - 3)};
                } else {
                    reportYear = new String[]{String.valueOf(year - 1), String.valueOf(year - 2)};
                }
                List<String> listyear = Arrays.asList(reportYear);
                customParamMap.put("reportYear", listyear);
                //customParamMap.put("regorg", gzaiccode.getScountrycode());
                page = eBaseinfoService.getWnbAndSdcwPage(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), customParamMap);
            } else if (searchRemDate instanceof List) { // 查异常名录表
                if (!aicUser.getOrgName().equals("广州市市场监督管理局")) { // 非市局账号只查自己区移出的
                    customParamMap.put("xzqh", aicUser.getOrgName().substring(0, 2));
                }
                List<String> list = (List<String>) searchRemDate;
                customParamMap.put("remDateStart", list.get(0));
                customParamMap.put("remDateEnd", list.get(1));
                page = eBaseinfoService.pageByRemDate(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), customParamMap);
            } else if (StringUtils.isNotBlank(yearReport)) {

                page = eBaseinfoService.selectYearReport(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), customParamMap);
            } else {
                //基本主体查询，则sorl查询
                IPage<EBaseInfoSolrBean> pages = eBaseinfoService.comprehensiveQuery(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), customParamMap);
                if (pages != null && CollectionUtils.isNotEmpty(pages.getRecords())) {
                    //封装主体类型名称
                    pages.getRecords().forEach(each -> {
                        TREntPriseType code = entPriseTypeService.getEntPriseTypeFromCache(each.getEnttype());
                        if (code != null) {
                            each.setEnttypeCn(code.getDisplayvalue());
                        }
                    });
                }
                return RestResult.ok(pages);
            }
        }
        if (page != null && CollectionUtils.isNotEmpty(page.getRecords())) {
            //封装主体类型名称
            page.getRecords().forEach(each -> {
                TREntPriseType code = entPriseTypeService.getEntPriseTypeFromCache(each.getEnttype());
                if (code != null) {
                    each.setEnttypeCn(code.getDisplayvalue());
                }
                String level = eBaseinfoService.getLevelFromCrgs(each.getPripid());
                if (StringUtils.isNotBlank(level)) {
                    each.setLevel(level);
                }
            });
        }
        return RestResult.ok(page);
    }

    @RequestMapping("queryCphStatistics")
    public RestResult<?> queryCphStatistics(@RequestBody Map<String, Object> customParamMap, HttpServletRequest request) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser != null) {
            log.debug("orgId: {} regionId: {}", aicUser.getOrgID(), aicUser.getRegionID());
            String regionId = aicUser.getRegionID();
            customParamMap.put("regionId", regionId);
        } else {
            log.error("用户未登录");
        }
        List<ComprehensiveStat> rs = eBaseinfoService.queryCphStat(customParamMap);
        return RestResult.ok(rs);
    }

    /**
     * 业务查询拆分出经营异常的业务查询
     */
    @RequestMapping("queryCphStatisticsSplit")
    public RestResult<?> queryCphStatisticsSplit(@RequestBody Map<String, Object> customParamMap, HttpServletRequest request) {
        List<ComprehensiveStat> rs = eBaseinfoService.queryCphStatSplit(customParamMap);
        return RestResult.ok(rs);
    }

    @GetMapping("/list")
    public RestResult<List<EBaseinfo>> list(String uscc, String entName) {
        LambdaQueryWrapper<EBaseinfo> lqw = lambdaQuery();
        if (StringUtils.isNotBlank(uscc)) {
            if (StringUtils.isUscc(uscc)) {
                lqw.eq(EBaseinfo::getUniscid, uscc);
            } else {
                lqw.eq(EBaseinfo::getRegno, uscc);
            }
        }
        lqw.eq(StringUtils.isNotBlank(entName), EBaseinfo::getEntname, entName);
        List<EBaseinfo> list = eBaseinfoService.list(lqw);
        for (EBaseinfo eBaseinfo : list) {
            // 中文渲染
            // 经营状态
            Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CA19");
            TRBaseCode code = codeMap.get(eBaseinfo.getRegstate());
            if (code != null) {
                eBaseinfo.setRegstateCn(code.getName());
            }
            // 登记机关
            if (eBaseinfo.getRegorg() != null) {
                String regorgName = baseCodeService.getRegorgName(eBaseinfo.getRegorg());
                if (regorgName != null) {
                    eBaseinfo.setRegorgCn(regorgName);
                }
            }
        }
        return RestResult.ok(list);
    }

    /**
     * 条件查询主体基本信息分页
     *
     * @param pageRequestDto
     * @return
     */
    @ApiOperation("条件查询主体基本信息分页")
    @PostMapping("getBasePage")
    public RestResult<?> getBasePage(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request) {
        AICUser loginUser = getLoginUser(request);
        if (loginUser == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }
        AssertUtils.isNotNull(pageRequestDto, pageRequestDto.getCustomParamMap());
        Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
        if (customParamMap != null) {
            // 处理登记机关参数
            List regorgs = (List) customParamMap.get("regorgs");
            if (CollectionUtils.isNotEmpty(regorgs)) {
                ArrayList<String> regorgsList = new ArrayList<>();
                for (Object regorg : regorgs) {
                    if (regorg instanceof List<?>) {
                        List<?> regorglist = (List<?>) regorg;
                        regorgsList.add(StringUtils.tranObject(regorglist.get(regorglist.size() - 1)));
                    }
                }
                customParamMap.put("regorgs", regorgsList);

            }
            // 处理受理机关参数
            List acceptRegorgs = (List) customParamMap.get("acceptRegorgs");
            if (CollectionUtils.isNotEmpty(acceptRegorgs)) {
                ArrayList<String> acceptRegorgsList = new ArrayList<>();
                for (Object acceptRegorg : acceptRegorgs) {
                    if (acceptRegorg instanceof List<?>) {
                        List<?> acceptRegorglist = (List<?>) acceptRegorg;
                        acceptRegorgsList.add(StringUtils.tranObject(acceptRegorglist.get(acceptRegorglist.size() - 1)));
                    }
                }
                customParamMap.put("acceptRegorgs", acceptRegorgsList);

            }
            // 处理属地监管机关参数
            List suporgs = (List) customParamMap.get("suporgs");
            if (CollectionUtils.isNotEmpty(suporgs)) {
                ArrayList<String> suporgsList = new ArrayList<>();
                for (Object suporg : suporgs) {
                    if (suporg instanceof List<?>) {
                        List<?> suporglist = (List<?>) suporg;
                        suporgsList.add(StringUtils.tranObject(suporglist.get(suporglist.size() - 1)));
                    }
                }
                customParamMap.put("suporgs", suporgsList);

            }
            if (StringUtils.isNotBlank(customParamMap.get("entertype").toString())) {
                customParamMap.put("enttype", customParamMap.get("entertype").toString());
            }
        }
        customParamMap.put("regstate", "1");
//        IPage<EBaseinfo> page = eBaseinfoService.selectAddressAbnPage(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), customParamMap);
        // 改solr查
        //基本主体查询，则sorl查询
        IPage<EBaseInfoSolrBean> resultPage = eBaseinfoService.comprehensiveQuery(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), customParamMap);
        if (CollectionUtils.isNotEmpty(resultPage.getRecords())) {
            for (EBaseInfoSolrBean record : resultPage.getRecords()) {
                //登记机关
                if (StringUtils.isEmpty(record.getRegorgCn())) {
                    record.setRegorgCn(iGzaiccodeService.getNameByCode(record.getRegorg()));
                }
                //受理机关
                if (StringUtils.isEmpty(record.getAcceptregorgCn())) {
                    record.setAcceptregorgCn(iGzaiccodeService.getNameByCode(record.getAcceptRegorg()));
                }
                //属地监管机关
                if (StringUtils.isEmpty(record.getSuporgCn())) {
                    record.setSuporgCn(iGzaiccodeService.getNameByCode(record.getSuporg()));
                }
            }
        }
        return RestResult.ok(resultPage);
//        Page<EBaseInfoSolrBean> page1 = eBaseinfoService.comprehensiveQuery(new Page<>(1, -1), customParamMap);
//        Page<EBaseInfoSolrBean> page = eBaseinfoService.comprehensiveQuery(new Page<>(1, page1.getTotal()), customParamMap);
//        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();
//            }
//            HashMap<String, Object> params = new HashMap<>();
//            params.put("pripids",pripidArray);
//            params.put("entertype",customParamMap.get("entertype").toString());
//            IPage<EBaseinfo> resultPage = eBaseinfoService.selectAddressAbnPage(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), params);
//            if(CollectionUtils.isNotEmpty(resultPage.getRecords())){
//                for (EBaseinfo record : resultPage.getRecords()) {
//                    //登记机关
//                    if(StringUtils.isEmpty(record.getRegorgCn())){
//                        record.setRegorgCn(iGzaiccodeService.getNameByCode(record.getRegorg()));
//                    }
//                    //受理机关
//                    if(StringUtils.isEmpty(record.getAcceptregorgCn())){
//                        record.setAcceptregorgCn(iGzaiccodeService.getNameByCode(record.getAcceptRegorg()));
//                    }
//                    //属地监管机关
//                    if(StringUtils.isEmpty(record.getSuporgCn())){
//                        record.setSuporgCn(iGzaiccodeService.getNameByCode(record.getSuporg()));
//                    }
//                }
//            }
//            return RestResult.ok(resultPage);
//        }else {
//            return RestResult.ok(new Page<EBaseinfo>());
//        }
    }

    @PostMapping("checkExportNum")
    public RestResult checkExportNum(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) throw new BusinessException("登录超时，请重新登录");
        Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
        String searchUscc = StringUtils.tranObject(customParamMap.get("searchUscc"));
        if (StringUtils.isNotBlank(searchUscc)) {
            if (StringUtils.isUscc(searchUscc)) {
                customParamMap.put("uniscid", searchUscc);
            } else {
                customParamMap.put("regno", searchUscc);
            }
        }
        String type = StringUtils.tranObject(customParamMap.get("type"));
        String isGRDZ = StringUtils.tranObject(customParamMap.get("isGRDZ"));
        String yearReport = StringUtils.tranObject(customParamMap.get("yearReport"));
        IPage<EBaseinfo> page = null;
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("entNameJQ")))) {
            page = eBaseinfoService.defaultPaging(pageRequestDto, queryWrapper -> {
                queryWrapper.lambda().eq(EBaseinfo::getEntname, customParamMap.get("entNameJQ").toString());
            }, null);
        }

        if (page == null) {
            // 判断是否查信用信用修复移出时间
            Object searchRemDate = customParamMap.get("searchRemDate");

            if (StringUtils.isNotEmpty(isGRDZ)) {
                if ("GRDZ".equals(isGRDZ)) {
                    customParamMap.put("sole", Constant.REVOKE_SOLE_CODE);
                } else if ("NOGRDZ".equals(isGRDZ)) {
                    customParamMap.put("company", Constant.REVOKE_COMPANY_CODE);
                }
            }
            //片区查询属地监管机关
            if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("regulatory")))) {
                List<String> regulatory = (List<String>) customParamMap.get("regulatory");
                if (regulatory.size() > 0) {
                    String suporg = regulatory.get(regulatory.size() - 1);
                    List<String> idsByParentId = areaSliceService.getIdsByParentId(suporg);     //获取所有子片区id
                    idsByParentId.add(suporg);      //加上父id
                    customParamMap.put("regulatoryList", idsByParentId);
                }
            }
            //登记机关
            if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("regorg")))) {
                List<String> regorg = (List<String>) customParamMap.get("regorg");
                if (regorg.size() > 0) {
                    customParamMap.put("regorgFinal", regorg.get(regorg.size() - 1));   //找出机关列表中的最后一个
                }
            }
            //成立日期
            Object searchDate = customParamMap.get("establishDate");
            if (searchDate instanceof List) {
                List<String> list = (List<String>) searchDate;
                customParamMap.put("eststartDate", list.get(0));
                customParamMap.put("estendDate", list.get(1));
            }
            //核准日期
            Object apprDate = customParamMap.get("apprDate");
            if (apprDate instanceof List) {
                List<String> list = (List<String>) apprDate;
                customParamMap.put("apprDatestart", list.get(0));
                customParamMap.put("apprDateend", list.get(1));
            }
            customParamMap.put("yearReport", yearReport);
            if ("abn".equals(type)) {// 实地查无列异两年以上
                LocalDate date = LocalDate.now().minusYears(2);
                customParamMap.put("abntime", DateUtils.localDateFormat(date, DateUtils.DATE_DEFAULT_FORMAT));
                page = eBaseinfoService.getSDCWandTwoYearsPage(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), customParamMap);
            } else if ("wnb2".equals(type)) {// 连续两年未年报
                // 获取当前日期
                LocalDate currentDate = LocalDate.now();
                int year = currentDate.getYear();
                // 构造6月30日的日期,6月30号为年报提交日期
                LocalDate endDate = LocalDate.of(year, 6, 30);
                String[] reportYear;
                if (currentDate.isBefore(endDate)) {
                    reportYear = new String[]{String.valueOf(year - 2), String.valueOf(year - 3)};
                } else {
                    reportYear = new String[]{String.valueOf(year - 1), String.valueOf(year - 2)};
                }
                List<String> listyear = Arrays.asList(reportYear);
                customParamMap.put("reportYear", listyear);
                customParamMap.put("yearSize", 2);
                IPage<EBaseInfoSolrBean> pages = eBaseinfoService.comprehensiveQuery(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), customParamMap);
                return RestResult.ok(pages.getTotal());
            } else if ("wnbSdcw".equals(type)) {// 两年未年报实地查无
                // 获取当前日期
                LocalDate currentDate = LocalDate.now();
                int year = currentDate.getYear();
                // 构造6月30日的日期,6月30号为年报提交日期
                LocalDate endDate = LocalDate.of(year, 6, 30);
                String[] reportYear;
                if (currentDate.isBefore(endDate)) {
                    reportYear = new String[]{String.valueOf(year - 2), String.valueOf(year - 3)};
                } else {
                    reportYear = new String[]{String.valueOf(year - 1), String.valueOf(year - 2)};
                }
                List<String> listyear = Arrays.asList(reportYear);
                customParamMap.put("reportYear", listyear);
                page = eBaseinfoService.getWnbAndSdcwPage(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), customParamMap);
            } else if (searchRemDate instanceof List) { // 查异常名录表
                if (!aicUser.getOrgName().equals("广州市市场监督管理局")) { // 非市局账号只查自己区移出的
                    customParamMap.put("xzqh", aicUser.getOrgName().substring(0, 2));
                }
                List<String> list = (List<String>) searchRemDate;
                customParamMap.put("remDateStart", list.get(0));
                customParamMap.put("remDateEnd", list.get(1));
                page = eBaseinfoService.pageByRemDate(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), customParamMap);
            } else if (StringUtils.isNotBlank(yearReport)) {
                page = eBaseinfoService.selectYearReport(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), customParamMap);
            } else {
                //基本主体查询，则sorl查询
                IPage<EBaseInfoSolrBean> pages = eBaseinfoService.comprehensiveQuery(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), customParamMap);
                return RestResult.ok(pages.getTotal());
            }
        }
        return RestResult.ok(page.getTotal());
    }

    @ApiOperation("综合查询主体导出")
    @PostMapping("exportInfo2")
    public void exportInfo2(@RequestBody PageRequestDto pageRequestDto, HttpServletResponse response, HttpServletRequest request) throws IOException {
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLUtil.encode("主体名单.xlsx"));
            response.setContentType("application/msexcel;charset=UTF-8");
            ExcelWriter excelWriter = EasyExcel.write(outputStream).build();
            WriteSheet writeSheet = EasyExcel.writerSheet(0, "主体名单").build();

            AICUser aicUser = getLoginUser(request);
            if (aicUser == null) throw new BusinessException("登录超时，请重新登录");
//            String decOrgCode = aicorgService.getRegionCodeByUser(aicUser);
            Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();

            List<String> filedList = (List<String>) customParamMap.get("filedList");

            String searchUscc = StringUtils.tranObject(customParamMap.get("searchUscc"));
            if (StringUtils.isNotBlank(searchUscc)) {
                if (StringUtils.isUscc(searchUscc)) {
                    customParamMap.put("uniscid", searchUscc);
                } else {
                    customParamMap.put("regno", searchUscc);
                }
            }
            String type = StringUtils.tranObject(customParamMap.get("type"));
            String isGRDZ = StringUtils.tranObject(customParamMap.get("isGRDZ"));
            String yearReport = StringUtils.tranObject(customParamMap.get("yearReport"));

            // 判断是否查信用信用修复移出时间
            Object searchRemDate = customParamMap.get("searchRemDate");

            if (StringUtils.isNotEmpty(isGRDZ)) {
                if ("GRDZ".equals(isGRDZ)) {
                    customParamMap.put("sole", Constant.REVOKE_SOLE_CODE);
                } else if ("NOGRDZ".equals(isGRDZ)) {
                    customParamMap.put("company", Constant.REVOKE_COMPANY_CODE);
                }
            }
            customParamMap.put("yearReport", yearReport);
            if (searchRemDate instanceof List) { // 查异常名录表
                if (!aicUser.getOrgName().equals("广州市市场监督管理局")) { // 非市局账号只查自己区移出的
                    customParamMap.put("xzqh", aicUser.getOrgName().substring(0, 2));
                }
                List<String> list = (List<String>) searchRemDate;
                customParamMap.put("remDateStart", list.get(0));
                customParamMap.put("remDateEnd", list.get(1));
                List<String> pripidList = eBaseinfoService.pageByRemDate(customParamMap);
                int total = pripidList.size();
                if (total <= 2000) {
                    List<List<Object>> rs = eBaseinfoService.exportInfo2(pripidList, filedList, true);
                    excelWriter.write(rs, writeSheet);
                } else if (total <= 50000) {
                    int i = total / 2000;
                    int j = total % 2000;
                    for (int a = 1; a <= i; a++) {
                        // 计算当前分页偏移量
                        int offset = a > 0 ? (a - 1) * 2000 : 0;
                        List<String> pripids = pripidList.subList(offset, offset + 2000);
                        List<List<Object>> rs = new ArrayList<>();
                        if (a == 1) {
                            rs = eBaseinfoService.exportInfo2(pripids, filedList, true);
                        } else {
                            rs = eBaseinfoService.exportInfo2(pripids, filedList, false);
                        }
                        excelWriter.write(rs, writeSheet);
                    }
                    if (j != 0) {
                        List<String> pripids = pripidList.subList(i * 2000, total);
                        List<List<Object>> rs = eBaseinfoService.exportInfo2(pripids, filedList, false);
                        excelWriter.write(rs, writeSheet);
                    }
                }
            } else if ("wnb2".equals(type)) {// 连续两年未年报
                //Gzaiccode gzaiccode = tUsersService.findOrganization(aicUser.getPrimaryKey());
                // 获取当前日期
                LocalDate currentDate = LocalDate.now();
                int year = currentDate.getYear();
                // 构造6月30日的日期,6月30号为年报提交日期
                LocalDate endDate = LocalDate.of(year, 6, 30);
                String[] reportYear;
                if (currentDate.isBefore(endDate)) {
                    reportYear = new String[]{String.valueOf(year - 2), String.valueOf(year - 3)};
                } else {
                    reportYear = new String[]{String.valueOf(year - 1), String.valueOf(year - 2)};
                }
                List<String> listyear = Arrays.asList(reportYear);
                customParamMap.put("reportYear", listyear);
                customParamMap.put("yearSize", 2);
//                List<String> regorgList = new ArrayList<>();
//                regorgList.add(gzaiccode.getScountrycode());
//                customParamMap.put("regorg", regorgList);
                IPage<EBaseInfoSolrBean> pages = eBaseinfoService.comprehensiveQuery(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), customParamMap);
                int total = (int) pages.getTotal();
                if (total <= 2000) {
                    org.springframework.data.domain.Page<EBaseInfoSolrBean> rsPage = eBaseinfoService.comprehensiveQuery(customParamMap, 0, total);
                    List<EBaseInfoSolrBean> beans = rsPage.getContent();
                    List<String> pripidList = new ArrayList<>();
                    for (EBaseInfoSolrBean bean : beans) {
                        pripidList.add(bean.getPripid());
                    }
                    List<List<Object>> rs = eBaseinfoService.exportInfo2(pripidList, filedList, true);
                    excelWriter.write(rs, writeSheet);
                } else if (total <= 50000) {
                    int i = total / 2000;
                    int j = total % 2000;
                    for (int a = 1; a <= i; a++) {
                        // 计算当前分页偏移量
                        int offset = a > 0 ? (a - 1) * 2000 : 0;
                        org.springframework.data.domain.Page<EBaseInfoSolrBean> rsPage = eBaseinfoService.comprehensiveQuery(customParamMap, offset, 2000);
                        List<EBaseInfoSolrBean> beans = rsPage.getContent();
                        List<String> pripidList = new ArrayList<>();
                        for (EBaseInfoSolrBean bean : beans) {
                            pripidList.add(bean.getPripid());
                        }
                        List<List<Object>> rs = new ArrayList<>();
                        if (a == 1) {
                            rs = eBaseinfoService.exportInfo2(pripidList, filedList, true);
                        } else {
                            rs = eBaseinfoService.exportInfo2(pripidList, filedList, false);
                        }
                        excelWriter.write(rs, writeSheet);
                    }
                    if (j != 0) {
                        org.springframework.data.domain.Page<EBaseInfoSolrBean> rsPage = eBaseinfoService.comprehensiveQuery(customParamMap, i * 2000, j);
                        List<EBaseInfoSolrBean> beans = rsPage.getContent();
                        List<String> pripidList = new ArrayList<>();
                        for (EBaseInfoSolrBean bean : beans) {
                            pripidList.add(bean.getPripid());
                        }
                        List<List<Object>> rs = eBaseinfoService.exportInfo2(pripidList, filedList, false);
                        excelWriter.write(rs, writeSheet);
                    }
                }
            } else {
                //基本主体查询，则sorl查询
                org.springframework.data.domain.Page<EBaseInfoSolrBean> pages = eBaseinfoService.comprehensiveQuery(customParamMap, -1, -1);
                int total = (int) pages.getTotalElements();
                if (total <= 2000) {
                    org.springframework.data.domain.Page<EBaseInfoSolrBean> rsPage = eBaseinfoService.comprehensiveQuery(customParamMap, 0, total);
                    List<EBaseInfoSolrBean> beans = rsPage.getContent();
                    List<List<Object>> rs = eBaseinfoService.exportInfo2New(beans, filedList, true);
                    excelWriter.write(rs, writeSheet);
                } else if (total <= 50000) {
                    int i = total / 2000;
                    int j = total % 2000;
                    for (int a = 1; a <= i; a++) {
                        // 计算当前分页偏移量
                        int offset = a > 0 ? (a - 1) * 2000 : 0;
                        org.springframework.data.domain.Page<EBaseInfoSolrBean> rsPage = eBaseinfoService.comprehensiveQuery(customParamMap, offset, 2000);
                        List<EBaseInfoSolrBean> beans = rsPage.getContent();
                        List<List<Object>> rs;
                        if (a == 1) {
                            rs = eBaseinfoService.exportInfo2New(beans, filedList, true);
                        } else {
                            rs = eBaseinfoService.exportInfo2New(beans, filedList, false);
                        }
                        excelWriter.write(rs, writeSheet);
                    }
                    if (j != 0) {
                        org.springframework.data.domain.Page<EBaseInfoSolrBean> rsPage = eBaseinfoService.comprehensiveQuery(customParamMap, i * 2000, j);
                        List<EBaseInfoSolrBean> beans = rsPage.getContent();
                        List<List<Object>> rs = eBaseinfoService.exportInfo2New(beans, filedList, false);
                        excelWriter.write(rs, writeSheet);
                    }
                }
            }
            excelWriter.finish();
        } catch (Exception e) {
            log.error("主体查询导出失败", e);
        }
    }

    @ApiOperation("综合查询主体导出")
    @PostMapping("exportInfo")
    public void exportInfo(String pripids, String filedParams, HttpServletResponse response) throws IOException {
        List<String> pripidList = Arrays.asList(pripids.split(","));
        List<String> filedList = Arrays.asList(filedParams.split(","));
        HSSFWorkbook workbook = eBaseinfoService.exportInfo(pripidList, filedList);
        response.setContentType("application/msexcel;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String("主体名单.xls".getBytes(), "UTF-8"));
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            workbook.write(os);
        } catch (IOException e) {
            os.close();
            e.printStackTrace();
        } finally {
            os.close();
        }
    }

    @RequestMapping("queryEAlterByPripid")
    public RestResult<?> queryEAlterByPripid(String pripid) {
        return RestResult.ok(eBaseinfoService.queryEAlterByPripid(pripid));
    }

    @RequestMapping("queryEAlterByEntNo")
    public RestResult<?> queryEAlterByEntNo(String pripid) {
        return RestResult.ok(eAlterRecoderService.queryEAlterByEntNo(pripid));
    }

    /**
     * 查询企业关联的联系人信息
     *
     * @param pripid 主体pripid
     * @author lwd
     * @since 2025年2月19日 14:01:07
     */
    @ApiOperation("查询企业关联的联系人信息")
    @RequestMapping("queryContactByEntNo")
    public RestResult<?> queryContactByEntNo(String pripid) {
        return RestResult.ok(eBaseinfoService.queryContactByEntNo(pripid));
    }

    /**
     * 记录查看联系人操作
     *
     * @param pripid 主体pripid
     * @author lwd
     * @since 2025年2月19日 16:01:07
     */
    @ApiOperation("记录查看联系人操作")
    @RequestMapping("addContactLogByEntNo")
    public RestResult<?> addContactLogByEntNo(String pripid, HttpServletResponse response, HttpServletRequest request) {
        AICUser aicUser = getLoginUser(request);
        return RestResult.ok(eBaseinfoService.addContactLogByEntNo(pripid, aicUser));
    }

    /**
     * 查询强制注销企业列表
     *
     * @param pageRequestDto 分页参数
     * @param request HTTP请求
     * @author lwd
     * @since 2025年10月20日 10:00:00
     */
    @ApiOperation("查询强制注销企业列表")
    @PostMapping("queryForcedLogoutEntList")
    public RestResult<?> queryForcedLogoutEntList(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request) {
        AICUser loginUser = getLoginUser(request);
        if (loginUser == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }

        AssertUtils.isNotNull(pageRequestDto, pageRequestDto.getCustomParamMap());
        Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
        if (customParamMap == null) {
            customParamMap = new HashMap<>();
        }

        // 获取查询参数
        String uniscid = StringUtils.tranObject(customParamMap.get("searchUscc"));
        String entname = StringUtils.tranObject(customParamMap.get("entName"));
        String regorg = StringUtils.tranObject(customParamMap.get("orgNumber"));
        String entType = StringUtils.tranObject(customParamMap.get("entType"));

        // 权限判断：市局人员可以查全市的，区局人员只能查本区的
        String queryRegorg = regorg; // 优先使用传入的regorg
        if (StringUtils.isBlank(queryRegorg)) {
            // 如果没有传入regorg，则根据登录用户权限确定
            if ("001".equals(loginUser.getOrgID())) {
                // 市局账号，可以查全市的，不限制regorg
                queryRegorg = null;
            } else {
                // 区局账号，只能查本区的
                OrgUnits orgModel = tUsersService.byOrgUnitId(loginUser.getOrgID());
                if (orgModel != null && orgModel.getOrgLevel() != null && orgModel.getOrgLevel().equals(3)) {
                    queryRegorg = orgModel.getOrgNumber();
                } else {
                    return RestResult.error(ResultCode.RUNTIME_EXCEPTION);
                }
            }
        }

        // 设置查询参数
        customParamMap.put("uniscid", uniscid);
//        customParamMap.put("entname", entname);
        if ("440101".equals(loginUser.getRegionID())) {
            customParamMap.put("queryRegorg", "440101" );
        }else {
            customParamMap.put("queryRegorg", queryRegorg);
        }
//        customParamMap.put("queryRegorg", queryRegorg);
        customParamMap.put("entType", entType);

        // 执行查询
        IPage<QzzxEntDto> page = eBaseinfoService.queryForcedLogoutEntList(
                new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()),
                customParamMap
        );

        return RestResult.ok(page);
    }

    @RequestMapping("queryEAlterTempByBizseq")
    public RestResult<?> queryEAlterTempByBizseq(String bizseq) {
        return RestResult.ok(eAlterRecoderTempService.queryEAlterTempByBizseq(bizseq));
    }

    /**
     * 综合查询
     * 经营异常名录查询
     * @param pageRequestDto
     * @param request
     * @return
     */
    @PostMapping("/exportqzzxList")
    public void exportqzzxList(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request, HttpServletResponse response) throws IOException{
        AssertUtils.isNotNull(pageRequestDto);
        AICUser curUser = SSOUtil.getUser();
        Map<String, Object> paramMap = pageRequestDto.getCustomParamMap();
        if (curUser != null) {
            if ("440101".equals(curUser.getRegionID())) {
                paramMap.put("regorg", "440101" + "%");
            }else {
                paramMap.put("regorg", curUser.getRegionID().substring(0,6) + "%");
            }
        }

        // 获取数据列表
        List<QzzxEntDto> rs = eBaseinfoService.exportQzzxEntList(paramMap);

        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(
                "强制注销_" + System.currentTimeMillis(),
                "UTF-8"
        );
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        try {
            EasyExcel.write(response.getOutputStream(), QzzxEntDto.class)
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .sheet("强制注销名单")
                    .doWrite(rs);
        } catch (Exception e) {
            log.error("导出失败", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("导出失败：" + e.getMessage());
        }
    }

    @ApiOperation(value = "分页查询市场主体基本信息", position = 5)
    @PostMapping("/pageBaseinfo")
    public RestResult<IPage<EBaseinfo>> pageBaseinfo(@RequestBody BaseQuery<EBaseinfo> query) {
        IPage<EBaseinfo> data = eBaseinfoService.listEBaseinfo(query);
        return RestResult.ok(data);
    }

    @ApiOperation(value = "6.修改单个主体的属地机关", position = 6)
    @PostMapping("/updateBaseinfoSuperviseDept")
    public RestResult<String> updateBaseinfoSuperviseDept(@RequestBody @Valid EBaseinfo eBaseinfo, HttpServletRequest request) {
        AICUser user = getLoginUser(request);
        if (user == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }
        String afterDeptid = eBaseinfo.getAfterDeptid();
        if (StringUtils.isEmpty(afterDeptid)){
            return RestResult.error(ResultCode.PARAM_IS_BLANK);
        }
        eBaseinfoService.updateBaseinfoSuperviseDept(eBaseinfo, afterDeptid, user);
        return RestResult.ok();
    }
}
