package digital.laboratory.platform.entrustment.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import digital.laboratory.platform.common.core.constant.CommonConstants;
import digital.laboratory.platform.common.core.util.R;
import digital.laboratory.platform.othersys.dto.EntrustQueryParams;
import digital.laboratory.platform.entrustment.entity.*;
import digital.laboratory.platform.entrustment.enums.EntrustmentStatusConstants;
import digital.laboratory.platform.entrustment.mapper.EntrustDataVoMapper;
import digital.laboratory.platform.entrustment.service.*;
import digital.laboratory.platform.othersys.dto.DataAuditBaseDto;
import digital.laboratory.platform.othersys.dto.EntrustDataDto;
import digital.laboratory.platform.othersys.utils.ConvertUtils;
import digital.laboratory.platform.othersys.utils.HttpsUtils;
import digital.laboratory.platform.othersys.vo.*;
import digital.laboratory.platform.sys.entity.Dictionary;
import digital.laboratory.platform.sys.entity.DrugLite;
import digital.laboratory.platform.sys.entity.SysUser;
import digital.laboratory.platform.sys.entity.entrustment.IMAdditionalProperty;
import digital.laboratory.platform.sys.feign.RemoteDictionaryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @ClassName SynchronizeDataServiceImpl
 * @Description
 * @Author xy
 * @Date 2023/6/13 11:02
 * @Version 1.0
 **/
@Slf4j
@Service
public class SynchronizeDataServiceImpl extends ServiceImpl<EntrustDataVoMapper, EntrustOfThirdSys> implements SynchronizeDataService {
    //保存第三方系统的委托数据
    @Resource
    private SynchronizeMaterialVoService synchronizeMaterialVoService;
    @Resource
    private EntrustmentIdentificationMaterialService entrustmentIdentificationMaterialService;
    @Resource
    private CaseEventService caseEventService;
    @Resource
    private CaseEvidenceService caseEvidenceService;
    @Resource
    private RemoteDictionaryService remoteDictionaryService;//字典接口
    @Resource
    private EntrustmentService entrustmentService;//委托书服务

    @Resource
    private CommonFeignService commonFeignService;

