package com.chinaweal.aiccs.aiccs.market.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.TSAbnList;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSAttachment;
import com.chinaweal.aiccs.aiccs.abnormal.mapper.GzaiccodeMapper;
import com.chinaweal.aiccs.aiccs.abnormal.service.*;
import com.chinaweal.aiccs.aiccs.blacklist.entity.TPyBlacklist;
import com.chinaweal.aiccs.aiccs.blacklist.service.ITPyBlacklistService;
import com.chinaweal.aiccs.aiccs.business.entity.TSTaskList;
import com.chinaweal.aiccs.aiccs.business.service.TSTaskListService;
import com.chinaweal.aiccs.aiccs.business.service.WorkFlowService;
import com.chinaweal.aiccs.aiccs.dict.entity.CascadeTreeNode;
import com.chinaweal.aiccs.aiccs.fraudreg.service.ITFraudCheckService;
import com.chinaweal.aiccs.aiccs.market.entity.TSUsualInspect;
import com.chinaweal.aiccs.aiccs.market.entity.TSUsualInspectEntList;
import com.chinaweal.aiccs.aiccs.market.mapper.TSUsualInspectMapper;
import com.chinaweal.aiccs.aiccs.market.service.ITSUsualInspectEntListService;
import com.chinaweal.aiccs.aiccs.market.service.ITSUsualInspectService;
import com.chinaweal.aiccs.aiccs.revoke.Vo.EnableListAndCheckVo;
import com.chinaweal.aiccs.aiccs.system.service.TRBaseCodeService;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.util.*;
import com.chinaweal.aiccs.door.entity.TUserportal;
import com.chinaweal.aiccs.door.service.ITUserportalService;
import com.chinaweal.aiccs.org.entity.OrgUnits;
import com.chinaweal.aiccs.org.service.AicorgService;
import com.chinaweal.aiccs.org.service.TUsersService;
import com.chinaweal.aiccs.outside.api.LangChaoDoorApi;
import com.chinaweal.aiccs.outside.dto.LangChaoTaskDto;
import com.chinaweal.aiccs.outside.dto.LangChaoTokenDto;
import com.chinaweal.aiccs.redis.RedisService;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.aicorg.services.OrgUM;
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.BaseServiceImpl;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.page.PageRequestDto;
import com.chinaweal.youfool.framework.springboot.util.AssertUtils;
import com.chinaweal.youfool.framework.sso.util.SSOUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;
import com.chinaweal.aiccs.aiccs.abnormal.entity.ContactLog;


/**
 * <p>
 * 日常检查信息 服务实现类
 * </p>
 *
 * @author chinaweal
 * @since 2021-10-18
 */
@Service
@Slf4j
public class TSUsualInspectServiceImpl extends BaseServiceImpl<TSUsualInspectMapper, TSUsualInspect> implements ITSUsualInspectService {

    private static final String CACHE_KEY_PREFIX = "market:inspect:no_search_data:";
    private static final int CACHE_EXPIRE_TIME = 10 * 60;

    @Resource
    private EBaseinfoService eBaseinfoService;
    @Resource
    private TUsersService tUsersService;
    @Resource
    private TSBizSpeListService tsBizSpeListService;
    @Resource
    private TSUsualInspectMapper tsUsualInspectMapper;
    @Resource
    private ITFraudCheckService itFraudCheckService;
    @Resource
    private TSTaskListService taskListService;
    @Resource
    private ITSUsualInspectEntListService itsUsualInspectEntListService;
    @Resource
    private IGzaiccodeService iGzaiccodeService;
    @Resource
    private TSAttachmentService attachmentService;
    @Resource
    private OrgUM orgUM;
    @Resource
    private AicorgService aicorgService;
    @Resource
    private WorkFlowService workFlowService;
    @Resource
    private TRBaseCodeService baseCodeService;
    @Resource
    private GzaiccodeMapper iGzaiccodeMapper;
    @Resource
    private ITPyBlacklistService iTPyBlacklistService;
    @Resource
    private RedisService redisService;
    @Resource
    private LangChaoDoorApi langChaoDoorApi;
    @Resource
    private ITUserportalService itUserportalService;
    @Resource
    private BizOwnerAssignServiceImpl bizOwnerAssignService;
    @Autowired
    private ContactLogService contactLogService;

    @Override
    public TSUsualInspect saveTSUsualInspect(TSUsualInspect tSUsualInspect) {
        String bizSeq = IdUtil.simpleUUID();

        AICUser user = null;
        // 撤销案件登记现场核查需通过指定人员发起业务，非当前登录人员
        if ("撤销案件登记现场核查".equals(tSUsualInspect.getInspectType()) || "3".equals(tSUsualInspect.getBusType())) {
            user = orgUM.findUserByPrimaryKey(tSUsualInspect.getInspectorId());
        } else {
            user = SSOUtil.getUser();
        }
        tSUsualInspect.setId(bizSeq);
        tSUsualInspect.setInspectOrg(user.getRegionID());
        tSUsualInspect.setBizSeq(bizSeq);
        tSUsualInspect.setStatus("0");
        tSUsualInspect.setBusType("1");

        itsUsualInspectEntListService.save(new TSUsualInspectEntList()
                .setPripid(tSUsualInspect.getPriPId())
                .setBizSeq(bizSeq)
                .setUscc(tSUsualInspect.getUscc())
                .setLegalName(tSUsualInspect.getLegalName())
                .setEntName(tSUsualInspect.getEntName()));

        // 启动工作流
        TSTaskList tsTaskList = new TSTaskList();
        tsTaskList.setBizseqid(bizSeq);
        tsTaskList.setBustype(BaseDataConstant.MARKET_INSPECT);
        tsTaskList.setBusname(tSUsualInspect.getEntName());
        //新待办 设置待办信息
        tsTaskList = HandleWorkFlowUtil.createTaskList(tsTaskList, user);
        //开始工作流
        taskListService.startWorkFlow(tsTaskList, user, FlowUtil.MARKET_INSPECT_WORKFLOW);

//        pushTaskForLangChao(tsTaskList);
        save(tSUsualInspect);
        return tSUsualInspect;
    }

