package com.ningdatech.pmapi.expert.manage;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ningdatech.basic.exception.BizException;
import com.ningdatech.basic.model.PageVo;
import com.ningdatech.basic.util.CollUtils;
import com.ningdatech.pmapi.common.enumeration.BoolDisplayEnum;
import com.ningdatech.pmapi.common.helper.RegionCacheHelper;
import com.ningdatech.pmapi.common.helper.RegionLimitHelper;
import com.ningdatech.pmapi.common.helper.UserInfoHelper;
import com.ningdatech.pmapi.common.util.BizUtils;
import com.ningdatech.pmapi.expert.assembler.RegionWrapperAssembler;
import com.ningdatech.pmapi.expert.constant.ExpertApplyStatusEnum;
import com.ningdatech.pmapi.expert.constant.ExpertApplyTypeEnum;
import com.ningdatech.pmapi.expert.constant.ExpertApplyTypeQueryEnum;
import com.ningdatech.pmapi.expert.entity.ExpertMetaApply;
import com.ningdatech.pmapi.expert.entity.ExpertUserFullInfo;
import com.ningdatech.pmapi.expert.model.DictionaryFieldInfo;
import com.ningdatech.pmapi.expert.model.TagFieldInfo;
import com.ningdatech.pmapi.expert.model.cmd.ExpertAdminExpertManageQueryCmd;
import com.ningdatech.pmapi.expert.model.cmd.ExpertStorageDealCmd;
import com.ningdatech.pmapi.expert.model.cmd.MetaApplyListQuery;
import com.ningdatech.pmapi.expert.model.dto.ExpertDictionaryDTO;
import com.ningdatech.pmapi.expert.model.dto.ExpertTagDTO;
import com.ningdatech.pmapi.expert.model.query.ExpertDictionaryQuery;
import com.ningdatech.pmapi.expert.model.req.MetaApplyResultRequest;
import com.ningdatech.pmapi.expert.model.vo.ExpertApplyMetaVO;
import com.ningdatech.pmapi.expert.model.vo.MetaApplyResultVo;
import com.ningdatech.pmapi.expert.service.ExpertInfoService;
import com.ningdatech.pmapi.expert.service.IExpertMetaApplyService;
import com.ningdatech.pmapi.expert.service.IExpertUserFullInfoService;
import com.ningdatech.pmapi.meta.constant.DictExpertInfoTypeEnum;
import com.ningdatech.pmapi.meta.helper.DictionaryCache;
import com.ningdatech.pmapi.meta.helper.ExpertUserInfoHelper;
import com.ningdatech.pmapi.meta.model.ExpertRegionInfo;
import com.ningdatech.pmapi.meta.model.bo.RegionContainsBO;
import com.ningdatech.pmapi.meta.model.dto.DictionaryDTO;
import com.ningdatech.pmapi.meta.model.entity.ExpertDictionary;
import com.ningdatech.pmapi.meta.service.IExpertDictionaryService;
import com.ningdatech.pmapi.sys.model.dto.RegionDTO;
import com.ningdatech.pmapi.user.util.LoginUserUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author liuxinxin
 * @date 2023/3/1 上午10:38
 */

@Component
@RequiredArgsConstructor
public class ExpertMetaApplyManage {

    private final IExpertMetaApplyService iMetaApplyService;
    private final IExpertDictionaryService expertDictionaryService;

    //    private final IExpertAdminManageService ExpertAdminManageService;
    private final RegionCacheHelper regionCacheHelper;
    private final IExpertUserFullInfoService userFullInfoService;
    private final DictionaryCache dictionaryCache;

    private final ExpertInfoService expertInfoService;

    private final UserInfoHelper userInfoHelper;

    private final RegionLimitHelper regionLimitHelper;

    private final ExpertUserInfoHelper expertUserInfoHelper;


