package com.trade.client.enterprise.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.trade.client.consumer.domain.CustomerUser;
import com.trade.client.consumer.domain.model.LoginUserInfo;
import com.trade.client.consumer.service.CustomerMessageService;
import com.trade.client.consumer.service.CustomerUserService;
import com.trade.client.enterprise.dto.EnterpriseStatusDto;
import com.trade.client.enterprise.service.EnterpriseService;
import com.trade.client.security.utils.UserUtils;
import com.trade.common.constant.HttpStatus;
import com.trade.common.exception.ValidatorException;
import com.trade.common.utils.ConstantUtil;
import com.trade.common.utils.DateUtils;
import com.trade.common.utils.LoggerUtil;
import com.trade.common.utils.bean.BeanCopyUtils;
import com.trade.common.utils.bean.Builder;
import com.trade.common.validate.ValidatorGroup;
import com.trade.common.validate.ValidatorUtil;
import com.trade.service.DictConstants;
import com.trade.service.FileTypeEnum;
import com.trade.service.TransStruct;
import com.trade.service.filestorage.entity.BusinessRelateFile;
import com.trade.service.enterprise.domain.Enterprise;
import com.trade.service.enterprise.domain.EnterpriseChangeRecord;
import com.trade.service.enterprise.domain.EnterpriseRelatedPerson;
import com.trade.service.enterprise.dto.EnterpriseDto;
import com.trade.service.enterprise.dto.EnterpriseRelatedPersonDto;
import com.trade.service.filestorage.service.BusinessRelateFileBaseService;
import com.trade.service.enterprise.service.EnterpriseBaseService;
import com.trade.service.enterprise.service.EnterpriseChangeRecordBaseService;
import com.trade.service.enterprise.service.EnterpriseRelatedPersonBaseService;
import com.trade.service.enterprise.service.impl.EnterpriseDataConverter;
import com.trade.service.thirdparty.qichacha.dto.EcBasicDetailDto;
import com.trade.service.thirdparty.qichacha.service.QichachaService;
import com.trade.service.thirdparty.xiaotu.XiaotuConstant;
import com.trade.service.thirdparty.xiaotu.dto.RegisterEnterpriseRequest;
import com.trade.service.thirdparty.xiaotu.dto.RegisterEnterpriseResponse;
import com.trade.service.thirdparty.xiaotu.dto.RegisterUserRequest;
import com.trade.service.thirdparty.xiaotu.dto.RegisterUserResponse;
import com.trade.service.thirdparty.xiaotu.service.XiaotuRequestService;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 企业信息服务实现类
 *
 * @author hlb
 * @since 2024-05-29 15:02:09
 */
@Service("enterpriseService")
public class EnterpriseServiceImpl implements EnterpriseService {

    private static final Logger log = LoggerUtil.logger(LoggerUtil.LogFileNameEnum.SERVICES_LOG);
    @Resource
    private CustomerMessageService customerMessageService;
    @Resource
    private EnterpriseBaseService enterpriseBaseService;
    @Resource
    private EnterpriseChangeRecordBaseService enterpriseChangeRecordBaseService;
    @Resource
    private EnterpriseDataConverter enterpriseDataConverter;
    @Resource
    private BusinessRelateFileBaseService businessRelateFileBaseService;
    @Resource
    private EnterpriseRelatedPersonBaseService enterpriseRelatedPersonBaseService;
    @Resource
    private XiaotuRequestService xiaotuRequestService;
    @Resource
    private CustomerUserService customerUserService;
    @Resource
    private QichachaService qichachaService;
    @Resource
    private TransStruct transStruct;

