package com.hz.pm.api.expert.manage;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ningdatech.basic.exception.BizException;
import com.ningdatech.basic.model.GenericResult;
import com.ningdatech.basic.model.PageVo;
import com.hz.pm.api.common.enumeration.BoolDisplayEnum;
import com.hz.pm.api.common.helper.RegionLimitHelper;
import com.hz.pm.api.common.model.CommonPage;
import com.hz.pm.api.common.util.StrUtils;
import com.hz.pm.api.expert.assembler.ExpertAdminExpertManageAssembler;
import com.hz.pm.api.expert.assembler.ExpertInfoCmdAssembler;
import com.hz.pm.api.expert.constant.ExpertAccountStatusEnum;
import com.hz.pm.api.expert.constant.ExpertApplyStatusEnum;
import com.hz.pm.api.expert.constant.ExpertApplyTypeEnum;
import com.hz.pm.api.expert.constant.QueryExpertAccountStatusEnum;
import com.hz.pm.api.expert.entity.ExpertMetaApply;
import com.hz.pm.api.expert.helper.ExpertInfoSensitiveFieldModifyCheckHelper;
import com.hz.pm.api.expert.helper.PermissionCheckHelper;
import com.hz.pm.api.expert.model.*;
import com.hz.pm.api.expert.model.bo.ExpertInfoSensitiveFieldCheckBO;
import com.hz.pm.api.expert.model.cmd.ExpertAdminExpertManageQueryCmd;
import com.hz.pm.api.expert.model.cmd.ExpertInfoModifyCmd;
import com.hz.pm.api.expert.model.dto.ExpertAdminExpertListDTO;
import com.hz.pm.api.expert.model.query.ExpertDictionaryQuery;
import com.hz.pm.api.expert.model.req.AdminExpertBasicInfoModifyRequest;
import com.hz.pm.api.expert.model.req.GetZzdInfoRequest;
import com.hz.pm.api.expert.model.req.MetaApplyResultRequest;
import com.hz.pm.api.expert.model.vo.ExpertLibraryListItemVO;
import com.hz.pm.api.expert.model.vo.ExpertBasicInfoModifyResultVO;
import com.hz.pm.api.expert.model.vo.ZzdInfoByMobileVO;
import com.hz.pm.api.expert.service.ExpertAdminManageService;
import com.hz.pm.api.expert.service.ExpertInfoService;
import com.hz.pm.api.expert.service.IExpertMetaApplyService;
import com.hz.pm.api.meta.constant.ExpertDictTypeEnum;
import com.hz.pm.api.user.util.LoginUserUtil;
import com.ningdatech.zwdd.client.ZwddClient;
import com.ningdatech.zwdd.model.dto.DingInfoByMobileDTO;
import com.ningdatech.zwdd.model.dto.DingOrgInfoDTO;
import com.ningdatech.zwdd.model.dto.EmployeeInfoDTO;
import com.ningdatech.zwdd.model.dto.EmployeePositionsDTO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author liuxinxin
 * @date 2023/3/1 下午2:12
 */

@Component
@RequiredArgsConstructor
public class ExpertAdminManage {

    private final PermissionCheckHelper permissionCheckHelper;
    private final RegionLimitHelper regionLimitHelper;
    private final IExpertMetaApplyService iExpertMetaApplyService;
    private final ExpertInfoSensitiveFieldModifyCheckHelper expertInfoSensitiveFieldModifyCheckHelper;
    private final ExpertInfoService expertInfoService;
    private final ExpertMetaApplyManage expertMetaApplyManage;
    private final ExpertAdminManageService expertAdminManageService;
    private final ExpertAdminExpertManageAssembler expertAdminExpertManageAssembler;
    private final ZwddClient zwddClient;

    /**
     * 专家管理员使用 专家库列表查询
     *
     * @param query \
     * @return \
     */
    public PageVo<ExpertLibraryListItemVO> getExpertLibraryList(ExpertLibraryReq query) {
        ExpertAdminExpertManageQueryCmd queryCmd = buildExpertAdminExpertManageQueryCmd(query);
        if (queryCmd.isHasNonData()) {
            return PageVo.empty();
        }
        CommonPage<ExpertAdminExpertListDTO> page = expertAdminManageService.getExpertLibraryList(queryCmd);

        PageVo<ExpertLibraryListItemVO> pageVo = new PageVo<>();
        pageVo.setTotal(page.getItemsTotal());
        pageVo.setRecords(expertAdminExpertManageAssembler.toViews(page.getItems()));
        return pageVo;
    }