    public PageVo<ExpertApplyMetaVO> metaApplyListQuery(MetaApplyListQuery req) {
        Long expertAdminUserId = LoginUserUtil.getUserId();
        // 查找符合专家条件的用户id
        List<RegionContainsBO> viewRegions = regionLimitHelper.getExpertAdminContainsRegion(expertAdminUserId);
        ExpertAdminExpertManageQueryCmd queryCmd = buildExpertAdminExpertManageQueryCmd(req, viewRegions);
        // TODO
//        List<Long> filterExpertUserIdList = expertAdminManageService.filterExpertUserIdList(queryCmd);
        List<Long> filterExpertUserIdList = new ArrayList<>();
        if (CollUtil.isEmpty(filterExpertUserIdList)) {
            return PageVo.empty();
        }

        LambdaQueryWrapper<ExpertMetaApply> expertMetaApplyListQuery =
                buildMetaApplyListQueryWrapper(req, filterExpertUserIdList, viewRegions);

        RegionWrapperAssembler.expertMetaApplyRegionContainsWrapperAssembler(expertMetaApplyListQuery, viewRegions);
        Page<ExpertMetaApply> pageResult = iMetaApplyService.page(req.page(), expertMetaApplyListQuery);
        PageVo<ExpertApplyMetaVO> result = new PageVo<>();
        result.setTotal(pageResult.getTotal());
        BizUtils.notEmpty(pageResult.getRecords(), records -> {
            List<Long> expertIds = CollUtils.fieldList(records, ExpertMetaApply::getUserId);
            // 根据用户id 获取专家基本信息
            List<ExpertUserFullInfo> expertList = userFullInfoService.listByUserIds(expertIds);
            Map<Long, ExpertUserFullInfo> expertMap = CollUtils.listToMap(expertList, ExpertUserFullInfo::getUserId);
            List<ExpertDictionary> expertDictList = expertDictionaryService.listByUserId(expertIds, DictExpertInfoTypeEnum.TITLE_LEVEL);
            Map<Long, List<ExpertDictionary>> dictMap = CollUtils.group(expertDictList, ExpertDictionary::getUserId);
            result.setRecords(buildExpertApplyMetaVOList(records, expertMap, dictMap));
        });
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    public void metaApplyResult(MetaApplyResultRequest req) {
        Long applyId = req.getApplyId();
        ExpertMetaApply expertMetaApply = iMetaApplyService.getById(applyId);
        Long userId = LoginUserUtil.getUserId();

        // 校验专家管理员区域权限，是否可以审核当前专家申请
//        permissionCheckHelper.operationPermissionsCheck(userId, expertMetaApply.getUserId());
        String applyStatus = expertMetaApply.getApplyStatus();
        if (!ExpertApplyStatusEnum.PENDING_REVIEW.getKey().equals(applyStatus)) {
            throw BizException.wrap("apply is already processed");
        }
        ExpertApplyTypeEnum applyType = ExpertApplyTypeEnum.of(expertMetaApply.getApplyType());
        boolean applyResult = req.getApplyResult();

        switch (applyType) {
            // 专家入库
            case EXPERT_STORAGE: {
                ExpertStorageDealCmd expertStorageDealCmd = buildExpertStorageDealCmd(req, expertMetaApply.getUserId(), expertMetaApply);
                expertInfoService.expertStorageDeal(expertStorageDealCmd);
                // 专家入库时，需要先审核专家入库，入库成功后，再履职意向审核，如果履职意向跟专家层级是同一层级的，就直接同意不需要审核
                if (applyResult) {
                    Long expertUserId = expertMetaApply.getUserId();
                    ExpertRegionInfo expertRegionInfo = expertUserInfoHelper.getExpertRegionInfo(expertUserId);
                    Integer regionLevel = expertRegionInfo.getRegionLevel();
                    String regionCode = expertRegionInfo.getRegionCode();

                    List<ExpertMetaApply> expertJoinApplyList = iMetaApplyService.list(Wrappers.lambdaQuery(ExpertMetaApply.class)
                            .eq(ExpertMetaApply::getUserId, expertUserId)
                            .eq(ExpertMetaApply::getApplyStatus, ExpertApplyStatusEnum.PENDING_REVIEW.getKey())
                            .eq(ExpertMetaApply::getApplyType, ExpertApplyTypeEnum.EXPERT_INTENTION_JOIN.getKey())
                            .eq(ExpertMetaApply::getDisplayEnable, BoolDisplayEnum.Y.name())
                            .eq(ExpertMetaApply::getRegionLevel, regionLevel)
                            .eq(ExpertMetaApply::getRegionCode, regionCode));
                    BizUtils.notEmpty(expertJoinApplyList, list -> list.forEach(r -> {
                        MetaApplyResultRequest resultRequest = new MetaApplyResultRequest();
                        resultRequest.setApplyId(r.getId());
                        resultRequest.setApplyResult(true);
                        resultRequest.setAuditOpinion("同意");
                        metaApplyResult(resultRequest);
                    }));
                }
            }
            break;
            // 专家出库
            case EXPERT_DELIVERY:
//                ExpertDeliveryDealCmd expertDeliveryDealCmd = buildExpertDeliveryDealCmd(req, expertMetaApply.getUserId());
//                expertInfoService.expertDeliveryDeal(expertDeliveryDealCmd);
                break;
            // 长期请假
            case LONG_TERM_LEAVE:
//                leaveManage.leaveAuditCallback(req.getApplyResult(), applyId);
                break;
            // 专家信息审核
            case EXPERT_INFO_MODIFY:
//                ExpertInfoModifyApplyDealCmd applyDealCmd = buildExpertInfoModifyApplyDealCmd(req, expertMetaApply.getUserId(), applyId);
//                expertInfoService.expertInfoModifyDeal(applyDealCmd);
                break;
            // 专家履职意向加入/离开
            case EXPERT_INTENTION_JOIN:
            case EXPERT_INTENTION_LEAVE:
//                ExpertIntentionApplyDealCmd expertIntentionApplyDealCmd = buildExpertIntentionApplyDealCmd(req, expertMetaApply);
//                expertInfoService.expertIntentionApplyDeal(expertIntentionApplyDealCmd);
                break;
            default:
                break;
        }

        Long expertUserId = expertMetaApply.getUserId();
        String auditOpinion = req.getAuditOpinion();
        // 发送审核结果短信
//        sendApplyResultNotify(applyType, applyResult, auditOpinion, expertUserId);
        // 更新申请结果
        expertMetaApply.setApproverUserId(userId);
        String adminUserName = userInfoHelper.getUserName(userId);
        expertMetaApply.setApprover(adminUserName);
        expertMetaApply.setAuditOpinion(auditOpinion);
        expertMetaApply.setApplyStatus(applyResult ? ExpertApplyStatusEnum.PASSED.getKey() : ExpertApplyStatusEnum.REFUSED.getKey());
        expertMetaApply.setReviewTime(LocalDateTime.now());
        expertMetaApply.setUpdateOn(LocalDateTime.now());
        iMetaApplyService.saveOrUpdate(expertMetaApply);
    }

    public MetaApplyResultVo metaApplyResult(Long applyId) {
        ExpertMetaApply metaApply = iMetaApplyService.getById(applyId);
        if (Objects.isNull(metaApply)) {
            throw BizException.wrap("当前审核不存在");
        }
        MetaApplyResultVo metaApplyResultVo = MetaApplyResultVo.builder()
                .applyTime(metaApply.getCreateOn())
                .auditor(metaApply.getApprover())
                .expertUserId(metaApply.getUserId())
                .auditOption(metaApply.getAuditOpinion())
                .auditStatus(metaApply.getApplyStatus())
                .auditTime(metaApply.getReviewTime())
                .build();
        String extraMaterialStr = metaApply.getExtraMaterial();
//        if (StringUtils.isNotBlank(extraMaterialStr)) {
//            ExtraMaterialDO extraMaterialDO = JSONObject.parseObject(extraMaterialStr, ExtraMaterialDO.class);
//            ModifyApplyExtraInfo modifyApplyExtraInfo = new ModifyApplyExtraInfo();
//            BizUtils.notEmpty(extraMaterialDO.getEvidenceList(), list -> {
//                List<Long> fileIdList = CollUtils.fieldList(list, FileBasicInfo::getFileId);
//                List<AttachFileVo> attachFiles = fileService.getByIds(fileIdList);
//                List<FileBasicInfo> tempList = attachFiles.stream().map(r -> {
//                    FileBasicInfo fileBasicInfo = new FileBasicInfo();
//                    fileBasicInfo.setFileId(r.getFileId());
//                    fileBasicInfo.setFileName(r.getOriginalFileName());
//                    return fileBasicInfo;
//                }).collect(Collectors.toList());
//                modifyApplyExtraInfo.setEvidenceList(tempList);
//            });
//            modifyApplyExtraInfo.setFactSheet(extraMaterialDO.getFactSheet());
//            metaApplyResultVo.setModifyApplyExtraInfo(modifyApplyExtraInfo);
//        }
        String applyType = metaApply.getApplyType();
        ExpertApplyTypeEnum applyTypeEnum = ExpertApplyTypeEnum.of(applyType);
        switch (applyTypeEnum) {
//            case EXPERT_INFO_MODIFY:
//                buildInfoModifyApplyDisplayVO(metaApplyResultVo, metaApply);
//                break;
            case EXPERT_INTENTION_JOIN:
            case EXPERT_INTENTION_LEAVE:
                buildIntentionApplyDisplayVO(metaApplyResultVo, metaApply, applyTypeEnum);
                break;
            case EXPERT_DELIVERY:
            case LONG_TERM_LEAVE:
            case EXPERT_STORAGE:
            default:
                break;
        }
        metaApplyResultVo.setApplyType(applyTypeTrans(applyTypeEnum));
        return metaApplyResultVo;
    }


    public void metaApplyRevoke(Long applyId) {
        Long userId = LoginUserUtil.getUserId();
        ExpertMetaApply expertMetaApply = iMetaApplyService.getById(applyId);
        if (Objects.isNull(expertMetaApply)) {
            throw new BizException("apply not exist");
        }
        if (!expertMetaApply.getUserId().equals(userId)) {
            throw new BizException("has not right to operate");
        }
        String applyStatus = expertMetaApply.getApplyStatus();
        ExpertApplyStatusEnum expertApplyStatusEnum = ExpertApplyStatusEnum.of(applyStatus);
        if (!ExpertApplyStatusEnum.PENDING_REVIEW.equals(expertApplyStatusEnum)) {
            throw new BizException("apply is already deal");
        }
        expertMetaApply.setApplyStatus(ExpertApplyStatusEnum.REVOKED.getKey());
        expertMetaApply.setUpdateOn(LocalDateTime.now());
        iMetaApplyService.updateById(expertMetaApply);
    }


    private void buildIntentionApplyDisplayVO(MetaApplyResultVo metaApplyResultVo, ExpertMetaApply metaApply, ExpertApplyTypeEnum applyTypeEnum) {
        String regionCode = metaApply.getRegionCode();
        Integer regionLevel = metaApply.getRegionLevel();
//        String unionPathStr = regionCache.getUnionPathStr(regionCode, regionLevel);
        MetaApplyResultVo.IntentionApplyDisplayVO intentionApplyDisplayVO = new MetaApplyResultVo.IntentionApplyDisplayVO();
        intentionApplyDisplayVO.setExpertApplyId(metaApply.getId());
        ExpertRegionInfo expertRegionInfo = new ExpertRegionInfo();
        expertRegionInfo.setRegionCode(regionCode);
        expertRegionInfo.setRegionLevel(regionLevel);
//        expertRegionInfo.setRegionName(unionPathStr);
        switch (applyTypeEnum) {
            case EXPERT_INTENTION_LEAVE: {
                intentionApplyDisplayVO.setReduceExpertRegion(expertRegionInfo);
            }
            break;
            case EXPERT_INTENTION_JOIN: {
                intentionApplyDisplayVO.setAddExpertRegion(expertRegionInfo);
            }
            break;
            default:
                break;
        }
        metaApplyResultVo.setIntentionApplyDisplayVo(intentionApplyDisplayVO);
    }

//    private void buildInfoModifyApplyDisplayVO(MetaApplyResultVo metaApplyResultVo, ExpertMetaApply infoModifyApply) {
//        InfoModifyApplyDisplayVO infoModifyApplyDisplayVo = new InfoModifyApplyDisplayVO();
//        if (Objects.nonNull(infoModifyApply)) {
//            Long metaApplyId = infoModifyApply.getId();
//            LambdaQueryWrapper<ExpertSensitiveInfoModifyDetailRecord> eq = Wrappers.lambdaQuery(ExpertSensitiveInfoModifyDetailRecord.class)
//                    .eq(ExpertSensitiveInfoModifyDetailRecord::getMetaApplyId, metaApplyId);
//            ExpertSensitiveInfoModifyDetailRecord one = iExpertSensitiveInfoModifyDetailRecordService.getOne(eq);
//            String originalJson = null;
//            if (StringUtils.isNotBlank(one.getOriginalJson())) {
//                originalJson = GzipUtils.uncompress(one.getOriginalJson());
//            }
//            List<SensitiveModifySegment> sensitiveModifySegments = JSONUtils.parseArray(originalJson, SensitiveModifySegment.class);
//
//            infoModifyApplyDisplayVo.setExpertApplyId(metaApplyId);
//            List<InfoModifyApplyDisplayVO.InfoModifyApplyDisplayValue> displayValueList = new ArrayList<>();
//            for (SensitiveModifySegment segment : sensitiveModifySegments) {
//                InfoModifyApplyDisplayVO.InfoModifyApplyDisplayValue displayValue = sensitiveModifySegmentParser.getDisplayValue(segment);
//                displayValueList.add(displayValue);
//            }
//            infoModifyApplyDisplayVo.setInfoModifyApplyDisplayValueList(displayValueList);
//            metaApplyResultVo.setInfoModifyApplyDisplayVo(infoModifyApplyDisplayVo);
//        }
//    }

    private String applyTypeTrans(ExpertApplyTypeEnum applyTypeEnum) {
        switch (applyTypeEnum) {
            case EXPERT_INTENTION_JOIN:
            case EXPERT_INTENTION_LEAVE: {
                return ExpertApplyTypeQueryEnum.EXPERT_INTENTION_CHANGE.getKey();
            }
            case EXPERT_INFO_MODIFY: {
                return ExpertApplyTypeQueryEnum.EXPERT_INFO_MODIFY.getKey();
            }
            case LONG_TERM_LEAVE: {
                return ExpertApplyTypeQueryEnum.LONG_TERM_LEAVE.getKey();
            }
            case EXPERT_DELIVERY: {
                return ExpertApplyTypeQueryEnum.EXPERT_DELIVERY.getKey();
            }
            case EXPERT_STORAGE: {
                return ExpertApplyTypeQueryEnum.EXPERT_STORAGE.getKey();
            }
            default:
                return null;
        }
    }

    private List<String> applyTypeTrans(ExpertApplyTypeQueryEnum applyTypeQueryEnum) {
        List<String> applyTypeList = new ArrayList<>();
        switch (applyTypeQueryEnum) {
            case EXPERT_INTENTION_CHANGE: {
                applyTypeList.add(ExpertApplyTypeEnum.EXPERT_INTENTION_JOIN.getKey());
                applyTypeList.add(ExpertApplyTypeEnum.EXPERT_INTENTION_LEAVE.getKey());
            }
            break;
            case EXPERT_INFO_MODIFY: {
                applyTypeList.add(ExpertApplyTypeEnum.EXPERT_INFO_MODIFY.getKey());
            }
            break;
            case LONG_TERM_LEAVE: {
                applyTypeList.add(ExpertApplyTypeEnum.LONG_TERM_LEAVE.getKey());
            }
            break;
            case EXPERT_DELIVERY: {
                applyTypeList.add(ExpertApplyTypeEnum.EXPERT_DELIVERY.getKey());
            }
            break;
            case EXPERT_STORAGE: {
                applyTypeList.add(ExpertApplyTypeEnum.EXPERT_STORAGE.getKey());
            }
            break;
            default:
                break;
        }
        return applyTypeList;
    }

    private ExpertAdminExpertManageQueryCmd buildExpertAdminExpertManageQueryCmd(MetaApplyListQuery query, List<RegionContainsBO> expertAdminContainsRegionList) {
        ExpertAdminExpertManageQueryCmd expertAdminExpertManageQueryCmd = new ExpertAdminExpertManageQueryCmd();
        expertAdminExpertManageQueryCmd.setPageNumber(query.getPageNumber());
        expertAdminExpertManageQueryCmd.setPageSize(query.getPageSize());
        if (StringUtils.isNotBlank(query.getExpertName())) {
            expertAdminExpertManageQueryCmd.setExpertName(query.getExpertName());
        }
        if (StringUtils.isNotBlank(query.getCompanyName())) {
            expertAdminExpertManageQueryCmd.setCompany(query.getCompanyName());
        }
        List<ExpertDictionaryQuery> expertDictionaryQueryList = new ArrayList<>();
        if (StringUtils.isNotBlank(query.getTitleLevelDictionaryCode())) {
            ExpertDictionaryQuery expertDictionaryQuery = new ExpertDictionaryQuery();
            expertDictionaryQuery.setExpertInfoField(DictExpertInfoTypeEnum.TITLE_LEVEL.getKey());
            expertDictionaryQuery.setDictionaryCodeList(CollectionUtil.toList(query.getTitleLevelDictionaryCode()));
            expertDictionaryQueryList.add(expertDictionaryQuery);
        }

        List<RegionContainsBO> containsRegion;
        if (Objects.nonNull(query.getExpertRegion())) {
            RegionContainsBO containsRegionBo = regionLimitHelper.getContainsRegionBo(query.getExpertRegion().getRegionLevel()
                    , query.getExpertRegion().getRegionCode());
            containsRegion = regionLimitHelper.queryContainsRegionAssembler(containsRegionBo, expertAdminContainsRegionList);
        } else {
            containsRegion = expertAdminContainsRegionList;
        }

        expertAdminExpertManageQueryCmd.setExpertDictionaryQueryList(expertDictionaryQueryList);
        expertAdminExpertManageQueryCmd.setRegionContainsList(containsRegion);
        expertAdminExpertManageQueryCmd.setPageSize(query.getPageSize());
        expertAdminExpertManageQueryCmd.setPageNumber(query.getPageNumber());
        return expertAdminExpertManageQueryCmd;
    }


    /**
     * 装配 专家审核列表筛选返回VO
     *
     * @param expertMetaApplyList     /
     * @param expertUserFullInfoMap   /
     * @param expertDictionaryListMap /
     * @return /
     */
    private List<ExpertApplyMetaVO> buildExpertApplyMetaVOList(List<ExpertMetaApply> expertMetaApplyList
            , Map<Long, ExpertUserFullInfo> expertUserFullInfoMap
            , Map<Long, List<ExpertDictionary>> expertDictionaryListMap) {
        List<ExpertApplyMetaVO> expertApplyMetaVOList = new ArrayList<>();
        for (ExpertMetaApply expertMetaApply : expertMetaApplyList) {
            ExpertApplyMetaVO expertApplyMetaVO = new ExpertApplyMetaVO();
            Long userId = expertMetaApply.getUserId();
            ExpertUserFullInfo expertUserFullInfo = expertUserFullInfoMap.get(userId);
            expertApplyMetaVO.setId(expertMetaApply.getId());
            expertApplyMetaVO.setUserId(userId);
            expertApplyMetaVO.setApplyStatus(expertMetaApply.getApplyStatus());

            String applyType = expertMetaApply.getApplyType();
            if (Objects.nonNull(applyType)) {
                expertApplyMetaVO.setApplyType(applyTypeTrans(ExpertApplyTypeEnum.of(applyType)));
            }
            expertApplyMetaVO.setName(expertUserFullInfo.getExpertName());

            RegionDTO regionDTO = regionCacheHelper.getByCodeAndLevel(expertUserFullInfo.getRegionCode(), expertUserFullInfo.getRegionLevel());
            ExpertRegionInfo expertRegionInfo = new ExpertRegionInfo();
            expertRegionInfo.setRegionCode(expertUserFullInfo.getRegionCode());
            expertRegionInfo.setRegionLevel(expertUserFullInfo.getRegionLevel());
            expertRegionInfo.setRegionName(regionDTO.getRegionName());
            expertApplyMetaVO.setExpertRegionInfo(expertRegionInfo);

            List<ExpertDictionary> expertDictionaryList = expertDictionaryListMap.get(userId);
            if (CollectionUtils.isNotEmpty(expertDictionaryList)) {
                expertApplyMetaVO.setTitleLevel(expertDictionaryList.stream().map(r -> {
                    DictionaryDTO dictionaryDTO = dictionaryCache.getByCode(r.getDictionaryCode());
                    DictionaryFieldInfo dictionaryFieldInfo = new DictionaryFieldInfo();
                    dictionaryFieldInfo.setDictionaryCode(r.getDictionaryCode());
                    dictionaryFieldInfo.setDictionaryFieldName(r.getExpertInfoField());
                    if (Objects.nonNull(dictionaryDTO)) {
                        dictionaryFieldInfo.setDictionaryName(dictionaryDTO.getName());
                    }
                    return dictionaryFieldInfo;
                }).collect(Collectors.toList()));
            }

            expertApplyMetaVO.setCompany(expertUserFullInfo.getCompany());
            expertApplyMetaVO.setPhoneNo(expertUserFullInfo.getPhoneNo());
            expertApplyMetaVO.setApplyTime(expertMetaApply.getCreateOn());
            expertApplyMetaVOList.add(expertApplyMetaVO);
        }
        return expertApplyMetaVOList;
    }

    private LambdaQueryWrapper<ExpertMetaApply> buildMetaApplyListQueryWrapper(MetaApplyListQuery applyListReq,
                                                                               List<Long> expertIdList,
                                                                               List<RegionContainsBO> viewRegions) {
        // 审核类型
        List<String> applyTypeList = new ArrayList<>();
        if (CollUtil.isNotEmpty(applyListReq.getApplyTypeList())) {
            List<ExpertApplyTypeQueryEnum> applyTypeQueryEnumList = applyListReq.getApplyTypeList();
            for (ExpertApplyTypeQueryEnum applyTypeQueryEnum : applyTypeQueryEnumList) {
                applyTypeList.addAll(applyTypeTrans(applyTypeQueryEnum));
            }
        }
        // 审核结果
        List<String> applyStatusList = new ArrayList<>();
        if (CollUtil.isNotEmpty(applyListReq.getApplyStatusList())) {
            applyStatusList = CollUtils.fieldList(applyListReq.getApplyStatusList(), ExpertApplyStatusEnum::getKey);
            ;
        }

        LocalDateTime applyStartTime = applyListReq.getApplyStartTime();
        LocalDateTime applyEndTime = applyListReq.getApplyEndTime();

        // 不展示撤回的申请记录
        LambdaQueryWrapper<ExpertMetaApply> expertMetaApplyListQuery = Wrappers.lambdaQuery(ExpertMetaApply.class)
                .in(CollectionUtils.isNotEmpty(applyTypeList), ExpertMetaApply::getApplyType, applyTypeList)
                .in(CollectionUtils.isNotEmpty(applyStatusList), ExpertMetaApply::getApplyStatus, applyStatusList)
                .in(ExpertMetaApply::getDisplayEnable, BoolDisplayEnum.Y.name())
                .in(CollectionUtils.isNotEmpty(expertIdList), ExpertMetaApply::getUserId, expertIdList)
                .gt(Objects.nonNull(applyStartTime), ExpertMetaApply::getCreateOn, applyStartTime)
                .lt(Objects.nonNull(applyEndTime), ExpertMetaApply::getCreateOn, applyEndTime)
                .ne(ExpertMetaApply::getApplyStatus, ExpertApplyStatusEnum.REVOKED.getKey())
                .orderByDesc(ExpertMetaApply::getCreateOn);

        RegionWrapperAssembler.expertMetaApplyRegionContainsWrapperAssembler(expertMetaApplyListQuery, viewRegions);
        return expertMetaApplyListQuery;
    }

    private ExpertStorageDealCmd buildExpertStorageDealCmd(
            MetaApplyResultRequest applyResultRequest, Long expertUserId, ExpertMetaApply expertMetaApply) {
        MetaApplyResultRequest.StorageApplyResultExtraInfo extraInfo = applyResultRequest.getStorageApplyResultExtraInfo();
        ExpertStorageDealCmd expertStorageDealCmd = new ExpertStorageDealCmd();
        Boolean applyResult = applyResultRequest.getApplyResult();
        expertStorageDealCmd.setApplyResult(applyResult);

        if (Objects.nonNull(extraInfo)) {
            List<DictionaryFieldInfo> expertType = extraInfo.getExpertType();
            if (CollectionUtils.isNotEmpty(expertType)) {
                expertStorageDealCmd.setExpertType(extraInfo.getExpertType().stream().map(r -> {
                    ExpertDictionaryDTO expertDictionaryDTO = new ExpertDictionaryDTO();
                    expertDictionaryDTO.setExpertInfoField(r.getDictionaryFieldName());
                    expertDictionaryDTO.setDictionaryCode(r.getDictionaryCode());
                    return expertDictionaryDTO;
                }).collect(Collectors.toList()));
            }
            List<TagFieldInfo> other = extraInfo.getOther();
            if (CollectionUtils.isNotEmpty(other)) {
                expertStorageDealCmd.setOther(extraInfo.getOther().stream().map(r -> {
                    ExpertTagDTO expertTagDTO = new ExpertTagDTO();
                    expertTagDTO.setExpertInfoField(r.getTagFieldName());
                    expertTagDTO.setTagCode(r.getTagCode());
                    return expertTagDTO;
                }).collect(Collectors.toList()));
            }
            expertStorageDealCmd.setRemark(extraInfo.getRemark());
        }
        expertStorageDealCmd.setExpertUserId(expertUserId);
        expertStorageDealCmd.setJoinRegionCode(expertMetaApply.getRegionCode());
        expertStorageDealCmd.setJoinRegionLevel(expertMetaApply.getRegionLevel());
        return expertStorageDealCmd;
    }

}