    @Override
    public EnterpriseStatusDto queryCertificationStatus() {
        EnterpriseStatusDto enterpriseStatusDto = new EnterpriseStatusDto();
        enterpriseStatusDto.setCertificationStatus(DictConstants.CERTIFICATION_STATUS_UNSUBMITTED);
        enterpriseStatusDto.setShowAllFunctions(Boolean.FALSE);
        Long customerUserId = UserUtils.getCustomerUserId();
        EnterpriseChangeRecord record = enterpriseChangeRecordBaseService.getLatestRecord(customerUserId, null);
        if (record != null) {
            enterpriseStatusDto.setCertificationStatus(record.getCertificationStatus());
        }
        Enterprise enterprise = enterpriseBaseService.getEnterpriseByCustomerId(customerUserId);
        enterpriseStatusDto.setShowAllFunctions(enterprise != null
                && DictConstants.CERTIFICATION_STATUS_PASSED.equals(enterprise.getCertificationStatus()));
        return enterpriseStatusDto;
    }

    @Override
    public EnterpriseDto queryForUpdate() {
        Long customerUserId = UserUtils.getCustomerUserId();
        EnterpriseChangeRecord record = enterpriseChangeRecordBaseService.getLatestRecord(customerUserId, null);
        if (record == null) {
            return null;
        }
        return enterpriseDataConverter.recordToEnterpriseDto(record);
    }