    private ExpertAdminExpertManageQueryCmd buildExpertAdminExpertManageQueryCmd(ExpertLibraryReq query) {
        ExpertAdminExpertManageQueryCmd queryCmd = new ExpertAdminExpertManageQueryCmd();
        queryCmd.setPageNumber(query.getPageNumber());
        queryCmd.setPageSize(query.getPageSize());
        if (StrUtils.isNotBlank(query.getExpertName())) {
            queryCmd.setExpertName(query.getExpertName());
        }
        if (StrUtils.isNotBlank(query.getCompany())) {
            queryCmd.setCompany(query.getCompany());
        }
        List<ExpertDictionaryQuery> dictQuery = new ArrayList<>();
        if (StrUtils.isNotBlank(query.getTitleLevelDictionaryCode())) {
            ExpertDictionaryQuery expertDictQuery = new ExpertDictionaryQuery();
            expertDictQuery.setExpertInfoField(ExpertDictTypeEnum.TITLE_LEVEL.getKey());
            expertDictQuery.setDictionaryCodeList(CollectionUtil.toList(query.getTitleLevelDictionaryCode()));
            dictQuery.add(expertDictQuery);
        }
        if (StrUtils.isNotBlank(query.getCompanyAttributeDictionaryCode())) {
            ExpertDictionaryQuery expertDictQuery = new ExpertDictionaryQuery();
            expertDictQuery.setExpertInfoField(ExpertDictTypeEnum.COMPANY_ATTRIBUTE.getKey());
            expertDictQuery.setDictionaryCodeList(CollectionUtil.toList(query.getCompanyAttributeDictionaryCode()));
            dictQuery.add(expertDictQuery);
        }
        if (StrUtils.isNotBlank(query.getExpertTypeDictionaryCode())) {
            ExpertDictionaryQuery expertDictQuery = new ExpertDictionaryQuery();
            expertDictQuery.setExpertInfoField(ExpertDictTypeEnum.EXPERT_TYPE.getKey());
            expertDictQuery.setDictionaryCodeList(CollectionUtil.toList(query.getExpertTypeDictionaryCode()));
            dictQuery.add(expertDictQuery);
        }
        if (StrUtils.isNotBlank(query.getExpertAccountStatus())) {
            QueryExpertAccountStatusEnum queryExpertAccountStatus = QueryExpertAccountStatusEnum.of(query.getExpertAccountStatus());
            switch (queryExpertAccountStatus) {
                case NORMAL:
                    queryCmd.setExpertAccountStatusList(CollectionUtil.toList(ExpertAccountStatusEnum.AVAILABLE));
                    break;
                case FREEZING:
                    queryCmd.setExpertAccountStatusList(CollectionUtil.toList(ExpertAccountStatusEnum.FREEZE));
                    break;
                default:
                    break;
            }
        } else {
            queryCmd.setExpertAccountStatusList(CollectionUtil.toList(ExpertAccountStatusEnum.AVAILABLE, ExpertAccountStatusEnum.FREEZE));
        }

        queryCmd.setExpertDictionaryQueryList(dictQuery);
        queryCmd.setIsDingUser(query.getIsDingUser());
        queryCmd.setPageSize(query.getPageSize());
        queryCmd.setPageNumber(query.getPageNumber());
        return queryCmd;
    }