    @Override
    public Map<String, Object> updateTSUsualInspect(TSUsualInspect model) {
        Map<String, Object> resultMap = new HashMap<>();
        AICUser user = SSOUtil.getUser();

        boolean isToIn = true; // 是否需要拟列入
        boolean isBackCall = StringUtils.isNotBlank(model.getBackOpinion()); // 是否需要列异回退
        if(model.getSource().equals("批量吊销")){
            isToIn = false;
            isBackCall = false;
        }
        String pripids = itsUsualInspectEntListService.lambdaQuery().eq(TSUsualInspectEntList::getBizSeq, model.getBizSeq()).list().stream().map(TSUsualInspectEntList::getPripid).collect(Collectors.joining(";"));

        // 列异回退处理
        if (isBackCall) {
            if ("双随机".equals(model.getSource())) {
                tsBizSpeListService.updateClue(model.getInspectResult().equals(model.getSourceInspectResult()) ? "update" : "delete", model.getId());
                isToIn = false;
            } else {
                TSUsualInspect tSUsualInspectSource = this.getById(model.getSourceInspectId());
                isToIn = !tSUsualInspectSource.getInspectResult().equals(model.getInspectResult());
                // 结果相同重新推送，不相同则废弃
                if ("1".equals(model.getBusType())) { // 个案
                    tsBizSpeListService.updateClue(isToIn ? "delete" : "update", model.getId());
                } else { // 批量
                    tsBizSpeListService.updateClueBatch(isToIn ? "delete" : "update", model.getId(), pripids);
                }
            }
        }

        if(StringUtils.isBlank(model.getInspectorId())){
            model.setInspectorId(user.getPrimaryKey());
            model.setInspector(user.getName());
        }

        // 判断是否满足列异 2-未公示 3-弄虚作假 4-实地查无 6-情节严重
        for (String inspectResult : model.getInspectResult().split(",")) {
            if ("2346".contains(inspectResult) && isToIn) {
                if ("1".equals(model.getBusType())) {
                    resultMap = tsBizSpeListService.clueAdd(model.getPriPId(), inspectResult, model.getInspectorId(), model.getInspector(), "3", model.getId());
                } else {
                    tsBizSpeListService.clueAddBatch(
                            pripids,
                            inspectResult,
                            model.getInspectorId(),
                            model.getInspector(),
                            "3",
                            model.getId());
                }
            }
        }


        // 撤销案件登记现场核查(来源) 推送检查结果
        if ("撤销案件登记现场核查".equals(model.getInspectType())) {
            itFraudCheckService.pushCheckStatus(model.getId());
        }

        // 番禺数据标识提示服务需求
        if (Constant.TRUE_1_STR.equals(model.getIsComplained())) {
            itsUsualInspectEntListService.lambdaQuery()
                    .eq(TSUsualInspectEntList::getBizSeq, model.getBizSeq())
                    .list().forEach(t -> {
                        iTPyBlacklistService.save(new TPyBlacklist()
                                .setUniscid(t.getUscc())
                                .setEntName(t.getEntName())
                                .setSourceId(model.getId())
                                .setSourceName(user.getName())
                                .setSourceOrgName(user.getOrgName())
                                .setTagType("4"));
                    });
        }

        model.setStatus("1");
        updateById(model);

        //更新关联信用修复的代办期限时间
        if ( model.getXyxfbizSeq() != null && !"".equals(model.getXyxfbizSeq())) {
            TSTaskList tsTaskListxyxf = taskListService.lambdaQuery().eq(TSTaskList::getBizseqid, model.getXyxfbizSeq()).one();
            tsTaskListxyxf.setDeadlineDate(HolidaysUtil.getNextWorkingDay(5));
            taskListService.updateById(tsTaskListxyxf);
        }

        TSTaskList tsTaskList = taskListService.lambdaQuery().eq(TSTaskList::getBizseqid, model.getBizSeq()).one();
        // 流程推进
        // 判断是否以组为签收单位
        if (StringUtils.isNotBlank(tsTaskList.getAcceptgroupid())) {
            workFlowService.claimGroup(tsTaskList.getWorkflowid(), user.getPrimaryKey());
        }
        taskListService.updateWorkFlow(user, null, tsTaskList,
                "endInspect", new String[]{user.getPrimaryKey()}, null);

        updateTaskForLangChao(tsTaskList.getBizseqid());
        return resultMap;
    }

    /**
     * 获取批吊现场检查结果
     */
    public EnableListAndCheckVo getCheckAndRevResult(String pripid){
        if(StringUtils.isBlank(pripid)) return null;
        EnableListAndCheckVo checkAndRevResult = tsUsualInspectMapper.getCheckAndRevResult(pripid);
        if(checkAndRevResult == null){      //无现场检查任务
            checkAndRevResult = new EnableListAndCheckVo();
            checkAndRevResult.setCheckStatus("0");
            checkAndRevResult.setCheckStatusCN("无现场检查任务");
            checkAndRevResult.setCheckResult("0");
            checkAndRevResult.setCheckResultCN("无检查结果");
        } else {                        //有现场检查任务
            if(checkAndRevResult.getCheckStatus().equals("2") && StringUtils.isNotBlank(checkAndRevResult.getCheckResult())){     //是否已检查
                if(checkAndRevResult.getCheckResult().equals("1")){
                    checkAndRevResult.setCheckResultCN("未发现问题");
                } else if(checkAndRevResult.getCheckResult().equals("4")){
                    checkAndRevResult.setCheckResultCN("通过登记住所（经营场所）无法取得联系");
                } else {
                    checkAndRevResult.setCheckResult("0");
                    checkAndRevResult.setCheckResultCN("无检查结果");
                }
            }else {
                checkAndRevResult.setCheckResult("0");
                checkAndRevResult.setCheckResultCN("无检查结果");
            }
        }
        checkAndRevResult.setPripid(pripid);
        return checkAndRevResult;
    }

