package com.crm.manager.service.impl;

import com.alibaba.fastjson.JSON;
import com.crm.manager.dao.mapper.UserEntryMapper;
import com.crm.manager.dao.repository.UserEntryRepository;
import com.crm.manager.dao.repository.UserReferralRepository;
import com.crm.manager.property.GooleUserAdminApiProperty;
import com.crm.manager.property.LarkApiProperty;
import com.crm.manager.service.*;
import com.crm.manager.service.activity.AccountApplyFeignService;
import com.crm.manager.util.ChineseToSpell;
import com.crm.rely.backend.core.constant.*;
import com.crm.rely.backend.core.dto.base.BaseResultDto;
import com.crm.rely.backend.core.dto.base.PageDto;
import com.crm.rely.backend.core.dto.base.ResultWithPagerDto;
import com.crm.rely.backend.core.dto.user.info.UserEntrySearchListDto;
import com.crm.rely.backend.core.entity.account.apply.AccountApplyAddEntity;
import com.crm.rely.backend.core.entity.base.SingleLongEntity;
import com.crm.rely.backend.core.entity.custom.kyc.CustomKycVerifyRecodeEntity;
import com.crm.rely.backend.core.entity.system.email.SysEmailSendEntity;
import com.crm.rely.backend.core.entity.user.info.*;
import com.crm.rely.backend.core.enums.SalesType;
import com.crm.rely.backend.core.pojo.table.*;
import com.crm.rely.backend.exception.ServiceException;
import com.crm.rely.backend.service.EmailService;
import com.crm.rely.backend.util.*;
import com.google.common.base.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class UserEntryServiceImpl implements UserEntryService {

    @Autowired
    private UserEntryRepository userEntryRepository;
    @Autowired
    private UserEntryMapper userEntryMapper;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private EmailService emailService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private UserReferralRepository userReferralRepository;
    @Autowired
    private KycFeignService kycFeignService;
    @Autowired
    private CustomInfoService customInfoService;
    @Autowired
    private AccountApplyFeignService accountApplyFeignService;
    @Autowired
    private Environment environment;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(UserEntryAddEntity entity) throws ServiceException {
        if (!Strings.isNullOrEmpty(entity.getReferralCode())) {
            UserReferralTable userReferralTable =
                    userReferralRepository.findFirstByReferralCode(entity.getReferralCode());
            if (null == userReferralTable) {
                throw ServiceException.exception(Constants.REFERRAL_ERROR);
            }

            if (null == entity.getHareId()) {
                userReferralTable.setReferralNum(userReferralTable.getReferralNum() + 1);
                userReferralRepository.save(userReferralTable);
            }
        }

        UserEntryTable table = new UserEntryTable();
        BeanUtils.copyProperties(entity, table);
        table.setEntryStatus(1);
        table.setManageStatus(1);
        table.setVerifyStatus(0);
        table.setFirstName(ChineseToSpell.getPingYin(entity.getFirstName()));
        table.setLastName(ChineseToSpell.getPingYin(entity.getLastName()));
        table.setEnglishName(Strings.isNullOrEmpty(table.getEnglishName()) ?
                ChineseToSpell.getPingYin(table.getFirstName() + " " + table.getLastName()) : entity.getEnglishName());
        table.setSerial(UUIDUtil.getUUID());
        table.setGoogleEmail(Strings.isNullOrEmpty(table.getGoogleEmail()) ? table.getGoogleEmail() :
                getGooglemail(entity.getFirstName(), entity.getLastName(), entity.getEnglishName()));
        userEntryRepository.save(table);

        SysConfigTable sysConfigTable = sysConfigService.getByCode(ConfigConstants.JOB_ONBOARDING_INFO_LINK);
        if (sysConfigTable == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
        String url = sysConfigTable.getValue() + "/" + table.getSerial();
        table.setLinkUrl(url);
        if (!Strings.isNullOrEmpty(table.getEmail())) {
            sendUserEntryUrlEmail(table);
        }
        userEntryRepository.save(table);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(UserEntryUpdateEntity entity) throws Exception {
        UserEntryTable table = userEntryRepository.findFirstBySerial(entity.getEntry());
        if (table == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        if (1 != table.getEntryStatus()) {
            throw ServiceException.exception("个人信息已提交");
        }

        if (Constants.MT4.equals(entity.getSalaryPlatform()) || Constants.MT5.equals(entity.getSalaryPlatform())) {
            /*if (Strings.isNullOrEmpty(entity.getLogin())) {
                throw ServiceException.exception(Constants.LOGIN_NOT_NULL_ERROR);
            }*/
        } else {
            if (Strings.isNullOrEmpty(entity.getBankCode()) || Strings.isNullOrEmpty(entity.getBankName()) || Strings.isNullOrEmpty(entity.getAccountHoldersName()) || Strings.isNullOrEmpty(entity.getBankAccountNumber())) {
                throw ServiceException.exception("请完善银行信息");
            }
        }

        if (0 == table.getVerifyStatus() && (!entity.getEntryFile().equals(table.getEntryFile()) || !entity.getCardType().equals(table.getCardType()))) {
            CustomKycVerifyRecodeEntity customKycVerifyRecodeEntity = new CustomKycVerifyRecodeEntity();
            customKycVerifyRecodeEntity.setExternalUserId(table.getSerial());
            customKycVerifyRecodeEntity.setCountry("CN");
            customKycVerifyRecodeEntity.setConfig(ConfigConstants.ENTRY_VERIFY_KYC_PROPERTY);

            if (Strings.isNullOrEmpty(table.getApplicantId())) {
                customKycVerifyRecodeEntity.setApplicantId(kycFeignService.createApplicant(customKycVerifyRecodeEntity));
                table.setApplicantId(customKycVerifyRecodeEntity.getApplicantId());
            } else {
                customKycVerifyRecodeEntity.setApplicantId(table.getApplicantId());
            }

            if (!Strings.isNullOrEmpty(table.getApplicantId())) {
                customKycVerifyRecodeEntity.setVerifyId(table.getId());
                customKycVerifyRecodeEntity.setVerifyType(2);
                customKycVerifyRecodeEntity.setVerifyFile(entity.getEntryFile());
                customKycVerifyRecodeEntity.setCardType(entity.getCardType());
                kycFeignService.uploadImage(customKycVerifyRecodeEntity);
            }
        }
        getUserEntryTable(table, entity);
        table.setEntryStatus(2);
        userEntryRepository.save(table);

        SysConfigTable sysConfigTable = sysConfigService.getByCode(ConfigConstants.ONBOARDED_EMAIL);
        if (sysConfigTable == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }

        //入职个人信息核验通知
        sendUserEntryVerifyEmail(sysConfigTable, table);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateHrAuditStatus(UserEntryUpdateStatusEntity entity) throws Exception {
        UserEntryTable table = userEntryRepository.findFirstById(entity.getId());
        if (table == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        if (1 == table.getEntryStatus()) {
            throw ServiceException.exception("个人信息未填写");
        }
        if (2 != table.getEntryStatus()) {
            throw ServiceException.exception("个人信息已核验");
        }
        /*if (3 == entity.getEntryStatus() && null == entity.getUserId()) {
            throw ServiceException.exception("归属团队不能为空");
        }*/

        table.setEntryStatus(4 == entity.getEntryStatus() ? 1 : entity.getEntryStatus());
        table.setManageStatus(3 == entity.getEntryStatus() ? 2 : table.getManageStatus());
        table.setUserId(entity.getUserId());
        table.setUserName(entity.getUserName());
        table.setUserIbNo(entity.getUserIbNo());
        table.setReferralCode(entity.getReferralCode());
        table.setEntryDesc(entity.getEntryDesc());
        table.setGoogleEmail(entity.getGoogleEmail());
        table.setSalary(entity.getSalary());
        table.setEntryDate(entity.getEntryDate());
        table.setAuditTime(new Date());
        table.setRoleId(entity.getRoleId());
        table.setPid(entity.getPid());
        table.setSalesType(entity.getSalesType());
        table.setLeaderId(entity.getLeaderId());
        table.setLogin(entity.getLogin());
        userEntryRepository.save(table);

        if (3 == entity.getEntryStatus()) {
            SysConfigTable sysConfigTable = sysConfigService.getByCode(ConfigConstants.HR_AUDIT_SUCCESS_EMAIL);
            if (sysConfigTable == null) {
                throw ServiceException.exception(Constants.SYSTEM_ERROR);
            }

            //入职个人信息核验通知
            sendUserEntryHrVerifyEmail(sysConfigTable, table);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(UserEntryUpdateStatusEntity entity) throws Exception {
        if (Strings.isNullOrEmpty(entity.getGoogleEmail())) {
            throw ServiceException.exception("GoogleEmail not null");
        }
        UserEntryTable table = userEntryRepository.findFirstById(entity.getId());
        if (table == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        if (2 != table.getManageStatus()) {
            throw ServiceException.exception("请先通过hr审核");
        }

        table.setManageStatus(entity.getManageStatus());
        table.setEntryDesc(entity.getEntryDesc());
        table.setSalary(entity.getSalary());
        table.setGoogleEmail(entity.getGoogleEmail());
        table.setEntryDate(entity.getEntryDate());
        table.setGroupEmail(entity.getGroupEmail());
        table.setAuditTime(new Date());

        if (3 == table.getManageStatus()) {
            table.setRoleId(entity.getRoleId());
            table.setPid(entity.getPid());
            table.setSalesType(entity.getSalesType());
            table.setLeaderId(entity.getLeaderId());

            //推广成功次数添加
            if (!Strings.isNullOrEmpty(table.getReferralCode())) {
                UserReferralTable userReferralTable =
                        userReferralRepository.findFirstByReferralCode(table.getReferralCode());
                if (null != userReferralTable) {
                    userReferralTable.setReferralSuccessNum(userReferralTable.getReferralSuccessNum() + 1);
                    userReferralRepository.save(userReferralTable);
                }
            }

            table.setGooglePassword(GetRandom.getRandomPasswordString());
            addGoogleemail(table);

            //添加账户
            UserInfoTable userInfoTable = addUser(table, entity);

            //添加个人中心
            CustomInfoTable customInfoTable = customInfoService.addCustom(table,userInfoTable);

            //添加交易账户申请
            addAccountApply(customInfoTable,userInfoTable.getId());

            //lark账户添加地址邮件发送
            /*SysConfigTable larkSysConfigTable = sysConfigService.getByCode(ConfigConstants.LARK_API_PROPERTY);
            if (larkSysConfigTable == null) {
                throw ServiceException.exception(Constants.SYSTEM_ERROR);
            }
            LarkApiProperty larkProperty = JSON.parseObject(larkSysConfigTable.getValue(), LarkApiProperty.class);
            sendUserEntryAddLarkEmail(table, larkProperty);*/

            SysConfigTable emailConfigTable = sysConfigService.getByCode(ConfigConstants.ONBOARDED_SUCCESS_EMAIL);
            if (emailConfigTable == null) {
                throw ServiceException.exception(Constants.SYSTEM_ERROR);
            }
            //入职人员核验通过通知(管理人员)邮件发送
            sendUserEntryVerifySuccessEmail(emailConfigTable, table, entity.getIbNo());

            //入职人员核验通过通知（入职人员）邮件发送
            sendUserEntryVerifySuccessPersonEmail(emailConfigTable, table, entity.getIbNo());
        }

        userEntryRepository.save(table);
    }

    @Transactional(rollbackFor = Exception.class)
    public void addGoogleemail(UserEntryTable table) throws Exception {
        for (int i = 0; i < environment.getActiveProfiles().length; i++) {
            if (environment.getActiveProfiles()[i].equals("prod")) {
                SysConfigTable gogleConfigTable =
                        sysConfigService.getByCode(ConfigConstants.GOOGLE_USER_ADMIN_API_PROPERTY);
                if (gogleConfigTable == null) {
                    throw ServiceException.exception(Constants.SYSTEM_ERROR);
                }

                //谷歌账户添加
                GooleUserAdminApiProperty property = JSON.parseObject(gogleConfigTable.getValue(),
                        GooleUserAdminApiProperty.class);
                String accessToken = GoogleAdminAPIHttp.getAccessToken(property.getAdminEmail(),
                        property.getClientEmail(), property.getPrivateKey());

                if (GoogleAdminAPIHttp.getUser(accessToken, table.getGoogleEmail()) != null) {
                    throw ServiceException.exception("GoogleEmail is already in use");
                }

                Integer resposeCode = GoogleAdminAPIHttp.createUser(accessToken, table.getGoogleEmail(),
                        table.getFirstName(), table.getLastName(), table.getGooglePassword(),
                        Strings.isNullOrEmpty(table.getPhoneNumbe()) ? null :
                                "+" + table.getCallingCode() + " " + table.getPhoneNumbe(), table.getEmail());
                if (Constants.SUCCESS_CODE != resposeCode) {
                    throw ServiceException.exception("create GoogleEmail is error");
                }

                if (!Strings.isNullOrEmpty(table.getGroupEmail())) {
                    String[] emails = table.getGroupEmail().split(",");
                    for (String email : emails) {
                        Integer groupCode = GoogleAdminAPIHttp.addUserToGroup(accessToken, email, table.getGoogleEmail(),
                                null);
                        if (Constants.SUCCESS_CODE != groupCode) {
                            throw ServiceException.exception("create GoogleEmail Group is error");
                        }
                    }
                }
                break;
            }
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public UserInfoTable addUser(UserEntryTable table, UserEntryUpdateStatusEntity updateEntity) throws Exception {
        if (!Constants.MT4.equals(updateEntity.getSalaryPlatform()) && !Constants.MT5.equals(updateEntity.getSalaryPlatform())) {
            updateEntity.setSalaryPlatform(null);
        }
        UserInfoAddEntity entity = new UserInfoAddEntity();
        BeanUtils.copyProperties(updateEntity, entity);
        entity.setEmail(table.getGoogleEmail());
        entity.setUsername(table.getGoogleEmail());
        entity.setName(table.getFirstName() + " " + table.getLastName());
        entity.setEntryDate(table.getEntryDate());
        entity.setCountry(table.getCountry());
        entity.setGroupEmail(table.getGroupEmail());
        //密码
        entity.setPassword(MD5Util.getMD5(table.getGooglePassword()));
        if (entity.getCommissionApproval() == null) {
            entity.setCommissionApproval(0);
        }
        if (entity.getIpLimit() == null) {
            entity.setIpLimit(0);
        }
        if (entity.getHide() == null) {
            entity.setHide(0);
        }
        //如果登录名不填 默认为邮箱
        if (Strings.isNullOrEmpty(entity.getUsername())) {
            entity.setUsername(entity.getEmail());
        }

        //如果不填是否禁用 默认为1 可以登录
        if (entity.getValid() == null) {
            entity.setValid(1);
        }

        if (entity.getSalesType() == null) {
            entity.setSalesType(SalesType.COMMON_SALES.getCode());
        }

        return userInfoService.add(entity);
    }

    @Transactional(rollbackFor = Exception.class)
    public void addAccountApply(CustomInfoTable customInfoTable,Long userId) throws Exception {
        AccountApplyAddEntity accountApplyAddEntity = new AccountApplyAddEntity();
        accountApplyAddEntity.setCustomId(customInfoTable.getId());
        accountApplyAddEntity.setCId(customInfoTable.getCId());
        accountApplyAddEntity.setPassword("Cwg123456!");
        accountApplyAddEntity.setPlatform(Constants.MT5);
        accountApplyAddEntity.setComPoint(customInfoTable.getComPoint());
        accountApplyAddEntity.setLeverage(400);
        accountApplyAddEntity.setCurrency(Constants.SYMBOL_USD);
        accountApplyAddEntity.setType(7l);
        accountApplyAddEntity.setAgentId(userId);
        accountApplyAddEntity.setNote("销售入职userId:"+userId);
        accountApplyAddEntity.setCountry(customInfoTable.getCountry());
        accountApplyAddEntity.setFirstName(customInfoTable.getFirstName());
        accountApplyAddEntity.setLastName(customInfoTable.getLastName());
        BaseResultDto dto = accountApplyFeignService.add(accountApplyAddEntity);
        if(dto.getCode() != 200){
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
    }

    private void sendUserEntryVerifyEmail(SysConfigTable sysConfigTable, UserEntryTable table) throws ServiceException {
        //构建map 用于后面邮件模版替换
        Map<String, String> map = new HashMap<>(14);

        map.put(MapConstants.DATE_TIME, DateUtil.formatTime(new Date()));
        map.put(MapConstants.EMAIL, table.getEmail());
        map.put(MapConstants.V_FIRST_NAME_V, table.getFirstName());
        map.put(MapConstants.V_LAST_NAME_V, table.getLastName());
        map.put(MapConstants.V_ENGLISH_NAME_V, Strings.isNullOrEmpty(table.getEnglishName()) ? "" :
                table.getEnglishName());
        map.put(MapConstants.V_PHONE_NUMBER_V, Strings.isNullOrEmpty(table.getPhoneNumbe()) ? "" :
                "+" + table.getCallingCode() + " " + table.getPhoneNumbe());
        map.put(MapConstants.V_SALARY_PLATFORM_V, "BANK_ACCOUNT".equals(table.getSalaryPlatform()) ? "银行账户" :
                table.getSalaryPlatform());
        map.put(MapConstants.V_SALARY_LOGIN_V, Strings.isNullOrEmpty(table.getLogin()) ? "" : table.getLogin());
        map.put(MapConstants.V_SALARY_V, String.valueOf(table.getSalary()));
        map.put(MapConstants.V_BANK_NAME_V, Strings.isNullOrEmpty(table.getBankName()) ? "" : table.getBankName());
        map.put(MapConstants.V_ACCOUNT_HOLDERS_NAME_V, Strings.isNullOrEmpty(table.getAccountHoldersName()) ? "" :
                table.getAccountHoldersName());
        map.put(MapConstants.V_BANK_ACCOUNT_NUMBER_V, Strings.isNullOrEmpty(table.getBankAccountNumber()) ? "" :
                table.getBankAccountNumber());
        map.put(MapConstants.V_BANK_CODE_V, Strings.isNullOrEmpty(table.getBankCode()) ? "" : table.getBankCode());
        map.put(MapConstants.V_REFERRAL_CODE_V, Strings.isNullOrEmpty(table.getReferralCode()) ? "" :
                table.getReferralCode());

        SysEmailSendEntity sysEmailSendEntity = new SysEmailSendEntity();
        sysEmailSendEntity.setSubject("CWG VERIFY PERSONAL INFORMATION FOR EMPLOYMENT");
        sysEmailSendEntity.setEmailSendEnum(EmailSendEnum.VERIFY_PERSONAL_INFORMATION_FOR_EMPLOYMENT);
        sysEmailSendEntity.setMap(map);
        sysEmailSendEntity.setTemplateName(SystemEmailCodeConstants.VERIFY_PERSONAL_INFORMATION_FOR_EMPLOYMENT);
        sysEmailSendEntity.setUsers(sysConfigTable.getValue());

        try {
            emailService.sendEmail(sysEmailSendEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendUserEntryUrlEmail(UserEntryTable table) throws ServiceException {
        //构建map 用于后面邮件模版替换
        Map<String, String> map = new HashMap<>(3);

        map.put(MapConstants.NAME, table.getFirstName() + table.getLastName());
        map.put(MapConstants.V_INFORMATION_LINKURL_V, table.getLinkUrl());
        map.put(MapConstants.DATE_TIME, DateUtil.formatTime(new Date()));

        SysEmailSendEntity sysEmailSendEntity = new SysEmailSendEntity();
        sysEmailSendEntity.setSubject("CWG INFORMATION");
        sysEmailSendEntity.setEmailSendEnum(EmailSendEnum.FILL_IN_PERSONAL_INFORMATION_FOR_EMPLOYMENT);
        sysEmailSendEntity.setMap(map);

        if (CountryUtil.isCN(table.getCountry())) {
            sysEmailSendEntity.setTemplateName(SystemEmailCodeConstants.FILL_IN_PERSONAL_INFORMATION_FOR_EMPLOYMENT_CN);
        } else {
            sysEmailSendEntity.setTemplateName(SystemEmailCodeConstants.FILL_IN_PERSONAL_INFORMATION_FOR_EMPLOYMENT_EN);
        }
        sysEmailSendEntity.setUsers(table.getEmail());

        try {
            emailService.sendEmail(sysEmailSendEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendUserEntryAddLarkEmail(UserEntryTable table, LarkApiProperty larkProperty) throws ServiceException {
        //构建map 用于后面邮件模版替换
        Map<String, String> map = new HashMap<>(3);

        map.put(MapConstants.NAME, table.getFirstName() + table.getLastName());
        map.put(MapConstants.V_INVITATION_LINK_V, larkProperty.getInvitationLink());
        map.put(MapConstants.DATE_TIME, DateUtil.formatTime(new Date()));

        SysEmailSendEntity sysEmailSendEntity = new SysEmailSendEntity();
        sysEmailSendEntity.setSubject("CWG ADD LARK");
        sysEmailSendEntity.setEmailSendEnum(EmailSendEnum.ADD_LARK_SEND);
        sysEmailSendEntity.setMap(map);

        if (CountryUtil.isCN(table.getCountry())) {
            sysEmailSendEntity.setTemplateName(SystemEmailCodeConstants.ADD_LARK_SEND_CN);
        } else {
            sysEmailSendEntity.setTemplateName(SystemEmailCodeConstants.ADD_LARK_SEND_EN);
        }

        sysEmailSendEntity.setUsers(table.getGoogleEmail());
        try {
            emailService.sendEmail(sysEmailSendEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendUserEntryVerifySuccessEmail(SysConfigTable sysConfigTable, UserEntryTable table, String ibNo) throws ServiceException {
        //构建map 用于后面邮件模版替换
        Map<String, String> map = new HashMap<>(15);

        map.put(MapConstants.DATE_TIME, DateUtil.formatTime(new Date()));
        map.put(MapConstants.EMAIL, table.getEmail());
        map.put(MapConstants.V_FIRST_NAME_V, table.getFirstName());
        map.put(MapConstants.V_LAST_NAME_V, table.getLastName());
        map.put(MapConstants.V_ENGLISH_NAME_V, Strings.isNullOrEmpty(table.getEnglishName()) ? "" :
                table.getEnglishName());
        map.put(MapConstants.V_GOOGLE_EMAIL_V, Strings.isNullOrEmpty(table.getGoogleEmail()) ? "" :
                table.getGoogleEmail());
        map.put(MapConstants.V_PHONE_NUMBER_V, Strings.isNullOrEmpty(table.getPhoneNumbe()) ? "" :
                "+" + table.getCallingCode() + " " + table.getPhoneNumbe());
        map.put(MapConstants.V_SALARY_PLATFORM_V, "BANK_ACCOUNT".equals(table.getSalaryPlatform()) ? "银行账户" :
                table.getSalaryPlatform());
        map.put(MapConstants.V_SALARY_LOGIN_V, Strings.isNullOrEmpty(table.getLogin()) ? "" : table.getLogin());
        map.put(MapConstants.V_SALARY_V, String.valueOf(table.getSalary()));
        map.put(MapConstants.V_IB_NO_V, ibNo);
        map.put(MapConstants.V_BANK_NAME_V, Strings.isNullOrEmpty(table.getBankName()) ? "" : table.getBankName());
        map.put(MapConstants.V_ACCOUNT_HOLDERS_NAME_V, Strings.isNullOrEmpty(table.getAccountHoldersName()) ? "" :
                table.getAccountHoldersName());
        map.put(MapConstants.V_BANK_ACCOUNT_NUMBER_V, Strings.isNullOrEmpty(table.getBankAccountNumber()) ? "" :
                table.getBankAccountNumber());
        map.put(MapConstants.V_BANK_CODE_V, Strings.isNullOrEmpty(table.getBankCode()) ? "" : table.getBankCode());
        map.put(MapConstants.V_REFERRAL_CODE_V, Strings.isNullOrEmpty(table.getReferralCode()) ? "" :
                table.getReferralCode());
        map.put(MapConstants.V_ENTRY_DATE_V, null == table.getEntryDate() ? "" :
                DateUtil.formatDate(table.getEntryDate()));

        SysEmailSendEntity sysEmailSendEntity = new SysEmailSendEntity();
        sysEmailSendEntity.setSubject("CWG VERIFY SUCCESS PERSONAL INFORMATION FOR EMPLOYMENT");
        sysEmailSendEntity.setEmailSendEnum(EmailSendEnum.VERIFY_SUCCESS_PERSONAL_INFORMATION_FOR_EMPLOYMENT);
        sysEmailSendEntity.setMap(map);
        sysEmailSendEntity.setTemplateName(SystemEmailCodeConstants.VERIFY_SUCCESS_PERSONAL_INFORMATION_FOR_EMPLOYMENT);
        sysEmailSendEntity.setUsers(sysConfigTable.getValue());
        try {
            emailService.sendEmail(sysEmailSendEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendUserEntryVerifySuccessPersonEmail(SysConfigTable emailConfigTable, UserEntryTable table,
                                                       String ibNo) throws ServiceException {
        //构建map 用于后面邮件模版替换
        Map<String, String> map = new HashMap<>(11);

        map.put(MapConstants.NAME, table.getFirstName() + table.getLastName());
        map.put(MapConstants.DATE_TIME, DateUtil.formatTime(new Date()));
        map.put(MapConstants.V_FIRST_NAME_V, table.getFirstName());
        map.put(MapConstants.V_LAST_NAME_V, table.getLastName());
        map.put(MapConstants.V_ENGLISH_NAME_V, table.getEnglishName());
        map.put(MapConstants.V_GOOGLE_EMAIL_V, table.getGoogleEmail());
        map.put(MapConstants.V_GOOGLE_PASSWORD_V, table.getGooglePassword());
        map.put(MapConstants.V_SALARY_V, String.valueOf(table.getSalary()));
        map.put(MapConstants.V_IB_NO_V, ibNo);
        map.put(MapConstants.V_REFERRAL_CODE_V, Strings.isNullOrEmpty(table.getReferralCode()) ? "" :
                table.getReferralCode());
        map.put(MapConstants.V_ENTRY_DATE_V, null == table.getEntryDate() ? "" :
                DateUtil.formatDate(table.getEntryDate()));
        SysEmailSendEntity sysEmailSendEntity = new SysEmailSendEntity();
        sysEmailSendEntity.setSubject("CWG VERIFY SUCCESS TO PERSONAL");
        sysEmailSendEntity.setEmailSendEnum(EmailSendEnum.VERIFY_SUCCESS_TO_PERSONAL);
        sysEmailSendEntity.setMap(map);
        if (CountryUtil.isCN(table.getCountry())) {
            sysEmailSendEntity.setTemplateName(SystemEmailCodeConstants.VERIFY_SUCCESS_TO_PERSONAL_CN);
        } else {
            sysEmailSendEntity.setTemplateName(SystemEmailCodeConstants.VERIFY_SUCCESS_TO_PERSONAL_EN);
        }
        sysEmailSendEntity.setUsers(table.getEmail());
        sysEmailSendEntity.setBccUsers(emailConfigTable.getValue());
        sysEmailSendEntity.setBcc(1);
        try {
            emailService.sendEmail(sysEmailSendEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendUserEntryHrVerifyEmail(SysConfigTable sysConfigTable, UserEntryTable table) throws ServiceException {
        //构建map 用于后面邮件模版替换
        Map<String, String> map = new HashMap<>(15);

        map.put(MapConstants.DATE_TIME, DateUtil.formatTime(new Date()));
        map.put(MapConstants.EMAIL, table.getEmail());
        map.put(MapConstants.V_FIRST_NAME_V, table.getFirstName());
        map.put(MapConstants.V_LAST_NAME_V, table.getLastName());
        map.put(MapConstants.V_ENGLISH_NAME_V, Strings.isNullOrEmpty(table.getEnglishName()) ? "" :
                table.getEnglishName());
        map.put(MapConstants.V_GOOGLE_EMAIL_V, Strings.isNullOrEmpty(table.getGoogleEmail()) ? "" :
                table.getGoogleEmail());
        map.put(MapConstants.V_PHONE_NUMBER_V, Strings.isNullOrEmpty(table.getPhoneNumbe()) ? "" :
                "+" + table.getCallingCode() + " " + table.getPhoneNumbe());
        map.put(MapConstants.V_SALARY_PLATFORM_V, "BANK_ACCOUNT".equals(table.getSalaryPlatform()) ? "银行账户" :
                table.getSalaryPlatform());
        map.put(MapConstants.V_SALARY_LOGIN_V, Strings.isNullOrEmpty(table.getLogin()) ? "" : table.getLogin());
        map.put(MapConstants.V_SALARY_V, String.valueOf(table.getSalary()));
        map.put(MapConstants.V_BANK_NAME_V, Strings.isNullOrEmpty(table.getBankName()) ? "" : table.getBankName());
        map.put(MapConstants.V_ACCOUNT_HOLDERS_NAME_V, Strings.isNullOrEmpty(table.getAccountHoldersName()) ? "" :
                table.getAccountHoldersName());
        map.put(MapConstants.V_BANK_ACCOUNT_NUMBER_V, Strings.isNullOrEmpty(table.getBankAccountNumber()) ? "" :
                table.getBankAccountNumber());
        map.put(MapConstants.V_BANK_CODE_V, Strings.isNullOrEmpty(table.getBankCode()) ? "" : table.getBankCode());
        map.put(MapConstants.V_REFERRAL_CODE_V, Strings.isNullOrEmpty(table.getReferralCode()) ? "" :
                table.getReferralCode());
        map.put(MapConstants.V_ENTRY_DATE_V, null == table.getEntryDate() ? "" :
                DateUtil.formatDate(table.getEntryDate()));

        SysEmailSendEntity sysEmailSendEntity = new SysEmailSendEntity();
        sysEmailSendEntity.setSubject("CWG HR VERIFY SUCCESS PERSONAL INFORMATION FOR EMPLOYMENT");
        sysEmailSendEntity.setEmailSendEnum(EmailSendEnum.HR_VERIFY_PERSONAL_INFORMATION_FOR_EMPLOYMENT);
        sysEmailSendEntity.setMap(map);
        sysEmailSendEntity.setTemplateName(SystemEmailCodeConstants.HR_VERIFY_PERSONAL_INFORMATION_FOR_EMPLOYMENT);
        sysEmailSendEntity.setUsers(sysConfigTable.getValue());
        try {
            emailService.sendEmail(sysEmailSendEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public UserEntrySearchListDto searchSingle(SingleLongEntity entity) throws ServiceException {
        UserEntryTable table = userEntryRepository.getFirstById(entity.getId());
        if (table == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        UserEntrySearchListDto userEntrySearchListDto = transformSearchListDto(table);
        return userEntrySearchListDto;
    }


    @Override
    public ResultWithPagerDto<UserEntrySearchListDto> searchPageList(UserEntrySearchEntity entity) throws ServiceException {
        Integer count = userEntryMapper.countList(entity);
        PageDto pageDto = PageDto.format(entity, count);
        if (count == null || count <= 0) {
            return ResultWithPagerDto.success(pageDto);
        }
        List<UserEntryTable> userEntryTables = userEntryMapper.pageList(entity);

        if (userEntryTables == null || userEntryTables.size() <= 0) {

            throw new ServiceException(Constants.SYSTEM_ERROR);
        }
        List<UserEntrySearchListDto> userEntrySearchListDtos = new ArrayList<>(userEntryTables.size());

        for (UserEntryTable userEntryTable : userEntryTables) {
            UserEntrySearchListDto userEntrySearchListDto = transformSearchListDto(userEntryTable);
            userEntrySearchListDtos.add(userEntrySearchListDto);
        }

        return ResultWithPagerDto.success(pageDto, userEntrySearchListDtos);
    }

    @Override
    public UserEntrySearchListDto getInfoUseFlag(UserEntryUpdateEntity entity) throws Exception {
        UserEntryTable table = userEntryRepository.getFirstBySerial(entity.getEntry());
        if (table == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        UserEntrySearchListDto userEntrySearchListDto = transformSearchListDto(table);
        return userEntrySearchListDto;
    }

    @Override
    public BaseResultDto getWebsdkLink(UserEntryUpdateEntity entity) throws ServiceException {
        UserEntryTable table = userEntryRepository.getFirstBySerial(entity.getEntry());
        if (table == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }

        CustomKycVerifyRecodeEntity customKycVerifyRecodeEntity = new CustomKycVerifyRecodeEntity();
        customKycVerifyRecodeEntity.setVerifyId(table.getId());
        customKycVerifyRecodeEntity.setExternalUserId(table.getSerial());
        customKycVerifyRecodeEntity.setVerifyType(2);
        customKycVerifyRecodeEntity.setCountry("CN");
        customKycVerifyRecodeEntity.setConfig(ConfigConstants.ENTRY_VERIFY_KYC_PROPERTY);
        return kycFeignService.getWebsdkLink(customKycVerifyRecodeEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateManage(UserEntryUpdateEntity entity) throws ServiceException {
        UserEntryTable table = userEntryRepository.findFirstById(entity.getId());
        if (table == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        if (3 == table.getManageStatus() || 4 == table.getManageStatus()) {
            throw ServiceException.exception("个人信息已核验");
        }
        getUserEntryTable(table, entity);
        table.setSalary(entity.getSalary());
        table.setEntryDate(entity.getEntryDate());
        table.setGoogleEmail(getGooglemail(entity.getFirstName(), entity.getLastName(), entity.getEnglishName()));
        table.setRoleId(entity.getRoleId());
        table.setPid(entity.getPid());
        table.setSalesType(entity.getSalesType());
        table.setLeaderId(entity.getLeaderId());
        userEntryRepository.save(table);
    }

    @Override
    public String getGooglemail(String firstName, String lastName, String englishName) throws ServiceException {
        SysConfigTable emailConfigTable = sysConfigService.getByCode(ConfigConstants.COMPANY_GMAIL_DOMAIN);
        if (emailConfigTable == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }

        String email = "";
        if (!Strings.isNullOrEmpty(englishName)) {
            email = ChineseToSpell.getPingYin(englishName.replace(" ", "_") + "." + lastName.replace(" ", "_")) + emailConfigTable.getValue();
        } else {
            email = ChineseToSpell.getPingYin(firstName.replace(" ", "_") + "." + lastName.replace(" ", "_")) + emailConfigTable.getValue();
        }
        return email;
    }

    public void getUserEntryTable(UserEntryTable table, UserEntryUpdateEntity entity) {
        table.setFirstName(ChineseToSpell.getPingYin(entity.getFirstName()));
        table.setLastName(ChineseToSpell.getPingYin(entity.getLastName()));
        table.setEnglishName(Strings.isNullOrEmpty(table.getEnglishName()) ?
                ChineseToSpell.getPingYin(table.getFirstName() + " " + table.getLastName()) : entity.getEnglishName());
        table.setGender(entity.getGender());
        table.setBirthday(entity.getBirthday());
        table.setNationality(entity.getNationality());
        table.setCountry(entity.getCountry());
        table.setEntryFile(entity.getEntryFile());
        table.setSalaryPlatform(Strings.isNullOrEmpty(entity.getSalaryPlatform())?Constants.MT4:entity.getSalaryPlatform());
        table.setLogin(entity.getLogin());
        table.setCallingCode(entity.getCallingCode());
        table.setPhoneNumbe(entity.getPhoneNumbe());
        table.setEmergencyContactName(entity.getEmergencyContactName());
        table.setEmergencyContactPhoneNumbe(entity.getEmergencyContactPhoneNumbe());
        table.setBankName(entity.getBankName());
        table.setBankCode(entity.getBankCode());
        table.setBankAccountNumber(entity.getBankAccountNumber());
        table.setAccountHoldersName(entity.getAccountHoldersName());
        table.setCardType(entity.getCardType());
        table.setReferralCode(entity.getReferralCode());
    }

    private UserEntrySearchListDto transformSearchListDto(UserEntryTable userEntryTable) {
        UserEntrySearchListDto userEntrySearchListDto = new UserEntrySearchListDto();
        BeanUtils.copyProperties(userEntryTable, userEntrySearchListDto);
        return userEntrySearchListDto;
    }

}