    /**
     * 专家管理员修改专家的个人信息接口(包含专家层级变更)
     *
     * @param request
     * @return
     */
    public ExpertBasicInfoModifyResultVO adminModifyExpertBasicInfo(AdminExpertBasicInfoModifyRequest request) {
        Long adminUserId = LoginUserUtil.getUserId();
        Long expertUserId = request.getExpertUserId();
        // 手机号不能更改
        request.getBasicInfo().setPhoneNo(null);

        // 校验当前是否有信息变更审核 如有，无法变更信息
        LambdaQueryWrapper<ExpertMetaApply> infoModifyEq = Wrappers.lambdaQuery(ExpertMetaApply.class)
                .eq(ExpertMetaApply::getUserId, expertUserId)
                .eq(ExpertMetaApply::getApplyType, ExpertApplyTypeEnum.EXPERT_INFO_MODIFY.getKey())
                .eq(ExpertMetaApply::getApplyStatus, ExpertApplyStatusEnum.PENDING_REVIEW.getKey())
                .eq(ExpertMetaApply::getDisplayEnable, BoolDisplayEnum.Y.name());
        ExpertMetaApply infoModifyApply = iExpertMetaApplyService.getOne(infoModifyEq);
        if (Objects.nonNull(infoModifyApply)) {
            throw new BizException("该账号还有信息修审核审核未审批，请撤销或审批后处理");
        }
        // 校验当前是否有层级变更审核,如有需要审核通过或撤销审核后重新提交
        LambdaQueryWrapper<ExpertMetaApply> expertStorageEq = Wrappers.lambdaQuery(ExpertMetaApply.class)
                .eq(ExpertMetaApply::getUserId, expertUserId)
                .eq(ExpertMetaApply::getApplyType, ExpertApplyTypeEnum.EXPERT_STORAGE.getKey())
                .eq(ExpertMetaApply::getApplyStatus, ExpertApplyStatusEnum.PENDING_REVIEW.getKey())
                .eq(ExpertMetaApply::getDisplayEnable, BoolDisplayEnum.Y.name());
        ExpertMetaApply expertStorageApply = iExpertMetaApplyService.getOne(expertStorageEq);
        if (Objects.nonNull(expertStorageApply)) {
            throw new BizException("当前账号还有入库审核未审批，请撤销或审批后处理");
        }

        ExpertBasicInfo basicInfo = request.getBasicInfo();
        ExpertEduInfo eduInfo = request.getEduInfo();
        ExpertJobInfo jobInfo = request.getJobInfo();
        ExpertProfessionalInfo professionalInfo = request.getProfessionalInfo();
        ExpertRecommendInfo recommendInfo = request.getRecommendInfo();
        ExpertOtherInfo otherInfo = request.getExpertOtherInfo();

        ExpertInfoSensitiveFieldCheckBO expertInfoSensitiveFieldCheckBO =
                expertInfoSensitiveFieldModifyCheckHelper.expertInfoSensitiveFieldModifyCheck(basicInfo, jobInfo, professionalInfo, expertUserId);
        ExpertInfoModifyCmd expertInfoModifyCmd = ExpertInfoCmdAssembler
                .buildExpertInfoModifyCmd(expertUserId, basicInfo, eduInfo, jobInfo, professionalInfo, recommendInfo, otherInfo, expertInfoSensitiveFieldCheckBO, null);
        List<Long> applyIdList = expertInfoService.adminModifyExpertInfo(expertInfoModifyCmd, adminUserId);

        // 批量通过专家管理员审核
        for (Long applyId : applyIdList) {
            MetaApplyResultRequest applyResult = new MetaApplyResultRequest();
            applyResult.setApplyId(applyId);
            applyResult.setAuditOpinion("同意");
            applyResult.setApplyResult(true);
            expertMetaApplyManage.metaApplyResult(applyResult);
        }
        return new ExpertBasicInfoModifyResultVO(false);
    }


    public ZzdInfoByMobileVO getZzdInfo(GetZzdInfoRequest request) {
        ZzdInfoByMobileVO zzdInfoByMobileVO = new ZzdInfoByMobileVO();
        String phoneNo = request.getPhoneNo();
        zzdInfoByMobileVO.setPhoneNo(phoneNo);

        GenericResult<DingInfoByMobileDTO> dingInfoByMobile = zwddClient.getDingInfoByMobile(phoneNo);
        DingInfoByMobileDTO dingInfo = dingInfoByMobile.getData();
        if (Objects.nonNull(dingInfo) && StringUtils.isNotBlank(dingInfo.getEmployeeCode())) {
            zzdInfoByMobileVO.setIsDingUser(true);
            String employeeCode = dingInfo.getEmployeeCode();
            GenericResult<List<EmployeePositionsDTO>> listGenericResult = zwddClient.listEmployeePositionsByEmployeeCode(employeeCode);
            List<EmployeePositionsDTO> employeePositionsDTOS = listGenericResult.getData();
            if (CollectionUtils.isNotEmpty(employeePositionsDTOS)) {
                EmployeePositionsDTO employeePositionsDTO = employeePositionsDTOS.get(0);
                String organizationCode = employeePositionsDTO.getOrganizationCode();
                GenericResult<DingOrgInfoDTO> dingOrgInfoDTOGenericResult = zwddClient.getOrganizationByCode(organizationCode);
                DingOrgInfoDTO organizationByCode = dingOrgInfoDTOGenericResult.getData();
                String organizationName = organizationByCode.getOrganizationName();
                zzdInfoByMobileVO.setCompanyName(organizationName);
            }
            GenericResult<EmployeeInfoDTO> infoDTOGenericResult = zwddClient.getEmployeeByCode(employeeCode);
            EmployeeInfoDTO employeeInfoDTO = infoDTOGenericResult.getData();
            if (Objects.nonNull(employeeInfoDTO)) {
                String employeeName = employeeInfoDTO.getEmployeeName();
                zzdInfoByMobileVO.setName(employeeName);
            }
        } else {
            zzdInfoByMobileVO.setIsDingUser(false);
        }
        return zzdInfoByMobileVO;
    }
}