    @Override
    public IPage<TSUsualInspect> listTSUsualInspect(BaseQuery<TSUsualInspect> query) {
        TSUsualInspect entity = query.getEntity(TSUsualInspect.class);
        Page<TSUsualInspect> page = query.getPage();

        LambdaQueryWrapper<TSUsualInspect> lambdaQueryWrapper = Wrappers.lambdaQuery();

        return page(page, lambdaQueryWrapper);
    }

    @Override
    public Map<String, Object> batchSave(MultipartFile file, String inspectExpireDate, String source) {

        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> paramsMap;
        String startDate = inspectExpireDate.split(",")[0];
        String endDate = inspectExpireDate.split(",")[1];
        int count; // 需要查询的企业主体数量
        List<String> uniScIds = new ArrayList<>();
        List<String> entNames = new ArrayList<>();
        List<String> regNos = new ArrayList<>();

        try {
            List<Map<Integer, String>> list = EasyExcel.read(file.getInputStream()).sheet(0).doReadSync();
            //移除第一个行表头
            for (Map<Integer, String> item : list) {
                String uniScId = StringUtils.trim(item.get(0));
                String entName = StringUtils.trim(item.get(1));
                String regNo = StringUtils.trim(item.get(2));
                if (StringUtils.isNotBlank(uniScId)) {
                    //统一码
                    uniScIds.add(uniScId);
                } else if (StringUtils.isNotBlank(entName)) {
                    //企业名
                    entNames.add(entName);
                } else if (StringUtils.isNotBlank(regNo)) {
                    //注册号
                    regNos.add(regNo);
                }
            }
            paramsMap = new LinkedHashMap<>();
            paramsMap.put("uniScIds", uniScIds);
            paramsMap.put("entNames", entNames);
            paramsMap.put("regNos", regNos);

            count = uniScIds.size() + entNames.size() + regNos.size();

        } catch (IOException e) {
            log.error("批量查询有误", e);
            throw new BusinessException("请检查文件格式是否有误");
        }

        if (uniScIds.isEmpty() && entNames.isEmpty() && regNos.isEmpty())
            throw new BusinessException("检测出未提供市场主体查询数据,请检查文件格式是否有误");

        if (count > 500)
            throw new BusinessException("批量查询企业主体数量超过500条，请重新调整。");

        List<EBaseinfo> eBaseinfoList = eBaseinfoService.lambdaQuery()
                .eq(EBaseinfo::getRegstate, "1")
                .and(i -> i.in(!uniScIds.isEmpty(), EBaseinfo::getUniscid, uniScIds).or()
                        .in(!regNos.isEmpty(), EBaseinfo::getRegno, regNos).or()
                        .in(!entNames.isEmpty(), EBaseinfo::getEntname, entNames))
                .list();

        Map<String, String> orgMap = baseCodeService.queryOrgName();

        for(EBaseinfo each : eBaseinfoList){
            // 登记机关
            if (each.getRegorg() != null) {
                each.setRegorgCn(orgMap.get(each.getRegorg()));
            }

            //属地监管所
            if (each.getSuporg() != null) {
                List<CascadeTreeNode> org = iGzaiccodeMapper.getNameByOrg(each.getSuporg());
                if(org.size() > 0){
                    each.setSuporgCn(org.get(0).getLabel());
                }
            }
        }

        // 筛选未查询出企业主体提供后续导出
        String id = IdUtil.simpleUUID();
        uniScIds.removeAll(eBaseinfoList.stream().map(EBaseinfo::getUniscid).collect(Collectors.toList()));
        entNames.removeAll(eBaseinfoList.stream().map(EBaseinfo::getEntname).collect(Collectors.toList()));
        regNos.removeAll(eBaseinfoList.stream().map(EBaseinfo::getRegno).collect(Collectors.toList()));
        log.info("查询不出的统一码：{}", JSON.toJSONString(uniScIds));
        log.info("查询不出的企业名称：{}", JSON.toJSONString(entNames));
        log.info("查询不出的注册号：{}", JSON.toJSONString(regNos));
        uniScIds.addAll(entNames);
        uniScIds.addAll(regNos);
        redisService.set(CACHE_KEY_PREFIX + id, JSON.toJSONString(uniScIds), CACHE_EXPIRE_TIME);

        resultMap.put("id", id); // 导出id
        resultMap.put("inCheckNum", eBaseinfoList.size()); // 列入检查数量
        resultMap.put("noCheckNum", count - eBaseinfoList.size()); // 未列入检查数量
        resultMap.put("eBaseinfoList", eBaseinfoList);

        return resultMap;
    }