    //鉴定结果提交
    public Boolean submitIdentifyResult(String dataPath, String entrustId) {
        SynConnInfoVo synConnInfoVo = getSysSynConnInfo();
        String token = getTokenInfo("SubCenter", synConnInfoVo);
        String remoteUrl = synConnInfoVo.getApiHost() + dataPath + "?token=" + token;
        //构造请求体
        AnalysisDataVo analysisDataVo = new AnalysisDataVo();
        String jsonStr = JSON.toJSONString(analysisDataVo);
        try {
            DataModelVo retDataModelVo = HttpsUtils.PostDataToServerByPathParams(remoteUrl, jsonStr, HttpMethod.PUT, entrustId);
            if (retDataModelVo.getStatusCode().equals("SUCCESS")) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 分中心受理
     *
     * @param dataPath
     * @param selfEntrust
     * @param thirdSysEntrust
     * @return
     */
    @Override
    @Transactional
    public Boolean subCenterAccept(String dataPath, Entrustment selfEntrust, EntrustOfThirdSys thirdSysEntrust) throws JsonProcessingException {
        SynConnInfoVo synConnInfoVo = getSysSynConnInfo();
        String token = getTokenInfo("SubCenter", synConnInfoVo);
        String remoteUrl = synConnInfoVo.getApiHost() + dataPath + "?token=" + token;
        //构造受理的请求体
        //我方检材
        List<EntrustmentIdentificationMaterial> entrustmentIdentificationMaterialList = entrustmentIdentificationMaterialService.list(Wrappers.<EntrustmentIdentificationMaterial>query()
                .eq("entrustment_id", selfEntrust.getId())
                .orderByAsc("order_no"));
        //创建方法描述
        String samplingMethod = "";
        BigDecimal analysisSampleAmountSum = new BigDecimal(0);
        BigDecimal retainedSampleAmountSum = new BigDecimal(0);
        for (EntrustmentIdentificationMaterial materialObj : entrustmentIdentificationMaterialList) {
            //
            if (materialObj.getSample1RepeatWeigh() != null && materialObj.getSample1RepeatWeigh().compareTo(BigDecimal.ZERO) != 0) {
                analysisSampleAmountSum = analysisSampleAmountSum.add(materialObj.getSample1RepeatWeigh());
            } else {
                analysisSampleAmountSum = analysisSampleAmountSum.add(materialObj.getSample1Quantity());
            }
            if (materialObj.getSample2RepeatWeigh() != null && materialObj.getSample2RepeatWeigh().compareTo(BigDecimal.ZERO) != 0) {
                retainedSampleAmountSum = retainedSampleAmountSum.add(materialObj.getSample2RepeatWeigh());
            } else {
                retainedSampleAmountSum = retainedSampleAmountSum.add(materialObj.getSample2Quantity());
            }


//            analysisSampleAmountSum=analysisSampleAmountSum.add(materialObj.getSample1RepeatWeigh());
//            retainedSampleAmountSum=retainedSampleAmountSum.add(materialObj.getSample2RepeatWeigh());
        }
        if (analysisSampleAmountSum.compareTo(BigDecimal.ZERO) > 0 && retainedSampleAmountSum.compareTo(BigDecimal.ZERO) > 0) {
            samplingMethod = "将检材分装为分析样、留存样";
        } else if (analysisSampleAmountSum.compareTo(BigDecimal.ZERO) == 0) {
            samplingMethod = "检材全部为留存样";
        } else if (retainedSampleAmountSum.compareTo(BigDecimal.ZERO) == 0) {
            samplingMethod = "检材全部为分析样";
        }

        //将受理时确定的方法持久化
        thirdSysEntrust.setSamplingMethod(samplingMethod);
        this.updateById(thirdSysEntrust);
        //第三方检材
        List<EntrustMaterialOfThirdSys> entrustMaterialOfThirdSysList = synchronizeMaterialVoService.list(
                Wrappers.<EntrustMaterialOfThirdSys>query().eq("entrust_id", thirdSysEntrust.getId()).orderByAsc("order_index"));

        //给第三方检材复称的数据
        entrustmentIdentificationMaterialList.forEach(matreialObj -> {

            entrustMaterialOfThirdSysList.forEach(otherItem -> {
                if (otherItem.getId().equals(matreialObj.getId())) {
                    //万一没复称数据，在受理委托的时候，如果发现没有复秤，就不让受理  1225 更新取消
                    //这代表已经复称了 复称后单位要改为克，如果没有复称 单位则沿用原来的
                    if (matreialObj.getSample1RepeatWeigh() != null && matreialObj.getSample1RepeatWeigh().compareTo(BigDecimal.ZERO) != 0) {
                        otherItem.setAnalysisSampleAmount(matreialObj.getSample1RepeatWeigh());
                        otherItem.setUnit("gram");
                        otherItem.setSampleUnit("gram");

                    } else {
                        otherItem.setAnalysisSampleAmount(matreialObj.getSample1Quantity());
                        otherItem.setSampleUnit(ConvertUtils.getUnitByZhCn(matreialObj.getUnit()));
                    }
                    if (matreialObj.getSample2RepeatWeigh() != null && matreialObj.getSample2RepeatWeigh().compareTo(BigDecimal.ZERO) != 0) {
                        otherItem.setRetainedSampleAmount(matreialObj.getSample2RepeatWeigh());
                    } else {
                        otherItem.setRetainedSampleAmount(matreialObj.getSample2Quantity());
                    }

//                    otherItem.setAnalysisSampleAmount(matreialObj.getSample1RepeatWeigh());
//                    otherItem.setRetainedSampleAmount(matreialObj.getSample2RepeatWeigh());
//                    otherItem.setSampleUnit(ConvertUtils.getUnitByZhCn(matreialObj.getUnit()));

                    //有的检材不用复称了
                    if (matreialObj.getSample1RepeatWeigh() != null && matreialObj.getSample1RepeatWeigh().compareTo(BigDecimal.ZERO) != 0) {
                        otherItem.setTotalSampleAmount(matreialObj.getSample1RepeatWeigh());
                    } else {
                        otherItem.setTotalSampleAmount(matreialObj.getSample1Quantity());
                    }
                    if (matreialObj.getSample2RepeatWeigh() != null && matreialObj.getSample2RepeatWeigh().compareTo(BigDecimal.ZERO) != 0) {
                        otherItem.setTotalSampleAmount(otherItem.getTotalSampleAmount().add(matreialObj.getSample2RepeatWeigh()));
                    } else {
                        otherItem.setTotalSampleAmount(otherItem.getTotalSampleAmount().add(matreialObj.getSample2Quantity()));
                    }
//                    otherItem.setTotalSampleAmount(matreialObj.getSample1RepeatWeigh().add(matreialObj.getSample2RepeatWeigh()));
                }
            });
        });
        //这里我们将受理的属性也持久化
        boolean ret = synchronizeMaterialVoService.updateBatchById(entrustMaterialOfThirdSysList);
//        for (EntrustMaterialOfThirdSys entrustMaterialOfThirdSys : entrustMaterialOfThirdSysList) {
//            System.out.println(entrustMaterialOfThirdSys.getName() + "~~~~~~~~~~~~~~~~~~看看我们提供给大数据平台的Order编号：" + entrustMaterialOfThirdSys.getOrder_index());
//        }
        System.out.println(ret);
        DataAuditBaseDto dataAuditBaseDto = genSubCenterAcceptData(thirdSysEntrust, entrustMaterialOfThirdSysList, samplingMethod);
        String jsonStr = JSON.toJSONString(dataAuditBaseDto);
        System.out.println("submit的数据：" + jsonStr);
        DataModelAcceptVo retDataModelVo = HttpsUtils.PostDataToServerByPathParamsAccept(remoteUrl, jsonStr, HttpMethod.PUT, thirdSysEntrust.getId());
        log.info("准备调用大数据平台委托受理接口，提交信息为{}", jsonStr);
        if (retDataModelVo.getStatusCode().equals("SUCCESS")) {
            System.out.println(JSONObject.toJSONString("受理执行结果" + retDataModelVo));
            //这里如果成功，我们应该获取受理成功的受理编号，并将这个编号存到我们的库中
            String thirdSysAcceptNo = retDataModelVo.getResult();
            log.info("接口调用成功 {} 返回的受理编号{}", remoteUrl, thirdSysAcceptNo);
            //将这个编号反写到我们的系统中

            selfEntrust.setAcceptNoThirdSys(thirdSysAcceptNo);
            selfEntrust.setAcceptNo(thirdSysAcceptNo);

            //按受理顺序生成检材的受理编号
            for (int i = 0; i < entrustmentIdentificationMaterialList.size(); i++) {
                EntrustmentIdentificationMaterial entrustmentIdentificationMaterial = entrustmentIdentificationMaterialList.get(i);
                entrustmentIdentificationMaterial.setAcceptNo(thirdSysAcceptNo + "-" + entrustmentIdentificationMaterial.getOrderNo());
            }
            entrustmentIdentificationMaterialService.updateBatchById(entrustmentIdentificationMaterialList);
            entrustmentService.updateById(selfEntrust);
            return true;
        } else {
            log.info("调用大数据平台委托受理接口失败，错误信息{} {} {}", retDataModelVo.getBusinessError().getCode(), retDataModelVo.getBusinessError().getMessage());
            return false;
        }

    }

    /**
     * 省级审核委托 和分中心审核委托
     *
     * @param userFlag          用户标识，是分中心用户还是省级用户
     * @param dataPath          API的访问路径
     * @param thirdSysEntrustID
     * @param result
     * @param reMark
     * @param auditOrAccept
     * @return
     */
    @Override
    public Boolean auditEntrustByProvinceOrCenter(String userFlag, String dataPath, String thirdSysEntrustID, String result,
                                                  String reMark, String auditOrAccept) {
        SynConnInfoVo synConnInfoVo = getSysSynConnInfo();
        String token = getTokenInfo(userFlag, synConnInfoVo);//获取到token,根据用户标识
        // /api/identify/entrust/{entrustId}/provinceAudit,这个是省级审核地址，如果是分中心，则审核地址是/api/identify/entrust/{entrustId}/acceptAudit
        String remoteUrl = synConnInfoVo.getApiHost() + dataPath + "?token=" + token;
        //构建请求体
        EntrustOfThirdSys entrustOfThirdSys = this.getById(thirdSysEntrustID);
        List<EntrustMaterialOfThirdSys> entrustMaterialOfThirdSysList = synchronizeMaterialVoService.list(
                Wrappers.<EntrustMaterialOfThirdSys>query().eq("entrust_id", thirdSysEntrustID));
        DataAuditBaseDto dataAuditBaseDto = genProvinceAuditData(entrustOfThirdSys, entrustMaterialOfThirdSysList, result, reMark, auditOrAccept);
        String jsonStr = JSON.toJSONString(dataAuditBaseDto);
        try {
            DataModelVo retDataModelVo = HttpsUtils.PostDataToServerByPathParams(remoteUrl, jsonStr, HttpMethod.PUT, thirdSysEntrustID);
            log.info("准备调用大数据平台委托 {} 接口，提交信息为{}", auditOrAccept, jsonStr);
            if (retDataModelVo.getStatusCode().equals("SUCCESS")) {
                log.info("接口调用成功 {}", remoteUrl);
                return true;
            } else {
                log.info("调用大数据平台委托接口失败，错误信息为{} {}", retDataModelVo.getBusinessError().getCode(), retDataModelVo.getBusinessError().getMessage());
                return false;
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 同步委托数据
     *
     * @param entrustStatus
     * @param userFlag
     * @return
     */
    public Boolean synEntrustDataToMyServer(String entrustStatus, String userFlag) {
        Boolean ret = true;

        DataModelVo dataModelVo = fetchDataFromRemote(entrustStatus);
        if (dataModelVo == null) {
            ret = false;
            throw new RuntimeException("远程获取数据失败，请检查网络及请求参数是否正常");
        }
        List<EntrustDataVo> entrustDataVoList = dataModelVo.getResult().getList();//获取到的数据，分别处理这些数据
        if (entrustStatus.trim().equals("accepted")) {
            log.info("本次处理的是已受理数据 数据量是 {} ", entrustDataVoList.size());
            //这里在系统初始化的时候，会同步禁毒系统已受理的数据，这单独用一个函数处理
            handelAcceptedStatusData(entrustDataVoList);
            return true;
        }
        for (EntrustDataVo entrustDataVo : entrustDataVoList) {
            //这里要查重复，如果已经同步过了，就不需要再同步
            if (checkExistEntrust(entrustDataVo.getId())) {
                //这里需要注意另外一种情况要更新，我们此时需要判断是否符合更新条件，如果符合执行更新，如果有数据是被省级退回，或者分中心审核退回的，
                // 这个时候，我们应该更新这条数据的委托编号，因为委托的ID 并没改变
                updateThirdSysData(entrustDataVo);
                //这里需要判断，如果在审核、审批的列表中同步了数据过来，但是又没有通过智慧实验室系统进行审核、审批，然后又在禁毒大数据进行了审核审批，
                //会导致两边系统委托的状态不一致，我们要以禁毒大数据平台的为准，所以要改变智慧实验室系统委托的状态
                if (entrustStatus.equals("toAccept")) {
                    EntrustOfThirdSys entrustOfThirdSys = this.getById(entrustDataVo.getId());
                    Entrustment entrustment = entrustmentService.getById(entrustOfThirdSys.getEntrustMainId());
                    if (entrustment != null && !(entrustment.getStatus().equals(EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_ACCEPT.getStatus()))) {
                        //如果禁毒大数据平台的状态是待受理，而智慧实验室不是，那么我们将状态也改为待受理
                        entrustment.setStatus(EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_ACCEPT.getStatus());
                        entrustmentService.updateById(entrustment);
                        log.info("将数据更新至待受理状态了 {} ", entrustment.getId());
                    }
                }
                System.out.println("数据已经同步过了，不需要再次同步");
                log.info("数据已经同步过了，不需要再次同步 {} ", entrustDataVo.getId());
                continue;//如果已经存在就不管了，进行下一条的同步
            }
            Map<String, List<Map<String, String>>> caseSaveRet = caseEventService.syncCaseEventInfo(entrustDataVo, null, false);
            log.info("插入案件成功 {} ", entrustDataVo.getId());
            //插入案件物证
            String caseID = caseSaveRet.entrySet().stream().findFirst().map(Map.Entry::getKey).get();
            List<Map<String, String>> evidToMaterial = caseSaveRet.entrySet().stream().findFirst().map(Map.Entry::getValue).get();
            log.info("插入物证成功 {} ", entrustDataVo.getId());
            //插入委托
            List<Integer> stDataList = getSynEntrustStatus(entrustDataVo.getStatus());
            Entrustment entrustmentForSave = addEntrustmentByOtherSys(entrustDataVo, caseID, "add", stDataList);
            log.info("插入委托成功 {} ", entrustDataVo.getId());
            //插入备用存储表
            this.addEntrustThirdSys(genThirdSysEntrustBean(entrustDataVo, entrustmentForSave.getId(), "add"));
            log.info("插入第三方委托成功 {} ", entrustDataVo.getId());
            List<MaterialVo> materialVos = entrustDataVo.getMaterialList();
            //插入检材
            for (MaterialVo materialVo : materialVos) {
                String materialIndex = materialVo.getIndex();
                //获取物证ID，根据索引
                String evidID = getEvidIdByIndex(materialIndex, evidToMaterial);
                //查出这个物证ID对应的物证编号
                CaseEvidence caseEvidence = caseEvidenceService.getById(evidID);
                String materialNo = entrustmentIdentificationMaterialService.getNewIdentificationMaterialNo(caseEvidence.getEvidenceNo());
                EntrustmentIdentificationMaterial selfEntrustmentIdentificationMaterial = addSampleByOtherSys(materialVo, entrustmentForSave, materialNo, caseID, evidID, entrustDataVo.getMaterialType());
                System.out.println("插入检材：" + materialVo.getName());
                log.info("插入委托的检材成功 检材名称:{} 检材ID:{}", materialVo.getName(), selfEntrustmentIdentificationMaterial.getId());
                materialVo.setEntrustId(entrustDataVo.getId());
                synchronizeMaterialVoService.addMaterialVoThirdSys(genThirdSysEntrustMaterialBean(materialVo, selfEntrustmentIdentificationMaterial.getId()));
                log.info("插入第三方委托的检材成功 检材名称:{} 检材ID:{}", materialVo.getName(), selfEntrustmentIdentificationMaterial.getId());
            }
        }
        return ret;
    }

    //从大数据平台同步已经受理的数据
    @Override
    public Boolean synAcceptedEntrustDataToMyServer(EntrustQueryParams queryParams) {
        Boolean ret = true;
        log.info("查询参数是:{}", queryParams);
        //DataModelVo dataModelVo=fetchDataFromRemote(entrustStatus);
        List<EntrustDataVo> entrustDataVoList = fetchAcceptedDataFromRemote(queryParams);
//        if (dataModelVo == null) {
//            log.info("远程获取数据失败，请检查网络及请求参数是否正常");
//            ret = false;
//            throw new RuntimeException("远程获取数据失败，请检查网络及请求参数是否正常");
//        }
//        List<EntrustDataVo> entrustDataVoList = dataModelVo.getResult().getList();//获取到的数据，分别处理这些数据
        log.info("从大数据平台获取到的数据量 {}", entrustDataVoList.size());
        return handelAcceptedStatusData(entrustDataVoList);
    }

    //同步已经受理的数据
    public List<EntrustDataVo> fetchAcceptedDataFromRemote(EntrustQueryParams entrustQueryParams) {
        SynConnInfoVo synConnInfoVo = getSysSynConnInfo();
        String token = getTokenInfo("SubCenter", synConnInfoVo);
        String remoteUrl = synConnInfoVo.getApiHost();
        String wtDataPath = synConnInfoVo.getDataPathInfo().getEntrustDataPath();
        //DataModelVo retDataModelVo= HttpsUtils.fetchWtDataFromRemote(remoteUrl,wtDataPath,token,wtStatus);
        ArrayList<EntrustDataVo> entrustDataVos = new ArrayList<>();
        for (int i = 0; ; i++) {
            entrustQueryParams.setPageIndex(i);
            entrustQueryParams.setPageSize(100);
            DataModelVo retDataModelVo = HttpsUtils.fetchAcceptedWtDataFromRemote(remoteUrl, wtDataPath, token, entrustQueryParams);
            log.info("remoteUrl ====== {}", remoteUrl);
            System.out.println("remoteUrl ===========================" + remoteUrl);
            int pageCount = retDataModelVo.getResult().getPageCount();
            log.info("总条数:"+pageCount);
            entrustDataVos.addAll(retDataModelVo.getResult().getList());
            if (i == 10) {
                break;
            }
            if (i >= pageCount - 1) {
                break;
            }
        }
//        DataModelVo retDataModelVo = HttpsUtils.fetchAcceptedWtDataFromRemote(remoteUrl, wtDataPath, token, entrustQueryParams);
//        int pageCount = retDataModelVo.getResult().getPageCount();
//        List<EntrustDataVo> list = retDataModelVo.getResult().getList();
//        if (pageCount > 1) {
//
//        }
        return entrustDataVos;
    }

    //同步已受理数据的处理
    private boolean handelAcceptedStatusData(List<EntrustDataVo> entrustDataVoList) {
        for (EntrustDataVo entrustDataVo : entrustDataVoList) {
            System.out.println("正在同步-------------------------------------------" + entrustDataVo.getId());
            //这里需要判断一下，是否之前同步过，如果同步过的话，我们就不用再同步
            if (isSynAcceptEntrust(entrustDataVo)) {
                //说明已经存在，不需要同步，但是如果我们系统中的状态不是已受理，那么就要进行更新，而且还要更新检材信息
                System.out.println("这个委托已经被通不过了，不需要再同步:" + entrustDataVo.getId());
                EntrustOfThirdSys thirdSys = this.getById(entrustDataVo.getId());
                Entrustment entrustment = entrustmentService.getById(thirdSys.getEntrustMainId());
                if (entrustment != null && !entrustment.getStatus().equals(EntrustmentStatusConstants.ENTRUSTMENT_STATUS_ACCEPTED.getStatus())) {
                    entrustmentIdentificationMaterialService.remove(Wrappers.<EntrustmentIdentificationMaterial>lambdaQuery().eq(EntrustmentIdentificationMaterial::getEntrustmentId, entrustment.getId()));
                    entrustmentService.removeById(entrustment);
                    synchronizeMaterialVoService.remove(Wrappers.<EntrustMaterialOfThirdSys>lambdaQuery().eq(EntrustMaterialOfThirdSys::getEntrustId, thirdSys.getId()));
                    this.removeById(thirdSys);
//                    entrustment.setStatus(EntrustmentStatusConstants.ENTRUSTMENT_STATUS_ACCEPTED.getStatus());
//                    entrustment.setAcceptNo(entrustDataVo.getSerialNumber());
//                    List<EntrustmentIdentificationMaterial> entrustmentIdentificationMaterialList = entrustmentIdentificationMaterialService.list(Wrappers.<EntrustmentIdentificationMaterial>lambdaQuery().eq(EntrustmentIdentificationMaterial::getEntrustmentId, entrustment.getId()));
//                    List<MaterialVo> materialList = entrustDataVo.getMaterialList();
//                    List<String> nameList = new ArrayList<>();
//                    materialList.forEach(item ->
//                            nameList.add(item.getName()));
//                    int index = 1;
//                    for (MaterialVo materialVo : materialList) {
//                        for (EntrustmentIdentificationMaterial entrustmentIdentificationMaterial : entrustmentIdentificationMaterialList) {
//                            if (entrustmentIdentificationMaterial.getName().equals(materialVo.getName())) {
//                                entrustmentIdentificationMaterial.setAcceptNo(entrustDataVo.getSerialNumber() + "-" + index);
//                                entrustmentIdentificationMaterial.setProvidedSample1Quantity(materialVo.getAnalysisSampleAmount());
//                                entrustmentIdentificationMaterial.setProvidedSample1FundQuantity(1);
//                                entrustmentIdentificationMaterial.setSample1Quantity(materialVo.getAnalysisSampleAmount());
//                                entrustmentIdentificationMaterial.setSample1FundQuantity(1);
//                                entrustmentIdentificationMaterial.setAcceptPassed(1);
//                                if (materialVo.getRetainedSampleAmount() != null && materialVo.getRetainedSampleAmount().compareTo(BigDecimal.ZERO) != 0) {
//                                    entrustmentIdentificationMaterial.setSample2Quantity(materialVo.getRetainedSampleAmount());
//                                    entrustmentIdentificationMaterial.setProvidedSample2Quantity(materialVo.getRetainedSampleAmount());
//                                }
//                                index++;
//                            }
//                        }
//                    }
//                    entrustmentIdentificationMaterialService.updateBatchById(entrustmentIdentificationMaterialList);
//                    entrustmentService.updateById(entrustment);
//                }
//                continue;
                } else {
                    continue;
                }
            }
            //插入案件，和之前逻辑一样，
            Map<String, List<Map<String, String>>> caseSaveRet = caseEventService.syncCaseEventInfo(entrustDataVo, null, false);
            //插入案件物证
            String caseID = caseSaveRet.entrySet().stream().findFirst().map(Map.Entry::getKey).get();
            List<Map<String, String>> evidToMaterial = caseSaveRet.entrySet().stream().findFirst().map(Map.Entry::getValue).get();
            //插入委托，比之前的信息多，因为要补录受理信息
            Entrustment entrustmentForSave = addEntrustmentOfAccepted(caseID, entrustDataVo);
            this.addEntrustThirdSys(genThirdSysEntrustBean(entrustDataVo, entrustmentForSave.getId(), "add"));

            //插入检材，比之前的信息多，因为要补录受理信息
            List<MaterialVo> materialVos = entrustDataVo.getMaterialList();
            for (MaterialVo materialVo : materialVos) {
                String materialIndex = materialVo.getIndex();
                //获取物证ID，根据索引
                String evidID = getEvidIdByIndex(materialIndex, evidToMaterial);
                //查出这个物证ID对应的物证编号
                CaseEvidence caseEvidence = caseEvidenceService.getById(evidID);
                String materialNo = entrustmentIdentificationMaterialService.getNewIdentificationMaterialNo(caseEvidence.getEvidenceNo());
                EntrustmentIdentificationMaterial selfEntrustmentIdentificationMaterial = addSampleByOtherSys(materialVo, entrustmentForSave, materialNo, caseID, evidID, entrustDataVo.getMaterialType());
                System.out.println("插入检材：" + materialVo.getName());
                materialVo.setEntrustId(entrustDataVo.getId());
                synchronizeMaterialVoService.addMaterialVoThirdSys(genThirdSysEntrustMaterialBean(materialVo, selfEntrustmentIdentificationMaterial.getId()));
            }
        }

        return false;
    }

    //判断已受理的委托是否已经被同步,返回true，已经同步  返回false，没有同步
    private Boolean isSynAcceptEntrust(EntrustDataVo entrustDataVo) {
        EntrustOfThirdSys entrustOfThirdSys = this.getById(entrustDataVo.getId());
        if (entrustOfThirdSys != null) {
            //说明已经存在，返回true
            return true;
        }
        return false;
    }

    //已受理委托的插入处理
    private Entrustment addEntrustmentOfAccepted(String caseID, EntrustDataVo entrustDataVo) {
        CaseEvent caseEvent = caseEventService.getById(caseID);
        Entrustment entrustment = new Entrustment();
        entrustment.setEntrustmentNo(entrustmentService.getNewEntrustNoByYear(entrustDataVo.getSerialYear() + ""));//设置委托编号
        entrustment.setId(IdWorker.get32UUID().toUpperCase());//设置系统编号
        entrustment.setDataSources(1);//设置数据来源，标识来自系统还是外部系统
        entrustment.setCaseId(caseID);//设置案件ID
        entrustment.setThirdSysEntrustNo(entrustDataVo.getEntrustSerialNumber());

        String materialType = entrustDataVo.getMaterialType();
        if (StringUtils.isNotBlank(materialType)) {
            if (materialType.equals("inVitro")) {
                entrustment.setEntrustmentType(0);
            } else if (materialType.equals("inVivo")) {
                entrustment.setEntrustmentType(1);
            } else {
                entrustment.setEntrustmentType(2);
            }
        }
        //设置候选人员
        setEntrustCheckCandidateUser(entrustment);


        entrustment.setIdentificationOrgName("国家毒品实验室陕西分中心");//设置鉴定机构
        entrustment.setClientOrgId(entrustDataVo.getCreateUserDeptRegionCode());//设置委托单位ID
        entrustment.setClientOrgName(entrustDataVo.getEntrustOrganization());//设置委托单位名称

        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime ldt = LocalDateTime.parse(entrustDataVo.getSubmitTime(), df);
        entrustment.setSubmitTime(ldt);//设置提交日期
        entrustment.setCreateTime(ldt);
        //entrustment.setCreateBy();
//        entrustment.setEntrustmentType(0);//设置委托类型  正常委托 0，案件 是 1  2024-3-20已更新：这个字段现在已经被用做检材类别了
        entrustment.setReportReceiveMode(ConvertUtils.reportSendType(entrustDataVo.getReportSendType()) + "");//confidentialDelivery:机要寄递, ems:邮政专递EMS（到付），takeFromOneself: 自取


        //设置送检人1
        DelivererVo delivererVo1 = entrustDataVo.getUserList().get(0);
        DelivererVo delivererVo2 = entrustDataVo.getUserList().get(1);

        entrustment.setDeliverer1Name(delivererVo1.getName());//姓名
        entrustment.setDeliverer1Position(delivererVo1.getPosition());//职务
        //证件名称   policeOfficerCard:警官证, identityCard:身份证, officerCard:军官证, workCard:工作证, passport:护照
        entrustment.setDeliverer1Cert(ConvertUtils.getCardTypeName(delivererVo1.getCardType()));
        entrustment.setDeliverer1Id(delivererVo1.getCertificatesCode());//证件编号
        //设置送检人2
        entrustment.setDeliverer2Name(delivererVo2.getName());//姓名
        entrustment.setDeliverer2Position(delivererVo2.getPosition());//职务
        entrustment.setDeliverer2Cert(ConvertUtils.getCardTypeName(delivererVo2.getCardType()));//证件名称
        entrustment.setDeliverer2Id(delivererVo2.getCertificatesCode());//证件编号
        //设置委托状态
        entrustment.setStatus(EntrustmentStatusConstants.ENTRUSTMENT_STATUS_ACCEPTED.getStatus());//设置为待审核
        entrustment.setPreviousStatus(EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_ACCEPT.getStatus());//
        entrustment.setIdentificationDomain("毒品检验");
        //补充受理信息
        entrustment.setAcceptNo(entrustDataVo.getSerialNumber());//我们自己的受理编号，
        entrustment.setAcceptNoThirdSys(entrustDataVo.getSerialNumber());//他们的受理编号
        LocalDateTime acceptDt = LocalDateTime.parse(entrustDataVo.getAcceptTime(), df);
        entrustment.setAcceptTime(acceptDt);
        entrustmentService.save(entrustment);
        return entrustment;
    }

    //退回逻辑的处理
    public void updateThirdSysData(EntrustDataVo entrustDataVo) {
        if (checkRollBackCondition(entrustDataVo.getId(), entrustDataVo.getEntrustSerialNumber())) {
            System.out.println("数据需要更新，开始执行更新操作");
            //符合更新逻辑
            EntrustOfThirdSys thirdEnObj = this.getById(entrustDataVo.getId());
            Entrustment _selfEntrust = entrustmentService.getById(thirdEnObj.getEntrustMainId());
            String caseID = _selfEntrust.getCaseId();
            Map<String, List<Map<String, String>>> caseUpdateRet = caseEventService.syncCaseEventInfo(entrustDataVo, caseID, true);
            //先更新委托
            List<Integer> stDataList = getSynEntrustStatus(entrustDataVo.getStatus());
            Entrustment entrustmentForUpdate = addEntrustmentByOtherSys(entrustDataVo, caseID, "update", stDataList);
            this.updateEntrustThirdSys(genThirdSysEntrustBean(entrustDataVo, entrustmentForUpdate.getId(), "update"));
            //再更新检材
            //更新之前，咱们把之前的检材先删除
            //删除本系统
            entrustmentIdentificationMaterialService.remove(Wrappers.<EntrustmentIdentificationMaterial>query()
                    .eq("entrustment_id", entrustmentForUpdate.getId()));
            //删除第三方系统的
            synchronizeMaterialVoService.remove(Wrappers.<EntrustMaterialOfThirdSys>query()
                    .eq("entrust_id", thirdEnObj.getId()));
            //删除后做插入
            List<Map<String, String>> evidToMaterial = caseUpdateRet.entrySet().stream().findFirst().map(Map.Entry::getValue).get();
            List<MaterialVo> materialVos = entrustDataVo.getMaterialList();
            //插入检材
            for (MaterialVo materialVo : materialVos) {
                String materialIndex = materialVo.getIndex();
                //获取物证ID，根据索引
                String evidID = getEvidIdByIndex(materialIndex, evidToMaterial);
                //查出这个物证ID对应的物证编号
                CaseEvidence caseEvidence = caseEvidenceService.getById(evidID);
                String materialNo = entrustmentIdentificationMaterialService.getNewIdentificationMaterialNo(caseEvidence.getEvidenceNo());
                EntrustmentIdentificationMaterial selfMaterial = addSampleByOtherSys(materialVo, entrustmentForUpdate, materialNo, caseID, evidID, entrustDataVo.getMaterialType());
                System.out.println("插入检材：" + materialVo.getName());
                materialVo.setEntrustId(thirdEnObj.getId());
                synchronizeMaterialVoService.addMaterialVoThirdSys(genThirdSysEntrustMaterialBean(materialVo, selfMaterial.getId()));
            }
        }
    }

    /**
     * 检查是否符合更新条件
     *
     * @param thirdEntrustID
     * @param targetEntrustNo
     * @return
     */
    public Boolean checkRollBackCondition(String thirdEntrustID, String targetEntrustNo) {
        List<EntrustOfThirdSys> retList = this.list(Wrappers.<EntrustOfThirdSys>query()
                .eq("id", thirdEntrustID)
                .eq("entrust_Serial_Number", targetEntrustNo));
        if (retList.size() > 0) {
            return false;//说明是同样的数据，不用处理
        } else {
            return true;
        }
    }


    @Override
    public void addEntrustThirdSys(EntrustOfThirdSys entrustOfThirdSys) {
        this.save(entrustOfThirdSys);
    }

    public void updateEntrustThirdSys(EntrustOfThirdSys entrustOfThirdSys) {
        this.updateById(entrustOfThirdSys);
    }

    //构建审核请求体
    public DataAuditBaseDto genProvinceAuditData(EntrustOfThirdSys entrustThirdSys, List<EntrustMaterialOfThirdSys> materialVoList,
                                                 String successFlag, String reMark, String auditOrAccept) {
        DataAuditBaseDto dataAuditBaseDto = new DataAuditBaseDto();
        dataAuditBaseDto.setResult(successFlag);
        if (!StringUtils.isBlank(reMark)) {
            dataAuditBaseDto.setRemark(reMark);
        } else {
            dataAuditBaseDto.setRemark("");
        }
        EntrustDataDto entrustDataDto = new EntrustDataDto();
        entrustDataDto.setId(entrustThirdSys.getId());
        entrustDataDto.setEntrustNumber(entrustThirdSys.getEntrustSerialNumber());
        entrustDataDto.setEntrustOrganization(entrustThirdSys.getEntrustOrganization());
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        entrustDataDto.setScheduledDate(entrustThirdSys.getScheduledDate() == null ? "" : entrustThirdSys.getScheduledDate().format(df));//预约日期
        entrustDataDto.setCaseName(entrustThirdSys.getCaseName());
        entrustDataDto.setCaseCode(entrustThirdSys.getCaseCode());
        entrustDataDto.setCaseRemark(entrustThirdSys.getCaseRemark());
        entrustDataDto.setMaterialType(entrustThirdSys.getMaterialType());
        entrustDataDto.setMaterialDescribe(entrustThirdSys.getMaterialDescribe());
        entrustDataDto.setEntrustRequirement(entrustThirdSys.getEntrustRequirement());
        entrustDataDto.setEntrustMethod(entrustThirdSys.getEntrustMethod());
        entrustDataDto.setOriginalIdentification(entrustThirdSys.getOriginalIdentification());//原鉴定情况
        entrustDataDto.setReportSendType(entrustThirdSys.getReportSendType());
        entrustDataDto.setReportSendAddress(StringUtils.isBlank(entrustThirdSys.getReportSendAddress()) ? " " : entrustThirdSys.getReportSendAddress());

        //如果是受理的时候，我们需要补充这个属性
        if (auditOrAccept.equals("Accept")) {
            entrustDataDto.setSamplingMethod(entrustThirdSys.getSamplingMethod());
        }
        //送检人信息
        DelivererVo delivererVo1 = new DelivererVo();
        delivererVo1.setName(entrustThirdSys.getDeliverer1Name());
        delivererVo1.setPosition(entrustThirdSys.getDeliverer1Position());
        delivererVo1.setCardType(entrustThirdSys.getDeliverer1CardType());
        delivererVo1.setCertificatesCode(entrustThirdSys.getDeliverer1CertificatesCode());
        delivererVo1.setPhone(entrustThirdSys.getDeliverer1Phone());
        DelivererVo delivererVo2 = new DelivererVo();
        delivererVo2.setName(entrustThirdSys.getDeliverer2Name());
        delivererVo2.setPosition(entrustThirdSys.getDeliverer2Position());
        delivererVo2.setCardType(entrustThirdSys.getDeliverer2CardType());
        delivererVo2.setCertificatesCode(entrustThirdSys.getDeliverer2CertificatesCode());
        delivererVo2.setPhone(entrustThirdSys.getDeliverer2Phone());
        List<DelivererVo> delivererVoList = new ArrayList<>();
        delivererVoList.add(delivererVo1);
        delivererVoList.add(delivererVo2);
        entrustDataDto.setUserList(delivererVoList);
        List<MaterialVo> materialVos = new ArrayList<>();
        //获取该委托对应的检材
        materialVoList.forEach(item -> {
            MaterialVo eg = new MaterialVo();
            eg.setIndex(item.getOrder_index());
            eg.setName(item.getName());
            eg.setColorType(item.getColorType());
            eg.setShapeType(item.getShapeType());
            eg.setPackageType(item.getPackageType());
            eg.setAmount(item.getAmount());
            eg.setUnit(item.getUnit());
            //JSONArray test=JSONObject.parseArray(item.getTargetObjectTypeList());
            List<String> tmp = JSONObject.parseArray(item.getTargetObjectTypeList(), String.class);
            eg.setTargetObjectTypeList(tmp);
            eg.setAnalysisType(item.getAnalysisType());
            eg.setAnalysisSampleAmount(item.getAnalysisSampleAmount());
            eg.setRetainedSampleAmount(item.getRetainedSampleAmount());
            eg.setTotalSampleAmount(item.getTotalSampleAmount());
            eg.setSampleUnit(item.getSampleUnit());
            materialVos.add(eg);
        });


        entrustDataDto.setMaterialList(materialVos);
        dataAuditBaseDto.setEntrust(entrustDataDto);
        return dataAuditBaseDto;
    }

    //
    public DataAuditBaseDto genSubCenterAcceptData(EntrustOfThirdSys entrustThirdSys, List<EntrustMaterialOfThirdSys> materialVoList, String samplingMethod) {
        DataAuditBaseDto dataAuditBaseDto = new DataAuditBaseDto();
        EntrustDataDto entrustDataDto = new EntrustDataDto();
        entrustDataDto.setId(entrustThirdSys.getId());
        entrustDataDto.setEntrustNumber(entrustThirdSys.getEntrustSerialNumber());
        entrustDataDto.setEntrustOrganization(entrustThirdSys.getEntrustOrganization());
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        entrustDataDto.setScheduledDate(entrustThirdSys.getScheduledDate() == null ? "" : entrustThirdSys.getScheduledDate().format(df));//预约日期
        entrustDataDto.setCaseName(entrustThirdSys.getCaseName());
        entrustDataDto.setCaseCode(entrustThirdSys.getCaseCode());
        entrustDataDto.setCaseRemark(entrustThirdSys.getCaseRemark());
        entrustDataDto.setMaterialType(entrustThirdSys.getMaterialType());
        entrustDataDto.setMaterialDescribe(entrustThirdSys.getMaterialDescribe());
        entrustDataDto.setEntrustRequirement(entrustThirdSys.getEntrustRequirement());
        entrustDataDto.setEntrustMethod(entrustThirdSys.getEntrustMethod());
        entrustDataDto.setOriginalIdentification(entrustThirdSys.getOriginalIdentification());//原鉴定情况
        entrustDataDto.setReportSendType(entrustThirdSys.getReportSendType());
        entrustDataDto.setReportSendAddress(StringUtils.isBlank(entrustThirdSys.getReportSendAddress()) ? " " : entrustThirdSys.getReportSendAddress());
        //如果是受理的时候，我们需要补充这个属性,这个属性可能是：1 全部为分析样，全部为留存，分装为分析样和留存样
        entrustDataDto.setSamplingMethod(samplingMethod);
        //送检人信息
        DelivererVo delivererVo1 = new DelivererVo();
        delivererVo1.setName(entrustThirdSys.getDeliverer1Name());
        delivererVo1.setPosition(entrustThirdSys.getDeliverer1Position());
        delivererVo1.setCardType(entrustThirdSys.getDeliverer1CardType());
        delivererVo1.setCertificatesCode(entrustThirdSys.getDeliverer1CertificatesCode());
        delivererVo1.setPhone(entrustThirdSys.getDeliverer1Phone());
        DelivererVo delivererVo2 = new DelivererVo();
        delivererVo2.setName(entrustThirdSys.getDeliverer2Name());
        delivererVo2.setPosition(entrustThirdSys.getDeliverer2Position());
        delivererVo2.setCardType(entrustThirdSys.getDeliverer2CardType());
        delivererVo2.setCertificatesCode(entrustThirdSys.getDeliverer2CertificatesCode());
        delivererVo2.setPhone(entrustThirdSys.getDeliverer2Phone());
        List<DelivererVo> delivererVoList = new ArrayList<>();
        delivererVoList.add(delivererVo1);
        delivererVoList.add(delivererVo2);
        entrustDataDto.setUserList(delivererVoList);
        List<MaterialVo> materialVos = new ArrayList<>();
        //获取该委托对应的检材
        materialVoList.forEach(item -> {
            MaterialVo eg = new MaterialVo();
            eg.setIndex(item.getOrder_index());
            eg.setName(item.getName());
            eg.setColorType(item.getColorType());
            eg.setShapeType(item.getShapeType());
            eg.setPackageType(item.getPackageType());
            eg.setAmount(item.getAmount());
            eg.setUnit(item.getUnit());
            //JSONArray test=JSONObject.parseArray(item.getTargetObjectTypeList());
            List<String> tmp = JSONObject.parseArray(item.getTargetObjectTypeList(), String.class);
            eg.setTargetObjectTypeList(tmp);
            eg.setAnalysisType(item.getAnalysisType());
            eg.setAnalysisSampleAmount(item.getAnalysisSampleAmount());
            eg.setRetainedSampleAmount(item.getRetainedSampleAmount());
            eg.setTotalSampleAmount(item.getTotalSampleAmount());
            eg.setSampleUnit(item.getSampleUnit());
            materialVos.add(eg);
        });


        entrustDataDto.setMaterialList(materialVos);
        dataAuditBaseDto.setEntrust(entrustDataDto);
        return dataAuditBaseDto;
    }

    //一些要用到的公共方法--------------------------------------------------------

    /**
     * 获取第三方系统中的配置参数
     *
     * @return 返回连接的数据结构对象
     */
    @Override
    public SynConnInfoVo getSysSynConnInfo() {
        final SynConnInfoVo synConnInfoVo = new SynConnInfoVo();
        String parentID = "920f9dd9cd14281e8b488a34c649ff70";
        List<Dictionary> retDataList = remoteDictionaryService.insideTreeData(parentID);
        List<Tree<String>> treeData = genTreeData(retDataList, parentID);
        if (treeData.size() > 0) {
            treeData.forEach(sourceObj -> {
                if (sourceObj.get("code").equals("tokenFetch"))//如果是token获取
                {
                    SynConnInfoTokenVo synConnInfoTokenVo = buildTokenInfo(sourceObj.getChildren());
                    synConnInfoVo.setProvinceTokenInfo(synConnInfoTokenVo.getProvinceTokenInfo());
                    synConnInfoVo.setSubCenterTokenInfo(synConnInfoTokenVo.getSubCenterTokenInfo());
                    synConnInfoVo.setTokenInfo(synConnInfoTokenVo);
                }
                if (sourceObj.get("code").equals("dataPath"))//如果是token获取
                {
                    SynConnInfoDataPathVo synConnInfoDataPathVo = buildDataPath(sourceObj.getChildren());
                    synConnInfoVo.setApiHost(synConnInfoDataPathVo.getApiHost());
                    synConnInfoVo.setDataPathInfo(synConnInfoDataPathVo);
                }
            });

        } else {
            System.out.println("没有获取到连接信息，请检查参数");
        }
        return synConnInfoVo;
    }

    /**
     * 构造token对象信息
     *
     * @param tokenAbout
     * @return
     */
    public SynConnInfoTokenVo buildTokenInfo(List<Tree<String>> tokenAbout) {
        SynConnInfoTokenVo synConnInfoTokenVo = new SynConnInfoTokenVo();
        tokenAbout.forEach(itemObj -> {
            String retKey = itemObj.get("label").toString();
            String retValue = itemObj.get("code").toString();
            String keyID = itemObj.get("id").toString();
            switch (retKey) {
                case "sx_sub_center_token":
                    synConnInfoTokenVo.setSubCenterTokenInfo(retValue);
                    synConnInfoTokenVo.setSubCenterTokenID(keyID);
                    break;
                case "sx_province_token":
                    synConnInfoTokenVo.setProvinceTokenInfo(retValue);
                    synConnInfoTokenVo.setProvinceTokenID(keyID);
                    break;
                case "accessKey":
                    synConnInfoTokenVo.setAccessSubCenterKey(retValue);
                    break;
                case "accessSecret":
                    synConnInfoTokenVo.setAccessSubCenterSecret(retValue);
                    break;
                case "accessProvinceKey":
                    synConnInfoTokenVo.setAccessProvinceKey(retValue);
                    break;
                case "accessProvinceSecret":
                    synConnInfoTokenVo.setAccessProvinceSecret(retValue);
                    break;
            }
        });
        return synConnInfoTokenVo;
    }
    //

    /**
     * 构建数据路径信息
     *
     * @param dataPathAbout
     * @return
     */
    public SynConnInfoDataPathVo buildDataPath(List<Tree<String>> dataPathAbout) {
        SynConnInfoDataPathVo synConnInfoDataPathVo = new SynConnInfoDataPathVo();
        dataPathAbout.forEach(itemObj -> {
            String retKey = itemObj.get("label").toString();
            String retValue = itemObj.get("code").toString();
            switch (retKey) {
                case "ApiHost":
                    synConnInfoDataPathVo.setApiHost(retValue);
                    break;
                case "tokenPath":
                    synConnInfoDataPathVo.setTokenPath(retValue);
                    break;
                case "entrustDataPath":
                    synConnInfoDataPathVo.setEntrustDataPath(retValue);
                    break;
                case "wtsStatus":
                    synConnInfoDataPathVo.setWtsStatus(retValue);
                    break;
                case "uploadSewageJobDataPath":
                    synConnInfoDataPathVo.setUploadSewageJobDataUrl(retValue);
                    break;
                case "province_audit_url":
                    synConnInfoDataPathVo.setProvinceAuditUrl(retValue);
                    break;
                case "sx_subcenter_audit_url":
                    synConnInfoDataPathVo.setSxSubCenterAuditUrl(retValue);
                    break;
                case "sx_subcenter_accept_url":
                    synConnInfoDataPathVo.setSxSubCenterAcceptUrl(retValue);
                    break;
            }
        });
        return synConnInfoDataPathVo;
    }

    /**
     * 检查委托数据是否已经同步过了
     *
     * @param entrustID
     * @return true 表示同步过了，false 表示没有同步
     */
    public Boolean checkExistEntrust(String entrustID) {
        List<EntrustOfThirdSys> entrustOfThirdSys = this.list(Wrappers.<EntrustOfThirdSys>query().eq("id", entrustID));
        if (entrustOfThirdSys.size() > 0) {
            return true;//存在
        } else {
            return false;//不存在
        }
    }

    //
    //构造一个第三方的委托数据
    public EntrustOfThirdSys genThirdSysEntrustBean(EntrustDataVo entrustDataVo, String entrustMainId, String optFlag) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        EntrustOfThirdSys targetBean = new EntrustOfThirdSys();
        if (optFlag.equals("add")) {
            targetBean.setEntrustMainId(entrustMainId);//主ID
            targetBean.setId(entrustDataVo.getId());
        } else {
            targetBean = this.getById(entrustDataVo.getId());
        }

        targetBean.setEntrustSerialNumber(entrustDataVo.getEntrustSerialNumber());
        targetBean.setStatus(entrustDataVo.getStatus());

        targetBean.setSubmitTime(StringUtils.isBlank(entrustDataVo.getSubmitTime()) ? null : LocalDateTime.parse(entrustDataVo.getSubmitTime(), df));
        targetBean.setAcceptTime(StringUtils.isBlank(entrustDataVo.getAcceptTime()) ? null : LocalDateTime.parse(entrustDataVo.getAcceptTime(), df));
        targetBean.setFinishTime(StringUtils.isBlank(entrustDataVo.getFinishTime()) ? null : LocalDateTime.parse(entrustDataVo.getFinishTime(), df));
        targetBean.setScheduledDate(StringUtils.isBlank(entrustDataVo.getScheduledDate()) ? null : LocalDateTime.parse(entrustDataVo.getScheduledDate() + " 00:00:00", df));
        targetBean.setAnalysisStartTime(StringUtils.isBlank(entrustDataVo.getAnalysisStartTime()) ? null : LocalDateTime.parse(entrustDataVo.getAnalysisStartTime(), df));
        targetBean.setAnalysisEndTime(StringUtils.isBlank(entrustDataVo.getAnalysisEndTime()) ? null : LocalDateTime.parse(entrustDataVo.getAnalysisEndTime(), df));

        targetBean.setEntrustOrganization(entrustDataVo.getEntrustOrganization());
        targetBean.setCreateUserDeptRegionCode(entrustDataVo.getCreateUserDeptRegionCode());
        targetBean.setCaseName(entrustDataVo.getCaseName());
        targetBean.setCaseCode(entrustDataVo.getCaseCode());
        targetBean.setCaseRemark(entrustDataVo.getCaseRemark());
        targetBean.setMaterialType(entrustDataVo.getMaterialType());
        targetBean.setMaterialDescribe(entrustDataVo.getMaterialDescribe());
        targetBean.setEntrustRequirement(entrustDataVo.getEntrustRequirement());
        targetBean.setEntrustMethod(entrustDataVo.getEntrustMethod());
        targetBean.setOriginalIdentification(entrustDataVo.getOriginalIdentification());
        targetBean.setReportSendType(entrustDataVo.getReportSendType());
        targetBean.setReportSendAddress(entrustDataVo.getReportSendAddress());

        DelivererVo delivererVo1 = entrustDataVo.getUserList().get(0);
        DelivererVo delivererVo2 = entrustDataVo.getUserList().get(1);
        targetBean.setDeliverer1Name(delivererVo1.getName());
        targetBean.setDeliverer1Position(delivererVo1.getPosition());
        targetBean.setDeliverer1CardType(delivererVo1.getCardType());
        targetBean.setDeliverer1CertificatesCode(delivererVo1.getCertificatesCode());
        targetBean.setDeliverer1Phone(delivererVo1.getPhone());

        targetBean.setDeliverer2Name(delivererVo2.getName());
        targetBean.setDeliverer2Position(delivererVo2.getPosition());
        targetBean.setDeliverer2CardType(delivererVo2.getCardType());
        targetBean.setDeliverer2CertificatesCode(delivererVo2.getCertificatesCode());
        targetBean.setDeliverer2Phone(delivererVo2.getPhone());

        //补充字段
        targetBean.setAcceptSerialNumber(entrustDataVo.getAcceptSerialNumber());
        targetBean.setSerialYear(entrustDataVo.getSerialYear());
        targetBean.setSerialIndex(entrustDataVo.getSerialIndex());
        targetBean.setSerialNumber(entrustDataVo.getSerialNumber());
        targetBean.setProvinceCode(entrustDataVo.getProvinceCode());
        targetBean.setProvinceName(entrustDataVo.getProvinceName());
        targetBean.setProvinceDeptName(entrustDataVo.getProvinceDeptName());
        return targetBean;
    }

    //构造第三方检材数据
    public EntrustMaterialOfThirdSys genThirdSysEntrustMaterialBean(MaterialVo materialVo, String localMaterialId) {
        EntrustMaterialOfThirdSys retBean = new EntrustMaterialOfThirdSys();
        //retBean.setId(IdWorker.get32UUID());
        retBean.setId(localMaterialId);//使用我们系统的检材ID
        retBean.setEntrustId(materialVo.getEntrustId());
        retBean.setOrder_index(materialVo.getIndex());
        retBean.setName(materialVo.getName());
        retBean.setColorType(materialVo.getColorType());
        retBean.setShapeType(materialVo.getShapeType());
        retBean.setPackageType(materialVo.getPackageType());
        retBean.setAmount(materialVo.getAmount());
        retBean.setUnit(materialVo.getUnit());
        retBean.setAnalysisType(materialVo.getAnalysisType());
        retBean.setTargetObjectTypeList(JSON.toJSONString(materialVo.getTargetObjectTypeList()));

        retBean.setAnalysisSampleAmount(materialVo.getAnalysisSampleAmount());
        retBean.setRetainedSampleAmount(materialVo.getRetainedSampleAmount());
        retBean.setTotalSampleAmount(materialVo.getTotalSampleAmount());
        retBean.setSampleUnit(materialVo.getSampleUnit());
        return retBean;
    }

    //根据数组返回一个树形结构
    public List<Tree<String>> genTreeData(List<Dictionary> dictionaryList, String parentID) {
        List<TreeNode<String>> collect = dictionaryList
                .stream()
                .map(getNodeFunction()).collect(Collectors.toList());
        return TreeUtil.build(collect, parentID);
    }

    //构造树形节点数据
    private Function<Dictionary, TreeNode<String>> getNodeFunction() {
        return dictionary -> {
            TreeNode<String> node = new TreeNode<>();
            node.setId(dictionary.getId());
            node.setParentId(dictionary.getType());
            node.setName(dictionary.getLabel());
            // 扩展属性
            Map<String, Object> extra = new HashMap<>();
            extra.put("type", dictionary.getType());
            extra.put("sort", dictionary.getSort());
            extra.put("code", dictionary.getCode());
            extra.put("label", dictionary.getLabel());
            extra.put("comments", dictionary.getComments());
            node.setExtra(extra);
            return node;
        };
    }

    /**
     * 根据禁毒系统中的检材序号，查出同步到我们系统中的物证ID
     *
     * @param index
     * @param evidIdList
     * @return
     */
    public String getEvidIdByIndex(String index, List<Map<String, String>> evidIdList) {

        String retEvid = "";
        for (Map<String, String> mp : evidIdList) {
            String evidIndex = mp.entrySet().stream().findFirst().map(Map.Entry::getKey).get();
            if (evidIndex.equals(index)) {
                if (retEvid.length() > 0) {
                    System.out.println("注意：出现重复的物证ID----------------");
                }
                retEvid = mp.entrySet().stream().findFirst().map(Map.Entry::getValue).get();
            }
        }
        return retEvid;
    }

    /**
     * 根据label和type 查到code
     *
     * @param dictLabel
     * @param parentType
     * @return
     */
    public String getDictCode(String dictLabel, String parentType) {
        String source = "";
        R sourceR = remoteDictionaryService.queryDictionaryVO(dictLabel, parentType);
        if (sourceR.getCode() == CommonConstants.SUCCESS) {
            source = (String) sourceR.getData();
        }
        return source;
    }

    /**
     * 根据同步的数据，构造一个委托对象，方便插入数据库
     *
     * @param entrustDataVo
     * @param caseID
     * @return
     */
    public Entrustment addEntrustmentByOtherSys(EntrustDataVo entrustDataVo, String caseID, String optFlag, List<Integer> setEntrustStatusValue) {
        Entrustment entrustment = null;
        if (optFlag.equals("add")) {
            CaseEvent caseEvent = caseEventService.getById(caseID);
            entrustment = new Entrustment();
            //entrustment.setEntrustmentNo(entrustmentService.getNewEntrustmentNo(caseEvent.getCaseNo()));//设置委托编号
            entrustment.setEntrustmentNo(entrustmentService.getNewEntrustmentNo());//设置委托编号

            entrustment.setId(IdWorker.get32UUID().toUpperCase());//设置系统编号
            entrustment.setDataSources(1);//设置数据来源，标识来自系统还是外部系统
            entrustment.setCaseId(caseID);//设置案件ID

        } else {
            EntrustOfThirdSys entrustOfThirdSys = this.getBaseMapper().selectOne(Wrappers.<EntrustOfThirdSys>query()
                    .eq("id", entrustDataVo.getId()));
            entrustment = entrustmentService.getById(entrustOfThirdSys.getEntrustMainId());
        }

        entrustment.setThirdSysEntrustNo(entrustDataVo.getEntrustSerialNumber());
        //设置审核候选人员
        setEntrustCheckCandidateUser(entrustment);
        //设置审批候选人员, 也就是受理审核的时候，才设置审批候选人
        if (entrustDataVo.getStatus().equals("acceptAuditing")) {
            List<SysUser> approveUsers = commonFeignService.remoteGetUsersByPermission(CommonConstants.ORG_TREE_ROOT_ID, CollUtil.newArrayList("EntrustmentApprove"));
            String approveCandidateUser = "";
            for (SysUser u : approveUsers) {
                if (approveCandidateUser.length() > 0) {
                    approveCandidateUser += ",";
                }
                approveCandidateUser += u.getUserId();
            }
            entrustment.setApproveCandidateUser(approveCandidateUser);
        }
        entrustment.setIdentificationOrgName("国家毒品实验室陕西分中心");//设置鉴定机构
        entrustment.setClientOrgId(entrustDataVo.getCreateUserDeptRegionCode());//设置委托单位ID
        entrustment.setClientOrgName(entrustDataVo.getEntrustOrganization());//设置委托单位名称

        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime ldt = LocalDateTime.parse(entrustDataVo.getSubmitTime(), df);
        entrustment.setSubmitTime(ldt);//设置提交日期
        entrustment.setCreateTime(ldt);

        String materialType = entrustDataVo.getMaterialType();
        if (StringUtils.isNotBlank(materialType)) {
            if (materialType.equals("inVitro")) {
                entrustment.setEntrustmentType(0);
            } else if (materialType.equals("inVivo")) {
                entrustment.setEntrustmentType(1);
            } else {
                entrustment.setEntrustmentType(2);
            }
        }
        //entrustment.setCreateBy();
//        entrustment.setEntrustmentType(0);//设置委托类型  正常委托 0，案件 是 1 2024-3-20已更新：这个字段现在已经被用做检材类别了
        entrustment.setReportReceiveMode(ConvertUtils.reportSendType(entrustDataVo.getReportSendType()) + "");//confidentialDelivery:机要寄递, ems:邮政专递EMS（到付），takeFromOneself: 自取


        //设置送检人1
        DelivererVo delivererVo1 = entrustDataVo.getUserList().get(0);
        DelivererVo delivererVo2 = entrustDataVo.getUserList().get(1);

        entrustment.setDeliverer1Name(delivererVo1.getName());//姓名
        entrustment.setDeliverer1Position(delivererVo1.getPosition());//职务
        entrustment.setDeliverer1Phone(delivererVo1.getPhone());//电话
        //证件名称   policeOfficerCard:警官证, identityCard:身份证, officerCard:军官证, workCard:工作证, passport:护照
        entrustment.setDeliverer1Cert(ConvertUtils.getCardTypeName(delivererVo1.getCardType()));
        entrustment.setDeliverer1Id(delivererVo1.getCertificatesCode());//证件编号
        //设置送检人2
        entrustment.setDeliverer2Name(delivererVo2.getName());//姓名
        entrustment.setDeliverer2Position(delivererVo2.getPosition());//职务
        entrustment.setDeliverer2Cert(ConvertUtils.getCardTypeName(delivererVo2.getCardType()));//证件名称
        entrustment.setDeliverer2Id(delivererVo2.getCertificatesCode());//证件编号
        entrustment.setDeliverer2Phone(delivererVo2.getPhone());//电话
        //设置委托鉴定要求
        entrustment.setEntrustRequirement(entrustDataVo.getEntrustRequirement());
        //设置邮寄地址
        entrustment.setPostAddress(entrustDataVo.getReportSendAddress());
        //设置原鉴定情况
        entrustment.setOldIdentificationResult(entrustDataVo.getOriginalIdentification());
        //设置委托状态
        //这里应根据情况，如果是省级审核   如果是受理审核， 如果是已受理
        //entrustment.setStatus(EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_CHECK_CLAIM.getStatus());//设置为待审核
        //entrustment.setPreviousStatus(EntrustmentStatusConstants.ENTRUSTMENT_STATUS_CREATED.getStatus());//
        entrustment.setStatus(setEntrustStatusValue.get(0));//设置为待审核
        entrustment.setPreviousStatus(setEntrustStatusValue.get(1));//

        entrustment.setIdentificationDomain("毒品检验");
        if (optFlag.equals("add")) {
            entrustmentService.save(entrustment);
        } else {
            entrustmentService.updateById(entrustment);
        }
        return entrustment;
    }

    //设置候选人员
    private void setEntrustCheckCandidateUser(Entrustment entrustment) {
        List<SysUser> users = commonFeignService.remoteGetUsersByPermission(CommonConstants.ORG_TREE_ROOT_ID, CollUtil.newArrayList("EntrustmentCheck"));
        String candidateUser = "";
        for (SysUser u : users) {
            if (candidateUser.length() > 0) {
                candidateUser += ",";
            }
            candidateUser += u.getUserId();
        }
        entrustment.setCheckCandidateUser(candidateUser);
    }

    //设置委托书状态
    private List<Integer> getSynEntrustStatus(String statusStr) {
        List<Integer> statusList = new ArrayList<>();
        switch (statusStr) {
            case "provinceAuditing":
                statusList.add(EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_CHECK_CLAIM.getStatus());//1
                statusList.add(EntrustmentStatusConstants.ENTRUSTMENT_STATUS_CREATED.getStatus());//0
                break;
            case "acceptAuditing":
                statusList.add(EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_APPROVE_CLAIM.getStatus());//3
                statusList.add(EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_CHECK.getStatus());//2
                break;
            case "toAccept":
                statusList.add(EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_ACCEPT.getStatus());//7
                statusList.add(EntrustmentStatusConstants.ENTRUSTMENT_STATUS_WAITING_DELIVER.getStatus());//6
                break;
        }
        return statusList;
    }

    /**
     * 构造一个检材，并插入到数据库中
     *
     * @param materialVo
     * @param entrustment
     * @param caseID
     * @param evidenceID
     * @param materialType
     * @return
     */
    public EntrustmentIdentificationMaterial addSampleByOtherSys(MaterialVo materialVo, Entrustment entrustment, String materilaNo, String caseID, String evidenceID, String materialType) {
//        if(entrustment.getAcceptNo().equals("2023-0003")){
//            System.out.println("命中---------------------");
//        }
        EntrustmentIdentificationMaterial entrustmentIdentificationMaterial = new EntrustmentIdentificationMaterial();
        //设置ID
        entrustmentIdentificationMaterial.setId(IdWorker.get32UUID().toUpperCase());
        //设置委托ID
        entrustmentIdentificationMaterial.setEntrustmentId(entrustment.getId());
        //设置案件ID
        entrustmentIdentificationMaterial.setCaseId(caseID);
        //设置物证ID
        entrustmentIdentificationMaterial.setEvidenceId(evidenceID);
        //检材名称
        entrustmentIdentificationMaterial.setName(materialVo.getName());
        //颜色
        entrustmentIdentificationMaterial.setColor(materialVo.getColorType());

        //设置检材编号
        entrustmentIdentificationMaterial.setImNo(materilaNo);
        entrustmentIdentificationMaterial.setSample1No(materilaNo);
        entrustmentIdentificationMaterial.setProvidedSample1No(materilaNo);

        //检材类型
        //entrustmentIdentificationMaterial.setType(getDictCode(ConvertUtils.getCaseEvidenceSource(materialType),"WZFL.1.6"));
        entrustmentIdentificationMaterial.setType(getDictCode(ConvertUtils.getCaseEvidenceSource(materialType), "6f4b55454a3ccde502493e04f63eed32"));

        entrustmentIdentificationMaterial.setTypeName(ConvertUtils.getCaseEvidenceSource(materialType));
        //形态

        //entrustmentIdentificationMaterial.setForm(getDictCode(materialVo.getShapeType(),"wzxz.11"));
        entrustmentIdentificationMaterial.setForm(getDictCode(materialVo.getShapeType(), "cdb0ca92f0d9c8f6af12457f8f924f21"));

        entrustmentIdentificationMaterial.setFormName(materialVo.getShapeType());
        //目标物✽
        //List<DrugLite> drugLites=new ArrayList<DrugLite>();
        //这里我们需要将毒品筛查目标物做一个转换，专门写一个转换函数
        entrustmentIdentificationMaterial.setCandidateDrugs(getDrugLiteList(materialVo));
        //分析项目
        entrustmentIdentificationMaterial.setAnalysisOption(ConvertUtils.getAnalysisName(materialVo.getAnalysisType()));
        //包装
        //entrustmentIdentificationMaterial.setPack(getDictCode(materialVo.getPackageType(),"BZFL.08"));
        entrustmentIdentificationMaterial.setPack(getDictCode(materialVo.getPackageType(), "56e4dda4300f99ae147c0c72d03f9488"));
        entrustmentIdentificationMaterial.setPackName(materialVo.getPackageType());//名称
        //处理承载物信息
        entrustmentIdentificationMaterial.setFundName(materialVo.getPackageType());
        entrustmentIdentificationMaterial.setFundQuantity(1);
        entrustmentIdentificationMaterial.setFundUnit(ConvertUtils.getFundUnit(materialVo.getPackageType()));
        //设置序号
        entrustmentIdentificationMaterial.setOrderNo(Integer.parseInt(materialVo.getIndex()));
        //检材的描述
        String materialUnit = ConvertUtils.getMaterialUnit(materialVo);
        BigDecimal materialMount = ConvertUtils.getMaterialMount(materialVo);
        String materialDes = materialVo.getColorType() + materialVo.getShapeType() + materialMount +
                ConvertUtils.getCaseEvidenceUnit(materialUnit) + "," + materialVo.getPackageType() + "包装";
        entrustmentIdentificationMaterial.setDescription(materialDes);


        //如果计量单位不是克，那么我们就将其质量设置为-1，方便客户端显示为 未称量  以前的逻辑
        // 11-27日修改：我们保留从大数据平台同步过来的检材单位与质量的信息，不对其进行二次处理了，也不需要在称量时计算质量差值
        if (ConvertUtils.getCaseEvidenceUnit(materialUnit).equals("克") || ConvertUtils.getCaseEvidenceUnit(materialUnit).equals("毫克")) {
            //提取数量
            entrustmentIdentificationMaterial.setQuantity(materialMount);
            //单位
            entrustmentIdentificationMaterial.setUnit(ConvertUtils.getCaseEvidenceUnit(materialUnit));
            //设置样本1的重量
            entrustmentIdentificationMaterial.setProvidedSample1Quantity(materialMount);
            entrustmentIdentificationMaterial.setProvidedSample1FundQuantity(1);
            entrustmentIdentificationMaterial.setSample1Quantity(materialMount);//必然存在一个样本
            entrustmentIdentificationMaterial.setSample1FundQuantity(1);

        } else {
            //提取数量
            entrustmentIdentificationMaterial.setQuantity(materialMount);
            //单位
            entrustmentIdentificationMaterial.setUnit(ConvertUtils.getCaseEvidenceUnit(materialUnit));
            //设置样本1的重量
            entrustmentIdentificationMaterial.setProvidedSample1Quantity(materialMount);
            entrustmentIdentificationMaterial.setProvidedSample1FundQuantity(1);
            entrustmentIdentificationMaterial.setSample1Quantity(materialMount);//必然存在一个样本
            entrustmentIdentificationMaterial.setSample1FundQuantity(1);

            //同时将其计量方式填入附加属性
            String propertyName = entrustmentIdentificationMaterial.getTypeName();
            //BigDecimal quantity=materialVo.getAmount();
            //String unit=ConvertUtils.getCaseEvidenceUnit(materialUnit);

            IMAdditionalProperty eg = new IMAdditionalProperty(propertyName, materialMount + "", materialUnit);
            List<IMAdditionalProperty> addPros = new ArrayList<>();
            addPros.add(eg);
            entrustmentIdentificationMaterial.setAdditionalProperties(addPros);
        }
        //设置存储类型
        entrustmentIdentificationMaterial.setStorageMethod("常规");
        entrustmentIdentificationMaterial.setDrawWay("转移");
        entrustmentIdentificationMaterial.setDataSources(1);//设置数据是来自何处
        //受理时候的属性
        if (StringUtils.isNotBlank(entrustment.getAcceptNo())) {
            entrustmentIdentificationMaterial.setSample1Quantity(materialVo.getAnalysisSampleAmount());
            entrustmentIdentificationMaterial.setSample2Quantity(materialVo.getRetainedSampleAmount());
            entrustmentIdentificationMaterial.setSample1RepeatWeigh(materialVo.getAnalysisSampleAmount());
            entrustmentIdentificationMaterial.setSample2RepeatWeigh(materialVo.getRetainedSampleAmount());
            String acceptNo = entrustmentIdentificationMaterialService.getNewMaterialAcceptNo(entrustment.getAcceptNo());
            System.out.println("设置检材的受理编号：" + acceptNo);
            entrustmentIdentificationMaterial.setAcceptNo(acceptNo);
            entrustmentIdentificationMaterial.setAcceptPassed(1);
            entrustmentIdentificationMaterial.setAcceptTime(entrustment.getAcceptTime());
        }
        entrustmentIdentificationMaterialService.save(entrustmentIdentificationMaterial);
        return entrustmentIdentificationMaterial;
    }

    /**
     * 获取token 并更新字典
     *
     * @param remoteUrl
     * @param tokenPath
     * @param accessKey
     * @param accessSecret
     * @param tokenDictID
     * @return
     */
    public String getTokenAndUpdate(String remoteUrl, String tokenPath, String accessKey, String accessSecret, String tokenDictID) {
        String retToken = "";
        Dictionary dictToken = remoteDictionaryService.getDictByID(tokenDictID);
        DataModelVo dataModelVoTmp = HttpsUtils.fetchTokenFromRemote(remoteUrl, tokenPath, accessKey, accessSecret);
        if (dataModelVoTmp.getStatusCode().equals("SUCCESS")) {
            retToken = dataModelVoTmp.getResult().getToken();
            System.out.println("重新申请第三方的数据token成功--");
            //将token 存储起来
            dictToken.setCode(retToken);
            remoteDictionaryService.updateById(dictToken);
            System.out.println("更新第三方数据token成功--");
        } else {
            System.out.println("获取第三方token失败，请检查网络或参数");
        }
        return retToken;
    }

    /**
     * 根据参数不同，获取访问单位的token
     *
     * @param whoUse
     * @return
     */
    @Override
    public String getTokenInfo(String whoUse, SynConnInfoVo synConnInfoVo) {
        String retToken = "";
        String accCheckTokenPath = "/api/sample/drug/task";
        //如果是分中心申请
        if (whoUse.equals("SubCenter")) {

            DataModelVo retData = HttpsUtils.checkTokenValid(synConnInfoVo.getApiHost(), accCheckTokenPath, synConnInfoVo.getSubCenterTokenInfo());
            if (retData.getStatusCode().equals("UNAUTHORIZED")) {
                //已经过期
                retToken = getTokenAndUpdate(synConnInfoVo.getApiHost(), synConnInfoVo.getDataPathInfo().getTokenPath(),
                        synConnInfoVo.getTokenInfo().getAccessSubCenterKey().trim(), synConnInfoVo.getTokenInfo().getAccessSubCenterSecret().trim(),
                        synConnInfoVo.getTokenInfo().getSubCenterTokenID());
            } else {
                retToken = synConnInfoVo.getSubCenterTokenInfo();
            }

        } else {
            //否则就认为是省总队申请
            DataModelVo retData = HttpsUtils.checkTokenValid(synConnInfoVo.getApiHost(), accCheckTokenPath, synConnInfoVo.getProvinceTokenInfo());
            if (retData.getStatusCode().equals("UNAUTHORIZED")) {
                //已经过期
                retToken = getTokenAndUpdate(synConnInfoVo.getApiHost(), synConnInfoVo.getDataPathInfo().getTokenPath(),
                        synConnInfoVo.getTokenInfo().getAccessProvinceKey().trim(), synConnInfoVo.getTokenInfo().getAccessProvinceSecret().trim(),
                        synConnInfoVo.getTokenInfo().getProvinceTokenID());
            } else {
                retToken = synConnInfoVo.getProvinceTokenInfo();
            }
        }
        return retToken;
    }

    /**
     * 获取远程系统中的数据
     *
     * @return DataModelVo  远程系统中获取到的数据对象
     */
    public DataModelVo fetchDataFromRemote(String entrustStatus) {
        SynConnInfoVo synConnInfoVo = getSysSynConnInfo();
        String token = getTokenInfo("SubCenter", synConnInfoVo);
        String remoteUrl = synConnInfoVo.getApiHost();
        String wtDataPath = synConnInfoVo.getDataPathInfo().getEntrustDataPath();
        String wtStatus = entrustStatus;//synConnInfoVo.getDataPathInfo().getWtsStatus();
        DataModelVo retDataModelVo = HttpsUtils.fetchWtDataFromRemote(remoteUrl, wtDataPath, token, wtStatus);
        return retDataModelVo;
    }

    @Override
    public EntrustOfThirdSys getThirdSysEntrustByMainId(String entrustMainId) {
        List<EntrustOfThirdSys> entrustOfThirdSysList = this.list(Wrappers.<EntrustOfThirdSys>query()
                .eq("entrust_main_id", entrustMainId));
        if (entrustOfThirdSysList.size() > 0) {
            return entrustOfThirdSysList.get(0);
        } else {
            return null;
        }
    }

    //毒品筛查目标物转换函数
    private List<DrugLite> getDrugLiteList(MaterialVo materialVo) {
        List<DrugLite> retDruglist = new ArrayList<>();
        List<String> dta1 = materialVo.getTargetObjectTypeList();
        dta1.forEach(item -> {
            DrugLite eg = new DrugLite();
            eg.setCode(item);
            eg.setAlias(item);
            eg.setName(item);
            retDruglist.add(eg);
        });
        return retDruglist;
    }
}