    @Override
    public EnterpriseDto queryMyEnterprise() {
        Long customerUserId = UserUtils.getCustomerUserId();
        Enterprise enterprise = enterpriseBaseService.getEnterpriseByCustomerId(customerUserId);
        if (enterprise != null) {
            return enterpriseDataConverter.EnterpriseDomainToDto(enterprise);
        } else {
            return this.queryForUpdate();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveEnterprise(String operate, EnterpriseDto enterpriseDto) {
        boolean firstSubmit = firstSubmitJudge(operate, enterpriseDto);
        LoginUserInfo loginUserInfo = UserUtils.getLoginUser();
        enterpriseDto.setCustomerId(loginUserInfo.getCustomerUserId());
        enterpriseDto.setCustomerIdentifierNo(loginUserInfo.getCustomerUser().getIdentifierNo());
        if (StrUtil.isEmpty(enterpriseDto.getCountryCode())) {
            enterpriseDto.setCountryCode(DictConstants.COUNTRY_CODE_CN);
        }
        checkParams(operate, enterpriseDto);
        // 比较有无字段发生变化
        if (!isChanged(enterpriseDto)) {
            log.info("企业信息无变化，无需保存！");
            return null;
        }
        enterpriseDto.setCertificationStatus(DictConstants.CERTIFICATION_STATUS_PROCESSING);
        if (operate.equalsIgnoreCase(ConstantUtil.OPERATE_TYPE_SUBMIT)) {
            enterpriseDto.setCertificationStatus(DictConstants.CERTIFICATION_STATUS_PASSED);
            String product = matchProduct(enterpriseDto);
            enterpriseDto.setBusinessProduct(product);
            Enterprise enterprise = transStruct.transDto2Enterprise(enterpriseDto);
            enterpriseBaseService.saveOrUpdate(enterprise);
            enterpriseDto.setId(enterprise.getId());
        }
        // 保存企业变更流水
        long recordId = saveEnterpriseChangeRecord(enterpriseDto);
        enterpriseDto.setChangeRecordId(recordId);
        // 保存企业证照信息
        saveEnterprisePictures(enterpriseDto);
        // 更新企业的流水id
        enterpriseBaseService.lambdaUpdate().eq(Enterprise::getId, enterpriseDto.getId())
                .set(Enterprise::getChangeRecordId, recordId).update();
        // 保存人员（法人、实控人）信息
        saveEnterprisePersons(enterpriseDto);
        // 第一提交则注册小图用户与企业信息
        if (firstSubmit) {
            registerXiaotuUserAndEnterprise(enterpriseDto, loginUserInfo.getCustomerUser());
        }
        return enterpriseDto.getChangeRecordId();
    }

    /**
     * 判断是否是第一次提交
     * 
     * @param operate
     * @param enterpriseDto
     * @return
     */
    private boolean firstSubmitJudge(String operate, EnterpriseDto enterpriseDto) {
        boolean firstSubmit = operate.equalsIgnoreCase(ConstantUtil.OPERATE_TYPE_SUBMIT);
        if (firstSubmit) {
            Enterprise tempEnterprise = null;
            if (enterpriseDto.getId() == null) {
                tempEnterprise = enterpriseBaseService.getEnterpriseByCertNo(enterpriseDto.getCertNo());
            } else {
                tempEnterprise = enterpriseBaseService.getById(enterpriseDto.getId());
            }
            if (tempEnterprise != null) {
                enterpriseDto.setId(tempEnterprise.getId());
            }
            firstSubmit = tempEnterprise == null
                    || !DictConstants.CERTIFICATION_STATUS_PASSED.equals(tempEnterprise.getCertificationStatus());
        }
        return firstSubmit;
    }

    /**
     * 匹配企业业务类型
     * 
     * @return 业务类型
     */
    private String matchProduct(EnterpriseDto enterpriseDto) {
        if (DictConstants.EXPORT_TYPE_SELF.equals(enterpriseDto.getExportType())) {
            return DictConstants.PRODUCT_F_TRADE;
        } else if (DictConstants.EXPORT_TYPE_PROXY.equals(enterpriseDto.getExportType())) {
            return DictConstants.PRODUCT_E_TRADE;
        } else {
            return DictConstants.PRODUCT_CROSS_BORDER_TRADE;
        }
    }

    /**
     * 企业保存、提交检查参数
     *
     * @param operate 操作：保存（save）；或提交（submit）
     * @param enterpriseDto 企业信息
     */
    private void checkParams(String operate, EnterpriseDto enterpriseDto) {
        Long customerUserId = UserUtils.getCustomerUserId();
        enterpriseDto.setCustomerId(customerUserId);
        if (StrUtil.isBlank(enterpriseDto.getCountryCode())) {
            enterpriseDto.setCountryCode(DictConstants.COUNTRY_CODE_CN);
        }
        if (enterpriseDto.getContactPerson() != null
                && StrUtil.isNotEmpty(enterpriseDto.getContactPerson().getEmail())) {
            if (StrUtil.isEmpty(enterpriseDto.getEmailAuthCode())) {
                throw new ValidatorException(HttpStatus.ERROR, "请先获取邮箱验证码！");
            }
            // 邮箱验证码校验
            customerMessageService.checkEmailAuthCode(enterpriseDto.getContactPerson().getEmail(),
                    enterpriseDto.getEmailAuthCode());
        }
        if (operate.equals(ConstantUtil.OPERATE_TYPE_SAVE)) {
            ValidatorUtil.validator(ValidatorGroup.ValidatorType.ADD, enterpriseDto);
            return;
        }
        ValidatorUtil.validator(ValidatorGroup.ValidatorType.SUBMIT, enterpriseDto);
        if (DictConstants.SYS_YES.equals(enterpriseDto.getSameRegisterAndBusinessAddress())
                && StrUtil.isEmpty(enterpriseDto.getBusinessAddress())) {
            throw new ValidatorException(HttpStatus.ERROR, "实际经营地址不能为空！");
        }
        ValidatorUtil.validator(ValidatorGroup.ValidatorType.SUBMIT, enterpriseDto.getContactPerson());
        ValidatorUtil.validator(ValidatorGroup.ValidatorType.SUBMIT, enterpriseDto.getLegalPerson());
        if (Objects.equals(enterpriseDto.getLegalPerson().getIsControl(), DictConstants.SYS_NO)) {
            if (enterpriseDto.getControlPerson() == null) {
                throw new ValidatorException(HttpStatus.ERROR, "企业实控人信息不能为空！");
            } else {
                ValidatorUtil.validator(ValidatorGroup.ValidatorType.SUBMIT, enterpriseDto.getControlPerson());
            }
        } else {
            enterpriseDto.setControlPerson(null);
        }
        if (StrUtil.isEmpty(enterpriseDto.getContactPerson().getEmail())) {
            throw new ValidatorException(HttpStatus.ERROR, "联系人邮箱不能为空！");
        }
        if (Objects.equals(enterpriseDto.getExportType(), DictConstants.EXPORT_TYPE_PROXY)
                && StrUtil.isEmpty(enterpriseDto.getProxyDistrictCode())) {
            throw new ValidatorException(HttpStatus.ERROR, "代理公司所属地区不能为空！");
        }
    }

    /**
     * 检查本次修改是否有变化
     *
     * @param enterpriseDto
     * @return
     */
    private boolean isChanged(EnterpriseDto enterpriseDto) {
        Long customerUserId = UserUtils.getCustomerUserId();
        EnterpriseChangeRecord record = enterpriseChangeRecordBaseService.getLatestRecord(customerUserId, null);
        if (record == null) {
            return true;
        }
        if (!StrUtil.equals(record.getEnterpriseType(), enterpriseDto.getEnterpriseType())) {
            return true;
        }
        if (!StrUtil.equals(record.getName(), enterpriseDto.getName())) {
            return true;
        }
        if (!StrUtil.equals(record.getCertNo(), enterpriseDto.getCertNo())) {
            return true;
        }
        if (!StrUtil.equals(record.getRegistrationNumber(), enterpriseDto.getRegistrationNumber())) {
            return true;
        }
        if (!StrUtil.equals(record.getCustomsEnterpriseCode(), enterpriseDto.getCustomsEnterpriseCode())) {
            return true;
        }
        if (!StrUtil.equals(record.getTaxNo(), enterpriseDto.getTaxNo())) {
            return true;
        }
        if (!Objects.equals(DateUtils.dateTime(record.getEstablishDate()),
                DateUtils.dateTime(enterpriseDto.getEstablishDate()))) {
            return true;
        }
        if ((record.getRegisterCapital() == null && enterpriseDto.getRegisterCapital() != null)
                || (record.getRegisterCapital() != null && enterpriseDto.getRegisterCapital() == null)
                || (record.getRegisterCapital() != null && enterpriseDto.getRegisterCapital() != null
                        && record.getRegisterCapital().compareTo(enterpriseDto.getRegisterCapital()) != 0)) {
            return true;
        }
        if (!StrUtil.equals(record.getRegisterAddress(), enterpriseDto.getRegisterAddress())) {
            return true;
        }
        if (!StrUtil.equals(record.getBusinessAddress(), enterpriseDto.getBusinessAddress())) {
            return true;
        }
        if (!StrUtil.equals(record.getSameRegisterAndBusinessAddress(),
                enterpriseDto.getSameRegisterAndBusinessAddress())) {
            return true;
        }
        if (!StrUtil.equals(record.getExportType(), enterpriseDto.getExportType())) {
            return true;
        }
        if (!StrUtil.equals(record.getProxyDistrictCode(), enterpriseDto.getProxyDistrictCode())) {
            return true;
        }
        // 证照信息是否变更
        List<BusinessRelateFile> bizObjFiles = businessRelateFileBaseService.getBizObjFiles(record.getId(),
                ConstantUtil.ENTERPRISE_ACCESS, null);
        for (BusinessRelateFile businessRelateFile : bizObjFiles) {
            if (StrUtil.equals(businessRelateFile.getFileType(), FileTypeEnum.IDENTITY_CARD_FRONT.getCode())
                    && enterpriseDto.getLegalPerson() != null && !Objects.equals(businessRelateFile.getFileId(),
                            enterpriseDto.getLegalPerson().getIdCardFront().getId())) {
                return true;
            } else if (StrUtil.equals(businessRelateFile.getFileType(), FileTypeEnum.IDENTITY_CARD_BACK.getCode())
                    && enterpriseDto.getLegalPerson() != null && !Objects.equals(businessRelateFile.getFileId(),
                            enterpriseDto.getLegalPerson().getIdCardBack().getId())) {
                                return true;
                            } else
                if (StrUtil.equals(businessRelateFile.getFileType(), FileTypeEnum.IDENTITY_CARD_FRONT.getCode())
                        && enterpriseDto.getControlPerson() != null && !Objects.equals(businessRelateFile.getFileId(),
                                enterpriseDto.getControlPerson().getIdCardFront().getId())) {
                                    return true;
                                } else
                    if (StrUtil.equals(businessRelateFile.getFileType(), FileTypeEnum.IDENTITY_CARD_BACK.getCode())
                            && enterpriseDto.getControlPerson() != null
                            && !Objects.equals(businessRelateFile.getFileId(),
                                    enterpriseDto.getControlPerson().getIdCardBack().getId())) {
                                        return true;
                                    } else
                        if (StrUtil.equals(businessRelateFile.getFileType(), FileTypeEnum.IDENTITY_CARD_FRONT.getCode())
                                && enterpriseDto.getContactPerson() != null
                                && !Objects.equals(businessRelateFile.getFileId(),
                                        enterpriseDto.getContactPerson().getIdCardFront().getId())) {
                                            return true;
                                        } else
                            if (StrUtil.equals(businessRelateFile.getFileType(),
                                    FileTypeEnum.IDENTITY_CARD_BACK.getCode())
                                    && enterpriseDto.getContactPerson() != null
                                    && !Objects.equals(businessRelateFile.getFileId(),
                                            enterpriseDto.getContactPerson().getIdCardBack().getId())) {
                                                return true;
                                            } else
                                if (StrUtil.equals(businessRelateFile.getFileType(),
                                        FileTypeEnum.BUSINESS_LICENSE.getCode())
                                        && !Objects.equals(businessRelateFile.getFileId(),
                                                enterpriseDto.getBusinessLicense().getId())) {
                                                    return true;
                                                }
        }
        // 人员信息是否变更
        if (isPersonBasicInfoChanged(enterpriseDto.getLegalPerson(), record)) {
            return true;
        }
        if (isPersonBasicInfoChanged(enterpriseDto.getControlPerson(), record)) {
            return true;
        }
        if (isPersonBasicInfoChanged(enterpriseDto.getContactPerson(), record)) {
            return true;
        }
        return false;
    }

    /**
     * 检查人员基本信息是否有变化
     *
     * @param personDto
     */
    private boolean isPersonBasicInfoChanged(EnterpriseRelatedPersonDto personDto, EnterpriseChangeRecord record) {
        if (personDto == null) {
            return false;
        }
        if (record == null) {
            return true;
        }
        List<EnterpriseRelatedPerson> persons = enterpriseRelatedPersonBaseService
                .getPersonsByChangeRecordId(record.getId());
        if (CollUtil.isEmpty(persons)) {
            return true;
        }
        EnterpriseRelatedPerson enterpriseRelatedPerson = persons.stream()
                .filter(p -> Objects.equals(p.getIsAuthorizedPerson(), personDto.getIsAuthorizedPerson())
                        && Objects.equals(p.getIsLegalPerson(), personDto.getIsLegalPerson())
                        && Objects.equals(p.getIsControl(), personDto.getIsControl()))
                .collect(Collectors.toList()).stream().findFirst().orElse(null);
        if (enterpriseRelatedPerson == null) {
            return true;
        }
        if (!StrUtil.equals(personDto.getName(), personDto.getName())) {
            return true;
        }
        if (!StrUtil.equals(personDto.getEmail(), personDto.getEmail())) {
            return true;
        }
        if (!StrUtil.equals(personDto.getMobile(), personDto.getMobile())) {
            return true;
        }
        if (!StrUtil.equals(personDto.getPersonalCertNo(), personDto.getPersonalCertNo())) {
            return true;
        }
        return false;
    }

    /**
     * 保存企业变更记录
     *
     * @param enterpriseDto
     * @return
     */
    private long saveEnterpriseChangeRecord(EnterpriseDto enterpriseDto) {
        EnterpriseChangeRecord record = transStruct.transEnterpriseDto2EnterpriseChangeRecord(enterpriseDto);
        if (record == null) {
            throw new ValidatorException(HttpStatus.ERROR, "企业变更记录保存失败！");
        }
        enterpriseChangeRecordBaseService.save(record);
        return record.getId();
    }

    /**
     * 保存企业证件信息
     *
     * @param enterpriseDto
     */
    private void saveEnterprisePictures(EnterpriseDto enterpriseDto) {
        List<BusinessRelateFile> enterprisePictures = new ArrayList<>();
        if (enterpriseDto.getBusinessLicense() != null) {
            BusinessRelateFile businessLicense = Builder.of(BusinessRelateFile.class)
                    .with(BusinessRelateFile::setBelongId, enterpriseDto.getChangeRecordId())
                    .with(BusinessRelateFile::setBelongType, ConstantUtil.ENTERPRISE_ACCESS)
                    .with(BusinessRelateFile::setFileType, FileTypeEnum.BUSINESS_LICENSE.getCode())
                    .with(BusinessRelateFile::setFileId, enterpriseDto.getBusinessLicense().getId()).build();
            enterprisePictures.add(businessLicense);
        }
        if (CollUtil.isNotEmpty(enterprisePictures)) {
            businessRelateFileBaseService.addBusinessRelateFiles(enterprisePictures);
        }
    }

    /**
     * 保存企业人员信息
     *
     * @param enterpriseDto
     */
    private void saveEnterprisePersons(EnterpriseDto enterpriseDto) {
        saveEnterprisePersons(enterpriseDto.getLegalPerson(), enterpriseDto.getChangeRecordId());
        saveEnterprisePersons(enterpriseDto.getControlPerson(), enterpriseDto.getChangeRecordId());
        saveEnterprisePersons(enterpriseDto.getContactPerson(), enterpriseDto.getChangeRecordId());
    }

    private void saveEnterprisePersons(EnterpriseRelatedPersonDto personDto, Long changeRecordId) {
        if (personDto != null) {
            EnterpriseRelatedPerson person = transStruct.transEnterpriseRelatedPerson2Dto(personDto);
            person.setEnterpriseChangeRecordId(changeRecordId);
            if (StrUtil.isBlank(person.getCountryCode())) {
                person.setCountryCode(DictConstants.COUNTRY_CODE_CN);
            }
            if (StrUtil.isBlank(person.getPersonalCertType())) {
                person.setPersonalCertType(DictConstants.PERSONAL_CERT_TYPE_CN_IDCARD);
            }
            enterpriseRelatedPersonBaseService.save(person);
            List<BusinessRelateFile> personFiles = new ArrayList<>();
            if (personDto.getIdCardFront() != null) {
                BusinessRelateFile idCardFront = Builder.of(BusinessRelateFile.class)
                        .with(BusinessRelateFile::setBelongId, person.getId())
                        .with(BusinessRelateFile::setBelongType, ConstantUtil.ENTERPRISE_PERSON)
                        .with(BusinessRelateFile::setFileType, FileTypeEnum.IDENTITY_CARD_FRONT.getCode())
                        .with(BusinessRelateFile::setFileId, personDto.getIdCardFront().getId()).build();
                personFiles.add(idCardFront);
            }
            if (personDto.getIdCardBack() != null) {
                BusinessRelateFile idCardBack = Builder.of(BusinessRelateFile.class)
                        .with(BusinessRelateFile::setBelongId, person.getId())
                        .with(BusinessRelateFile::setBelongType, ConstantUtil.ENTERPRISE_PERSON)
                        .with(BusinessRelateFile::setFileType, FileTypeEnum.IDENTITY_CARD_BACK.getCode())
                        .with(BusinessRelateFile::setFileId, personDto.getIdCardBack().getId()).build();
                personFiles.add(idCardBack);
            }
            if (CollUtil.isNotEmpty(personFiles)) {
                businessRelateFileBaseService.addBusinessRelateFiles(personFiles);
            }
        }
    }

    /**
     * 注册小图用户和企业
     * 
     * @param enterpriseDto
     * @param customerUser
     * @return
     */
    private void registerXiaotuUserAndEnterprise(EnterpriseDto enterpriseDto, CustomerUser customerUser) {
        // 注册小图用户
        RegisterUserRequest registerUserRequest = new RegisterUserRequest();
        registerUserRequest.setXm(customerUser.getIdentifierNo());
        registerUserRequest.setYddh(customerUser.getPhoneNumber());
        registerUserRequest.setJsDm(getXtUserRole(enterpriseDto));
        RegisterUserResponse registerUserResponse = xiaotuRequestService.registerUser(registerUserRequest);
        customerUserService.bindXtUserId(customerUser.getId(), registerUserResponse.getYhuuid1());
        // 企业信息注册
        RegisterEnterpriseRequest registerEnterpriseRequest = new RegisterEnterpriseRequest();
        registerEnterpriseRequest.setHgqyDm(enterpriseDto.getCustomsEnterpriseCode());
        registerEnterpriseRequest.setNsrmc(enterpriseDto.getName());
        registerEnterpriseRequest.setNsrsbh(enterpriseDto.getTaxNo());
        registerEnterpriseRequest.setShxydm(enterpriseDto.getCertNo());
        registerEnterpriseRequest.setDqcode(getXtDqCode(enterpriseDto));
        registerEnterpriseRequest.setCktsqylxDm(enterpriseDto.getEnterpriseType());
        registerEnterpriseRequest.setYhuuid1(registerUserResponse.getYhuuid1());
        registerEnterpriseRequest.setHstqysqbz(DictConstants.SYS_NO);
        RegisterEnterpriseResponse registerEnterpriseResponse = xiaotuRequestService
                .registerEnterprise(registerEnterpriseRequest);
        // 绑定小图企业ID
        enterpriseBaseService.lambdaUpdate().set(Enterprise::getXtEid, registerEnterpriseResponse.getSbqyuuid())
                .eq(Enterprise::getId, enterpriseDto.getId());
    }

    private String getXtUserRole(EnterpriseDto enterpriseDto) {
        switch (enterpriseDto.getEnterpriseType()) {
            case DictConstants.ENTERPRISE_TYPE_PRODUCE:
                return RegisterUserRequest.SCAntdQX;
            case DictConstants.ENTERPRISE_TYPE_PRODUCE_EXTERNAL:
                return RegisterUserRequest.QTSCAntd;
            case DictConstants.ENTERPRISE_TYPE_EXTERNAL_TRADE:
                return RegisterUserRequest.WMAntdQX;
            default:
                return RegisterUserRequest.QTAntdQX;
        }
    }

    /**
     * 获取小图地区代码
     * 
     * @param enterpriseDto
     * @return
     */
    private String getXtDqCode(EnterpriseDto enterpriseDto) {
        EcBasicDetailDto ecBasicDetailDto = qichachaService.getBasicDetailsByName(enterpriseDto.getName());
        if (ecBasicDetailDto == null) {
            throw new ValidatorException(HttpStatus.ERROR, "企业不存在！");
        }
        String result = XiaotuConstant.XT_DISTRICT_CODE_MAP.get(ecBasicDetailDto.getArea().getCity());
        if (StrUtil.isEmpty(result)) {
            result = XiaotuConstant.XT_DISTRICT_CODE_MAP.get(ecBasicDetailDto.getArea().getProvince());
        }
        return result;
    }
}