    @Override
    public Map<String, Object> batchAddressSave(String ids, String inspectExpireDate, String source, String checkAddress) {
        Map<String, Object> resultMap = new HashMap<>();
        String startDate = inspectExpireDate.split(",")[0];
        String endDate = inspectExpireDate.split(",")[1];
        List<String> pripids = Arrays.asList(ids.split(";"));


        if (pripids.isEmpty())
            throw new BusinessException("检测出未提供市场主体查询数据,请检查文件格式是否有误");

        if (pripids.size() > 500)
            throw new BusinessException("批量查询企业主体数量超过500条，请重新调整。");


        List<EBaseinfo> eBaseinfoList = eBaseinfoService.lambdaQuery()
                .eq(EBaseinfo::getRegstate, "1")
                .in(EBaseinfo::getPripid, pripids)
                .list();

        AICUser user = SSOUtil.getUser();

        String bizSeq = IdUtil.simpleUUID();
        if (!eBaseinfoList.isEmpty()) {
            TSUsualInspectEntList tsUsualInspectEntList;
            for (EBaseinfo eBaseinfo : eBaseinfoList) {

                tsUsualInspectEntList = new TSUsualInspectEntList().setBizSeq(bizSeq)
                        .setPripid(eBaseinfo.getPripid())
                        .setEntName(eBaseinfo.getEntname())
                        .setLegalName(eBaseinfo.getLerep())
                        .setDom(eBaseinfo.getDom())
                        .setUscc(eBaseinfo.getUniscid())
                        .setRegStateCn(ConstantsUtil.getRegStateCn(eBaseinfo.getRegstate()));

                if (StringUtils.isNotBlank(eBaseinfo.getRegorg())) {
                    tsUsualInspectEntList.setRegOrgCn(iGzaiccodeService.getNameByCode(eBaseinfo.getRegorg()));
                }

                if (StringUtils.isNotBlank(eBaseinfo.getSuporg())) {
                    tsUsualInspectEntList.setSupOrgCn(iGzaiccodeService.getNameByCode(eBaseinfo.getSuporg()));
                }

                itsUsualInspectEntListService.save(tsUsualInspectEntList);

            }

            // 启动工作流
            String busName = String.format("（%s家）关于%s等企业", eBaseinfoList.size(), eBaseinfoList.get(0).getEntname());
            TSUsualInspect tsUsualInspect = new TSUsualInspect();
            tsUsualInspect.setId(bizSeq);
            tsUsualInspect.setBizSeq(bizSeq);
            tsUsualInspect.setEntName(busName);
            tsUsualInspect.setBusType("2");
            tsUsualInspect.setInspectType("自定义检查");
            tsUsualInspect.setInspectOrg(user.getRegionID());
            tsUsualInspect.setInspectOrgName(user.getOrgName());
            tsUsualInspect.setInspector(user.getName());
            tsUsualInspect.setInspectorId(user.getPrimaryKey());
            tsUsualInspect.setInspectStartDate(LocalDate.parse(startDate));
            tsUsualInspect.setInspectExpireDate(LocalDate.parse(endDate));
            tsUsualInspect.setSource(source);
            tsUsualInspect.setStatus("0");
            tsUsualInspect.setCheckAddress(checkAddress);
            this.save(tsUsualInspect);

            TSTaskList tsTaskList = new TSTaskList();
            tsTaskList.setBizseqid(bizSeq);
            tsTaskList.setBustype(BaseDataConstant.MARKET_INSPECT);
            tsTaskList.setBusname(busName);

            //新待办 设置待办信息
            tsTaskList = HandleWorkFlowUtil.createTaskList(tsTaskList, user);
            //开始工作流
            taskListService.startWorkFlow(tsTaskList, user, FlowUtil.MARKET_INSPECT_WORKFLOW);
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> startManyTask(String ids, String inspectExpireDate, String source) {
        Map<String, Object> resultMap = new HashMap<>();
        String startDate = inspectExpireDate.split(",")[0];
        String endDate = inspectExpireDate.split(",")[1];
        List<String> pripids = Arrays.asList(ids.split(";"));

        if (pripids.isEmpty())
            throw new BusinessException("检测出未提供市场主体查询数据,请检查文件格式是否有误");

        if (pripids.size() > 500)
            throw new BusinessException("批量查询企业主体数量超过500条，请重新调整。");

        List<EBaseinfo> eBaseinfoList = eBaseinfoService.lambdaQuery()
                .eq(EBaseinfo::getRegstate, "1")
                .in(EBaseinfo::getPripid, pripids)
                .list();

        AICUser user = SSOUtil.getUser();

        if (!eBaseinfoList.isEmpty()) {

            for (EBaseinfo eBaseinfo : eBaseinfoList) {
                String bizSeq = IdUtil.simpleUUID();
                TSUsualInspectEntList tsUsualInspectEntList= new TSUsualInspectEntList().setBizSeq(bizSeq)
                        .setPripid(eBaseinfo.getPripid())
                        .setEntName(eBaseinfo.getEntname())
                        .setLegalName(eBaseinfo.getLerep())
                        .setDom(eBaseinfo.getDom())
                        .setUscc(eBaseinfo.getUniscid())
                        .setRegStateCn(ConstantsUtil.getRegStateCn(eBaseinfo.getRegstate()));

                if (StringUtils.isNotBlank(eBaseinfo.getRegorg())) {
                    tsUsualInspectEntList.setRegOrgCn(iGzaiccodeService.getNameByCode(eBaseinfo.getRegorg()));
                }

                if (StringUtils.isNotBlank(eBaseinfo.getSuporg())) {
                    tsUsualInspectEntList.setSupOrgCn(iGzaiccodeService.getNameByCode(eBaseinfo.getSuporg()));
                }

                itsUsualInspectEntListService.save(tsUsualInspectEntList);

                // 启动工作流
                String busName = String.format(eBaseinfo.getEntname());
                TSUsualInspect tsUsualInspect = new TSUsualInspect();
                tsUsualInspect.setId(bizSeq);
                tsUsualInspect.setPriPId(eBaseinfo.getPripid());
                tsUsualInspect.setDom(eBaseinfo.getDom());
                tsUsualInspect.setEntName(eBaseinfo.getEntname());
                tsUsualInspect.setLegalName(eBaseinfo.getLerep());
                tsUsualInspect.setMobilePhone(eBaseinfo.getPhone());
                tsUsualInspect.setContacts(eBaseinfo.getLerep());
                tsUsualInspect.setRegNo(eBaseinfo.getRegno());
                tsUsualInspect.setUscc(eBaseinfo.getUniscid());
                tsUsualInspect.setScope(eBaseinfo.getOpscope());
                tsUsualInspect.setBizSeq(bizSeq);
                tsUsualInspect.setEntName(busName);
                tsUsualInspect.setBusType("1");
                tsUsualInspect.setInspectType("自定义检查");
                tsUsualInspect.setInspectOrg(user.getRegionID());
                tsUsualInspect.setInspectOrgName(user.getOrgName());
                tsUsualInspect.setInspector(user.getName());
                tsUsualInspect.setInspectorId(user.getPrimaryKey());
                tsUsualInspect.setInspectStartDate(LocalDate.parse(startDate));
                tsUsualInspect.setInspectExpireDate(LocalDate.parse(endDate));
                tsUsualInspect.setSource(source);
                tsUsualInspect.setStatus("0");
                this.save(tsUsualInspect);

                TSTaskList tsTaskList = new TSTaskList();
                tsTaskList.setBizseqid(bizSeq);
                tsTaskList.setBustype(BaseDataConstant.MARKET_INSPECT);
                tsTaskList.setBusname(busName);

                //新待办 设置待办信息
                tsTaskList = HandleWorkFlowUtil.createTaskList(tsTaskList, user);
                //开始工作流
                taskListService.startWorkFlow(tsTaskList, user, FlowUtil.MARKET_INSPECT_WORKFLOW);
            }
        }

        return resultMap;
    }

    @Override
    public String backCheck(String id, String opinion, String source, String busType, String sourceInspectResult, String fileId, String pripids) {

        AssertUtils.isNotBlank(opinion, source, busType, pripids);

        List<String> pripidList = Arrays.asList(pripids.split(";"));

        if (pripidList.isEmpty())
            throw new BusinessException("未提供市场主体查询数据");


        List<EBaseinfo> eBaseinfoList = eBaseinfoService.lambdaQuery()
                .eq(EBaseinfo::getRegstate, "1")
                .in(EBaseinfo::getPripid, pripidList)
                .list();

        String bizSeq = IdUtil.simpleUUID();
        if (!eBaseinfoList.isEmpty()) {
            TSUsualInspectEntList tsUsualInspectEntList;
            for (EBaseinfo eBaseinfo : eBaseinfoList) {
                tsUsualInspectEntList = new TSUsualInspectEntList().setBizSeq(bizSeq)
                        .setPripid(eBaseinfo.getPripid())
                        .setEntName(eBaseinfo.getEntname())
                        .setLegalName(eBaseinfo.getLerep())
                        .setDom(eBaseinfo.getDom())
                        .setUscc(eBaseinfo.getUniscid())
                        .setRegStateCn(ConstantsUtil.getRegStateCn(eBaseinfo.getRegstate()));

                if (StringUtils.isNotBlank(eBaseinfo.getRegorg())) {
                    tsUsualInspectEntList.setRegOrgCn(iGzaiccodeService.getNameByCode(eBaseinfo.getRegorg()));
                }

                if (StringUtils.isNotBlank(eBaseinfo.getSuporg())) {
                    tsUsualInspectEntList.setSupOrgCn(iGzaiccodeService.getNameByCode(eBaseinfo.getSuporg()));
                }

                itsUsualInspectEntListService.save(tsUsualInspectEntList);

            }

            // attachmentService 接收附件
            List<TSAttachment> tsAttachmentList = attachmentService.lambdaQuery().eq(TSAttachment::getBizseq, fileId).list();

            TSAttachment tsAttachmentNew = null;
            for (TSAttachment tsAttachment : tsAttachmentList) {
                tsAttachmentNew = new TSAttachment();
                BeanUtil.copyProperties(tsAttachment, tsAttachmentNew, "attachmentid", "bizseq", "uploaddate");
                tsAttachmentNew.setBizseq(bizSeq);
                tsAttachmentNew.setAttachtype("2");
                tsAttachmentNew.setUploaddate(LocalDate.now());
                attachmentService.save(tsAttachmentNew);
            }

            // 启动工作流
            String busName = eBaseinfoList.size() == 1 ? eBaseinfoList.get(0).getEntname() : String.format("（%s家）关于%s等企业", eBaseinfoList.size(), eBaseinfoList.get(0).getEntname());
            TSUsualInspect tsUsualInspect = new TSUsualInspect().setId(bizSeq)
                    .setBizSeq(bizSeq)
                    .setEntName(busName)
                    .setBusType(busType)
                    .setInspectType("自定义检查")
                    .setInspectStartDate(LocalDate.now())
                    .setInspectExpireDate(LocalDate.now().plusDays(15))
                    .setSource(source)
                    .setBackOpinion(opinion)
                    .setStatus("0");

            // 单独检查要补充企业信息
            if ("1".equals(busType)) {
                EBaseinfo eBaseinfo = eBaseinfoList.get(0);
                tsUsualInspect.setPriPId(eBaseinfo.getPripid())
                        .setUscc(eBaseinfo.getUniscid())
                        .setLegalName(eBaseinfo.getLerep())
                        .setDom(eBaseinfo.getDom())
                        .setRegNo(eBaseinfo.getRegno())
                        .setScope(eBaseinfo.getOpscope());
            }

            TSTaskList tsTaskList = new TSTaskList();
            tsTaskList.setBizseqid(bizSeq);
            tsTaskList.setBustype(BaseDataConstant.MARKET_INSPECT);
            tsTaskList.setBusname(busName);


            // 配置流程发起、下一步人员名单
            List<AICUser> userList = null;
            EBaseinfo eBaseinfo = null;
            if ("双随机".equals(source)) {
                tsUsualInspect.setSourceInspectResult(sourceInspectResult);
                eBaseinfo = eBaseinfoList.get(0);
                if (StringUtils.isBlank(eBaseinfo.getSuporg())) {
                    throw new BusinessException("该主体找不到对应监管机关，无法发起回退业务");
                }

                userList = aicorgService.queryByOrgNumberAndSysMenu("market:dynamicsupervision", eBaseinfo.getSuporg());

                if (userList.isEmpty()) {
                    throw new BusinessException("双随机列异回退无法找到发起、接收业务人员");
                }

                if (userList.size() == 1) {
                    AICUser user = userList.get(0);
                    // 新待办 设置待办信息
                    tsTaskList = HandleWorkFlowUtil.createTaskList(tsTaskList, user);
                    // 开始工作流
                    taskListService.startWorkFlow(tsTaskList, user, FlowUtil.MARKET_INSPECT_WORKFLOW);
                } else { // 签收组
                    // 新待办 设置待办信息
                    tsTaskList = HandleWorkFlowUtil.createTaskList(tsTaskList);
                    // 开始工作流
                    taskListService.startWorkFlow(tsTaskList, userList.stream().map(AICUser::getPrimaryKey).collect(Collectors.toList()), eBaseinfo.getSuporg(), FlowUtil.MARKET_INSPECT_WORKFLOW);
                }

            } else {
                TSUsualInspect tsUsualInspectDB = this.getById(id);
                tsUsualInspect.setInspectOrgName(tsUsualInspectDB.getInspectOrgName());
                tsUsualInspect.setInspector(tsUsualInspectDB.getInspector());
                tsUsualInspect.setInspectorId(tsUsualInspectDB.getInspectorId());
                tsUsualInspect.setInspectOrg(tsUsualInspectDB.getInspectOrg());
                tsUsualInspect.setSourceInspectId(id);
                tsUsualInspect.setSourceInspectResult(tsUsualInspectDB.getInspectResult());

                AICUser user = orgUM.findUserByPrimaryKey(tsUsualInspectDB.getInspectorId());

                if (user == null) {
                    throw new BusinessException("市场所监管回退无法找到发起、接收业务人员");
                }

                // 新待办 设置待办信息
                tsTaskList = HandleWorkFlowUtil.createTaskList(tsTaskList, user);
                // 开始工作流
                taskListService.startWorkFlow(tsTaskList, user, FlowUtil.MARKET_INSPECT_WORKFLOW);
            }

            this.save(tsUsualInspect);

        }

        return bizSeq;
    }

    @Override
    public boolean backCheck(String id, String opinion) {
        return true;
    }

    @SneakyThrows
    @Override
    public void exportNoSearchData(String id, HttpServletResponse response) {
        List<List<String>> headList = new ArrayList<>();
        List<String> head0 = new ArrayList<>();
        head0.add("未查出的数据");
        headList.add(head0);

        List<List<String>> dataList = new ArrayList<>();
        String cacheData = redisService.get(CACHE_KEY_PREFIX + id);
        if (StringUtils.isNotBlank(cacheData)) {
            List<String> noSearchDataList = JSON.parseArray(cacheData, String.class);
            for (String data : noSearchDataList) {
                dataList.add(new ArrayList<String>() {{
                    add(data);
                }});
            }
        }

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("未查询出得数据", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream())
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 自定义宽度
                .head(headList)
                .sheet()
                .doWrite(dataList);
    }

    @Override
    public List<TSUsualInspect> getListByPripid(String pripid) {
        return tsUsualInspectMapper.getListByPripid(pripid);
    }

    @Override
    public Map<String, List<Map<String, String>>> statistics() {

        Map<String, List<Map<String, String>>> resultMap = new LinkedHashMap<>();

        AICUser aicUser = SSOUtil.getUser();

        // 按机构统计
        List<OrgUnits> orgUnits = tUsersService.byNextLevelPlace(aicUser.getOrgID());
        orgUnits.forEach(o -> {
            // 只统计机构，过滤掉部门
            if ("1".equals(o.getUnitType())) {
                resultMap.put(o.getOrgUnitName(), tsUsualInspectMapper.statistics(o.getOrgNumber()));
            }
        });

        return resultMap;
    }

    @Override
    public void repairData() {
        List<TSUsualInspect> list = this.lambdaQuery().eq(TSUsualInspect::getStatus, "0").isNull(TSUsualInspect::getBizSeq).list();

        TSUsualInspect tsUsualInspect = null;
        for (TSUsualInspect tsUsualInspectDB : list) {
            tsUsualInspect = new TSUsualInspect();
            BeanUtil.copyProperties(tsUsualInspectDB, tsUsualInspect, "id", "createBy", "createTime", "updateBy", "updateTime");
            tsUsualInspect.setBusType("3");

            //重新生成业务
            tsUsualInspect = saveTSUsualInspect(tsUsualInspect);

            // 废弃旧数据
            tsUsualInspectDB.setStatus("3");
            tsUsualInspectDB.setSourceInspectId(tsUsualInspect.getBizSeq());
            updateById(tsUsualInspectDB);
        }

    }

    @Override
    public List<TSUsualInspect> queryHistroyListByPripid(String pripid) {
        return baseMapper.queryHistroyListByPripid(pripid);
    }

    @Override
    public List<TSUsualInspect> getPageByTask(Map<String, Object> param){
        return baseMapper.getPageByTask(param);
    }

    @Override
    public Integer countByTask(Map<String, Object> param){
        return baseMapper.countByTask(param);
    }

//    /**
//     * 推送浪潮待办
//     *
//     * @param tsTaskList
//     * @return
//     * @author ymc
//     * @since 2024年10月10日 11:16
//     */
//    private boolean pushTaskForLangChao(TSTaskList tsTaskList) {
//        AICUser user = SSOUtil.getUser();
//
//        String redisKey = ConstantsUtil.LANG_CHAO_ACCESS_TOKEN_KEY + user.getEname();
//        if (redisService.exists(redisKey)) {
//
//            LangChaoTokenDto langChaoTokenDto = JSON.parseObject(redisService.get(redisKey), LangChaoTokenDto.class);
//            String bizUrl = "http://10.207.148.172/integration/#/aiccs/market/dynamicsupervision";
//
//            // 获取企业名称 + 任务名称
//            String taskName = tsTaskList.getBusname() + "_现场核查";
//
//            TUserportal signer = itUserportalService.getByLocalUserId(tsTaskList.getSignuserid());
//
//            // 注意此处为异步请求，正式上线请谨慎选择
//            Map<String, List<LangChaoTaskDto>> taskList = new HashMap<>();
//            List<LangChaoTaskDto> langChaoTaskDtos = new ArrayList<>();
//            LangChaoTaskDto langChaoTaskDto = new LangChaoTaskDto();
//            langChaoTaskDto.setTaskName(taskName);
//            langChaoTaskDto.setTaskUrgencyLevel("01");
//            langChaoTaskDto.setSystemName("信用监管综合系统");
//            langChaoTaskDto.setSystemCode("6");
//            langChaoTaskDto.setTaskAssignType("0");
//            langChaoTaskDto.setTaskIssueType("指定用户");
//            langChaoTaskDto.setTaskDetailUrl("https://sjzx.scjgj.gz.gov.cn/auth/oauth/authorize?response_type=code&scope=trust&state=LangChao&client_id=zwtxyjg&redirect_uri=" + URLUtil.encode(bizUrl));
//            langChaoTaskDto.setTaskResultUrl("https://sjzx.scjgj.gz.gov.cn/auth/oauth/authorize?response_type=code&scope=trust&state=LangChao&client_id=zwtxyjg&redirect_uri=" + URLUtil.encode(bizUrl));
//            langChaoTaskDto.setTaskSerialNo(tsTaskList.getBizseqid());
//            langChaoTaskDto.setTaskTargetName(tsTaskList.getBusname());
//            langChaoTaskDto.setTaskTargetSign("无"); // todo
//            langChaoTaskDto.setTaskCorpId(signer.getOrgid());
//            langChaoTaskDto.setTaskCorpName("无"); // todo
//            langChaoTaskDto.setTaskDeptId(signer.getOrgid());
//            langChaoTaskDto.setTaskDeptName("无");// todo
//            langChaoTaskDto.setTaskPersonId(signer.getUsername());
//            langChaoTaskDto.setTaskPersonName(signer.getRealname());
//            langChaoTaskDto.setTaskContent("信用在线-现场核查");
//            langChaoTaskDtos.add(langChaoTaskDto);
//            taskList.put("originalTasks", langChaoTaskDtos);
//            langChaoDoorApi.insertTaskFromOriginal(langChaoTokenDto.getAccess_token(), taskList);
//
//        }
//
//        return true;
//    }

    /**
     * 更新浪潮待办
     * @author ymc
     * @since 2024年10月10日 19:38
     * @param bizSeq
     * @return
     */
    public boolean updateTaskForLangChao(String bizSeq) {
        AICUser user = SSOUtil.getUser();
        String redisKey = ConstantsUtil.LANG_CHAO_ACCESS_TOKEN_KEY + user.getEname();
        if (redisService.exists(redisKey)) {
            LangChaoTokenDto langChaoTokenDto = JSON.parseObject(redisService.get(redisKey), LangChaoTokenDto.class);
            String langChaoTaskId = bizSeq;
            // 注意此处为异步请求，正式上线请谨慎选择
            log.info("浪潮待办id: {}", langChaoTaskId);
            langChaoDoorApi.taskTodoUpdateFinish(langChaoTokenDto.getAccess_token(), bizSeq);
        }
        return true;
    }

    /**
     * 生成现场核查代办
     * @author lwd
     * @since 2025年03月25日 15:38
     * @return
     */
    @Override
    public Map<String, String> savewsqTSUsualInspect(TSAbnList tsAbnListModel,String bizseqUp, EBaseinfo baseinfo) {
        Map<String, String> map = new HashMap<>();
        try {
            String permission = "market:dynamicsupervision";
            List<String> userIdListxc = null;
            if ("440101".equals(tsAbnListModel.getDecorg().substring(0,6))){
                userIdListxc = iGzaiccodeService.byPermissionListHandleUserList(tsAbnListModel.getPripid(), permission, baseinfo.getSuporg(), baseinfo.getRegion())
                        .stream().map(AICUser::getPrimaryKey).collect(Collectors.toList());
            }else {
                userIdListxc = iGzaiccodeService.byPermissionListHandleUserList(tsAbnListModel.getPripid(), permission, tsAbnListModel.getDecorg(), tsAbnListModel.getIntoDecorg())
                        .stream().map(AICUser::getPrimaryKey).collect(Collectors.toList());
            }


            if (userIdListxc.isEmpty()) {
                log.error("分派失败，受理人列表为空,tsabnlist为：{},权限为：{}", tsAbnListModel, permission);
                map.put("status", "1");
                throw new BusinessException("现场检查受理人列表为空！");
            }
            PageRequestDto pageRequestDto = new PageRequestDto();
            Map<String, Object> customParamMap1 = new HashMap<>();
            customParamMap1.put("regno",tsAbnListModel.getUniscid());
            pageRequestDto.setCurPage(1);
            pageRequestDto.setPageSize(10);
            pageRequestDto.setCustomParamMap(customParamMap1);
            AICUser aicUser = orgUM.findUserByPrimaryKey(userIdListxc.get(0));
            IPage<EBaseinfo> data = eBaseinfoService.defaultPaging(pageRequestDto, queryWrapper -> {
                queryWrapper.lambda().eq(EBaseinfo::getRegstate, "1");


                if (!"440101".equals(aicUser.getRegionID())) { // 区所局
                    queryWrapper.lambda().likeRight(EBaseinfo::getSuporg, aicUser.getRegionID().substring(0, 6));
                }

                Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
                if (customParamMap == null || customParamMap.isEmpty()) return;
                String entType = customParamMap.get("entType") != null ? customParamMap.get("entType").toString() : null;
                if ("individual".equals(entType)) {
                    queryWrapper.lambda().eq(EBaseinfo::getEnttype, "9910");
                } else if ("farmer".equals(entType)) {
                    queryWrapper.lambda().in(EBaseinfo::getEnttype, "9100", "9200");
                } else if ("company".equals(entType)) {
                    queryWrapper.lambda().notIn(EBaseinfo::getEnttype, "9910", "9100", "9200");
                }
                String regno = customParamMap.get("regno") != null ? customParamMap.get("regno").toString() : null;
                if (StringUtils.isNotBlank(regno)) {
                    queryWrapper.lambda().and(fq -> fq.or(eq -> eq.eq(EBaseinfo::getUniscid, regno)).or(eq -> eq.eq(EBaseinfo::getRegno, regno)));
                }

                if (customParamMap.get("entname")!= null && StringUtils.isNotBlank(customParamMap.get("entname").toString())) {
                    queryWrapper.lambda().eq(EBaseinfo::getEntname, customParamMap.get("entname").toString());
                }

                if (customParamMap.get("sliceId") != null && StringUtils.isNotBlank(customParamMap.get("sliceId").toString())) {
                    List<String> pripIds = new ArrayList<>();
                    String sliceId = customParamMap.get("sliceId").toString();
                    bizOwnerAssignService.listBySliceId(sliceId).forEach(item -> { pripIds.add(item.getPripid()); });
                    queryWrapper.lambda().in(EBaseinfo::getPripid, pripIds);
                }
            }, null);

            TSUsualInspect tsUsualInspect = new TSUsualInspect();
            EBaseinfo eBaseinfo = data.getRecords().get(0);
            String bizSeq =  IdUtil.simpleUUID();
            tsUsualInspect.setId(bizSeq);
            tsUsualInspect.setBizSeq(bizSeq);
            tsUsualInspect.setPriPId(eBaseinfo.getPripid());
            tsUsualInspect.setRegNo(eBaseinfo.getRegno());
            tsUsualInspect.setUscc(eBaseinfo.getUniscid());
            tsUsualInspect.setEntName(eBaseinfo.getEntname());
            tsUsualInspect.setLegalName(eBaseinfo.getLerep());
            tsUsualInspect.setDom(eBaseinfo.getDom());
            tsUsualInspect.setContacts(eBaseinfo.getName());
            tsUsualInspect.setContactPhone(eBaseinfo.getPhone());
            tsUsualInspect.setMobilePhone(eBaseinfo.getPhone());
            tsUsualInspect.setScope(eBaseinfo.getOpscope());
            tsUsualInspect.setInspectType("自定义巡查");
            tsUsualInspect.setInspectOrg(aicUser.getRegionID());
            tsUsualInspect.setInspectOrgName(aicUser.getOrgName());
            tsUsualInspect.setSource("其他");
            tsUsualInspect.setInspectStartDate(LocalDate.now());
            tsUsualInspect.setInspectExpireDate(LocalDate.now().plusDays(30));
            tsUsualInspect.setStatus("0");
            tsUsualInspect.setBusType("1");
            tsUsualInspect.setCreateBy("系统发起");
            tsUsualInspect.setXyxfbizSeq(bizseqUp);

            itsUsualInspectEntListService.save(new TSUsualInspectEntList()
                    .setPripid(tsUsualInspect.getPriPId())
                    .setBizSeq(bizSeq)
                    .setUscc(tsUsualInspect.getUscc())
                    .setLegalName(tsUsualInspect.getLegalName())
                    .setEntName(tsUsualInspect.getEntName()));

            // 启动工作流
            TSTaskList tsTaskList = new TSTaskList();
            tsTaskList.setBizseqid(bizSeq);
            tsTaskList.setBustype(BaseDataConstant.MARKET_INSPECT);
            tsTaskList.setBusname(tsUsualInspect.getEntName());
            //新待办 设置待办信息
            tsTaskList = HandleWorkFlowUtil.createTaskList(tsTaskList);
            //开始工作流
//        taskListService.startWorkFlow(tsTaskList, aicUser, FlowUtil.MARKET_INSPECT_WORKFLOW);
            taskListService.startWorkFlow(tsTaskList, userIdListxc, aicUser.getRegionID().substring(0, 6), FlowUtil.MARKET_INSPECT_WORKFLOW);

//            pushTaskForLangChao(tsTaskList);
            save(tsUsualInspect);
        }catch (Exception e) {
            e.printStackTrace();
            log.error("生成现场核查失败！" + e.getMessage());
            map.put("status", "1");
            throw new BusinessException("生成现场核查失败！");
        }
        map.put("status", "0");
        return map;
    }

    @Override
    public TSUsualInspect getbyXyfxbizSeq(String bizseq) {
        return baseMapper.getbyXyfxbizSeq(bizseq);
    }

    @Override
    public Object addContactLogByEntNo(String pripid, String originalValue, AICUser aicUser) {
        Map<String,Object> map = new HashMap<>();
        ContactLog contactLog = new ContactLog();

        contactLog.setId(UUID.randomUUID().toString());
        contactLog.setPripId(pripid);
        contactLog.setOperatorName(aicUser.getName());
        contactLog.setOperatorId(aicUser.getPrimaryKey());
        contactLog.setOperationTime(new Timestamp(System.currentTimeMillis()));
        contactLog.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        contactLog.setCreateTime(new Timestamp(System.currentTimeMillis()));
        contactLog.setContentText("操作人员查看了：" + originalValue);

        try {
            contactLogService.save(contactLog);
            map.put("flag", "yes");
        }catch (Exception e) {
            map.put("flag", "no");
        }

        return map;
    }
}
