package com.crm.custom.service.impl;

import com.crm.custom.dao.mapper.CustomFileDao;
import com.crm.custom.dao.mapper.CustomInfoDao;
import com.crm.custom.dao.repository.CustomInfoRepository;
import com.crm.custom.dao.repository.CustomLoginHistoryRepository;
import com.crm.custom.dao.repository.UserInfoRepository;
import com.crm.custom.service.*;
import com.crm.custom.service.impl.base.BaseUploadServiceImpl;
import com.crm.rely.backend.configuration.LocaleMessage;
import com.crm.rely.backend.core.constant.*;
import com.crm.rely.backend.core.entity.base.LongEntitys;
import com.crm.rely.backend.core.entity.system.email.SysEmailSendEntity;
import com.crm.rely.backend.core.entity.web.notice.record.WebNoticeRecordAndEmailMqEntity;
import com.crm.rely.backend.core.exception.ServiceException;
import com.crm.rely.backend.core.pojo.table.CustomLoginHistoryTable;
import com.crm.rely.backend.core.pojo.table.SysConfigTable;
import com.crm.rely.backend.core.pojo.table.SysCountryTable;
import com.crm.rely.backend.model.constant.ConfigConstants;
import com.crm.rely.backend.model.constant.CustomConstants;
import com.crm.rely.backend.model.entity.custom.bank.CustomBankAddEntity;
import com.crm.rely.backend.model.entity.custom.fund.history.CustomFundHistoryAddEntity;
import com.crm.rely.backend.model.entity.custom.info.*;
import com.crm.rely.backend.model.entity.user.info.UserInfoEntity;
import com.crm.rely.backend.model.pojo.table.CustomInfoTable;
import com.crm.rely.backend.model.pojo.table.UserInfoTable;
import com.crm.rely.backend.model.util.CustomInfoUtil;
import com.crm.rely.backend.service.EmailService;
import com.crm.rely.backend.service.MqSendService;
import com.crm.rely.backend.service.RedisService;
import com.crm.rely.backend.util.*;
import com.google.common.base.Strings;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.*;

/**
 * @program: crm-backend
 * @description:
 * @author: houn
 * @create: 2019-07-25 16:14
 */
@SuppressWarnings("SpringJavaAutowiringInspection")
@Log4j
@Service
public class CustomInfoServiceImpl extends BaseUploadServiceImpl implements CustomInfoService {

    @Autowired
    private CustomInfoRepository customInfoRepository;
    @Autowired
    private UserInfoRepository userInfoRepository;
    @Autowired
    private CustomLoginHistoryRepository customLoginHistoryRepository;
    @Autowired
    private SysCountryService sysCountryService;
    @Autowired
    private EmailService emailService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private MqSendService mqSendService;
    @Autowired
    private CustomInfoDao customInfoDao;
    @Autowired
    private CustomFileDao customFileDao;

    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private CustomBankService customBankService;

    @Autowired
    private CustomLoginService customLoginService;

    @Autowired
    private CustomLoginDemoService customLoginDemoService;

    @Autowired
    private CustomLoginFirmOfferService customLoginFirmOfferService;

    @Autowired
    private CustomLoginAssetManagementService customLoginAssetManagementService;

    @Autowired
    private CustomFundHistoryService customFundHistoryService;

    @Autowired
    private LocaleMessage localeMessage;


    /**
     * 用户登录
     *
     * @param entity
     * @return
     * @throws ServiceException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CustomInfoEntity login(CustomInfoLoginEntity entity) throws ServiceException {

        //首先用邮箱和密码验证账号
        CustomInfoTable customInfoTable = customInfoRepository.findFirstByEmailAndPassword(entity.getLoginName(),
                entity.getPassword());

        //如果不存在则判断 输入的是否为id
        if (customInfoTable == null) {
            Long id = null;
            try {
                //将登陆输入的账号转为id
                id = Long.parseLong(entity.getLoginName());
                customInfoTable = customInfoRepository.findFirstByIdAndPassword(id, entity.getPassword());
            } finally {
                //如果转化id异常或者id和密码不匹配 这提示用户名或密码错误
                if (customInfoTable == null || id == null) {
                    throw new ServiceException(Constants.LOGIN_FAIL);
                }
            }
        }
        if (customInfoTable.getValid() == null || !customInfoTable.getValid().equals(1)) {
            throw ServiceException.exception(Constants.RESTRICTED_LOGIN);
        }
        /*
            获取ib信息
         */

        //List<CustomFileDto> fileDtos = customFileService.getAllFiles(customInfoTable.getId());

        //CustomBankTable customBankTable = customBankService.getByCustomId(customInfoTable.getId());
        CustomInfoEntity transform = transform(customInfoTable, null, entity);

        /**
         * 更新登录信息
         */
        customInfoTable.setLastAddress(entity.getAddress());
        customInfoTable.setLastIp(entity.getIp());

        customInfoTable.setLastTime(entity.getTime());
        customInfoTable.setModifyUser(customInfoTable.getId());
        customInfoTable.setModifyIp(entity.getIp());
        customInfoTable.setModifyTime(entity.getTime());
        customInfoRepository.save(customInfoTable);

        //添加登录记录
        CustomLoginHistoryTable customLoginHistoryTable = new CustomLoginHistoryTable();
        customLoginHistoryTable.setAddress(entity.getAddress());
        customLoginHistoryTable.setLoginIp(entity.getIp());
        customLoginHistoryTable.setLoginTime(entity.getTime());
        customLoginHistoryTable.setCustomId(customInfoTable.getId());
        customLoginHistoryTable.setName(CustomInfoUtil.getName(customInfoTable));
        customLoginHistoryTable.setAddUser(customInfoTable.getId());
        customLoginHistoryTable.setAddIp(entity.getIp());
        customLoginHistoryTable.setAddTime(entity.getTime());

        customLoginHistoryRepository.save(customLoginHistoryTable);

        return transform;
    }

    /**
     * 注册发送邮箱验证码
     *
     * @param entity
     * @throws ServiceException
     */
    @Override
    public void registerSendEmailCode(CustomInfoRegisterSendEmailCodeEntity entity) throws ServiceException {
        //验证邮箱是否存在
        existByEmail(entity.getEmail());

        //构建实体
        SysEmailSendEntity sysEmailSendEntity = createRegisterSendEmailCodeSysEmailEntity(entity);

        //发送收据
        emailService.sendCode(sysEmailSendEntity, sysEmailSendEntity.getMap().get(MapConstants.CODE),
                Constants.EMAIL_REGISTER_VALIDATECODE_TIME * 60 * 1000);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CustomInfoTable applyReal(CustomApplyRealEntity entity) throws ServiceException {
        CustomInfoTable customInfoTable = findFirstById(entity.getCustomId());


        if (StatusConstants.PASSED_STATUS.equals(customInfoTable.getApplyRealStatus())
                && StatusConstants.PASSED_STATUS.equals(customInfoTable.getStatus())) {
            return customInfoTable;
        } else {
            customInfoTable.setStatus(StatusConstants.APPLY_STATUS);
            customInfoTable.setApplyRealStatus(StatusConstants.APPLY_STATUS);
        }
        entity.setId(customInfoTable.getId());


        BeanUtils.copyProperties(entity, customInfoTable);

        customInfoRepository.save(customInfoTable);

        sendCustomApplyVerificationSysEmailEntity(customInfoTable);
        sendCustomApplyVerificationToCustom(customInfoTable);


        return customInfoTable;
    }

    @Override
    public void updateEmailSendEmailCode(CustomInfoUpdateEmailSendEmailCodeEntity entity) throws ServiceException {
        //验证邮箱是否存在
        existByEmail(entity.getEmail());
        //构建实体
        SysEmailSendEntity sysEmailSendEntity = createUpdateEmailSendEmailSysEmailEntity(entity);

        //发送收据
        emailService.sendCode(sysEmailSendEntity, sysEmailSendEntity.getMap().get(MapConstants.CODE));
    }

    /**
     * 添加用户信息
     *
     * @param entity
     * @throws ServiceException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(CustomInfoRegisterEntity entity) throws ServiceException, InterruptedException {

        //打印注册信息日志
        String registerString = String.format("register email:%s,emailCode:%s,agentId:%d",entity.getEmail(),entity.getEmailCode(), entity.getAgentId());
        log.info(registerString);

        //emailService.validateCode(entity.getEmail(), entity.getEmailCode());
        //验证邮箱是否存在
        existByEmail(entity.getEmail());

        /*if (entity.getAgentId() != null) {
            UserInfoTable agent = userInfoRepository.getFirstById(entity.getAgentId());
            //不存在代理设置为null 外佣设置为0
            if (agent == null) {

                log.error("get agent is null,agentId:" + entity.getAgentId());
                entity.setAgentId(null);
            } else {

            }
        }

        //如果代理链接错误或者没有代理 则将客户挂在公司名下
        if (entity.getAgentId() == null) {
            SysConfigTable sysConfigTable = sysConfigService.getByCode(GlobalConfigConstants.COMPANY_ACCOUNT_SUPER);
            if (sysConfigTable != null) {

                Long agentId = Long.parseLong(sysConfigTable.getValue());
                entity.setAgentId(agentId);
            }
        }*/

        //获取国家信息
        SysCountryTable sysCountryTable = sysCountryService.getByCode(entity.getCountry());

        CustomInfoTable customInfoTable = new CustomInfoTable();
        BeanUtils.copyProperties(entity, customInfoTable);
        //设置国家信息
        customInfoTable.setCountryEnName(sysCountryTable.getEnName());
        customInfoTable.setCountryName(sysCountryTable.getName());
        customInfoTable.setAreaCode(sysCountryTable.getCallingCode());
        customInfoTable.setPayStatus(0);
        //获取和设置c_id
        customInfoTable.setCId(CidUtil.getCid().longValue());
        customInfoRepository.save(customInfoTable);
        customInfoTable.setAddUser(customInfoTable.getId());
//
//        //构建实体
//        SysEmailSendEntity sysEmailSendEntity = createRegisterCompleteSysEmailEntity(customInfoTable);
//
//        //发送收据
//        emailService.sendEmail(sysEmailSendEntity);
//
//        WebNoticeRecordAndEmailMqEntity mqEntity = new WebNoticeRecordAndEmailMqEntity(sysEmailSendEntity,
//                customInfoTable.getCId(), customInfoTable.getId());
//        mqSendService.send(Constants.WEB_NOTICE_PUT_RECORD, mqEntity);
//
//        //构建实体
//        SysEmailSendEntity sysEmailSendEntityToManger = createRegisterCompleteToMangerSysEmailEntity(customInfoTable);
//
//        //发送收据
//        emailService.sendEmail(sysEmailSendEntityToManger);
    }

    /**
     * 修改用户信息
     *
     * @param entity
     * @throws ServiceException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(CustomInfoUpdateEntity entity) throws ServiceException {

        CustomInfoTable customInfoTable = findFirstById(entity.getId());
        if (!Strings.isNullOrEmpty(entity.getIdentity()) && !entity.getIdentity().equals(customInfoTable.getIdentity())) {
            existByIdentity(entity.getIdentity());
        }

        BeanUtils.copyProperties(entity, customInfoTable);

        //获取国家信息
      /*  SysCountryTable sysCountryTable = sysCountryService.getByCode(entity.getCountry());
        //设置国家信息
        customInfoTable.setCountryEnName(sysCountryTable.getEnName());
        customInfoTable.setCountryName(sysCountryTable.getName());
        if (entity.getAddressLines() != null) {
            customInfoTable.setAddressLine(String.join("@#", entity.getAddressLines()));
        } else {
            customInfoTable.setAddressLine(null);
        }*/

        customInfoRepository.save(customInfoTable);

        /*CustomBankAddEntity customBankAddEntity = new CustomBankAddEntity();
        BeanUtils.copyProperties(entity, customBankAddEntity);
        customBankAddEntity.setCustomId(entity.getId());
        customBankService.add(customBankAddEntity);*/
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmail(CustomInfoUpdateEmailEntity entity) throws ServiceException {
        emailService.validateCode(entity.getEmail(), entity.getEmailCode());
        //邮箱
        existByEmail(entity.getEmail());

        CustomInfoTable customInfoTable = customInfoRepository.findFirstById(entity.getCustomId());
        customInfoTable.setEmail(entity.getEmail());
        customInfoRepository.save(customInfoTable);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updateHeadPicture(CustomInfoUpdateHeadPictureEntity entity, MultipartFile file) throws Exception {

        CustomInfoTable customInfoTable = customInfoRepository.findFirstById(entity.getCustomId());
        if (customInfoTable == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }

        //保存头像
        String path = saveFile((entity.getCustomId() == null ? "" : entity.getCustomId().toString()) + "/headPicture"
                , file);
        customInfoTable.setHeadPicture(path);
        customInfoTable.setModifyUser(entity.getUser());
        customInfoTable.setModifyTime(entity.getTime());
        customInfoTable.setModifyIp(entity.getIp());
        customInfoRepository.save(customInfoTable);
        return path;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePassword(CustomUpdateLoginPasswordEntity entity) throws ServiceException {

        CustomInfoTable customInfoTable = findFirstById(entity.getId());

        //验证密码是否正确
        if (!entity.getOldPassword().equals(customInfoTable.getPassword())) {
            throw new ServiceException(Constants.PASSWORD_ERROR);
        }
        /**
         * 填写修改时间和密码
         */
        customInfoTable.setPassword(entity.getNewPassword());
        customInfoTable.setModifyIp(entity.getModifyIp());
        customInfoTable.setModifyTime(entity.getModifyTime());
        customInfoTable.setModifyUser(entity.getModifyUser());

        customInfoRepository.save(customInfoTable);

        sendUpdatePasswordCompleteSendEmailSysEmailEntity(customInfoTable);
    }

    @Override
    public void updatePasswordSendEmail(CustomUpdatePasswordSendEmailEntity entity) throws ServiceException {

        CustomInfoTable customInfoTable = customInfoRepository.getFirstByEmailNotNullAndEmail(entity.getEmail());

        if (customInfoTable == null) {
            return;
//            throw new ServiceException(Constants.USER_NOT_EXIST_ERROR);
        }
        SysEmailSendEntity sysEmailSendEntity = createUpdatePasswordSendEmailSysEmailEntity(entity, customInfoTable);

        redisService.save(sysEmailSendEntity.getMap().get(MapConstants.TOKEN), customInfoTable.getId(),
                Constants.EMAIL_TOKEN_TIME * 60 * 1000);

        mqSendService.send("ACTIVEMQ_JMS_URL_EMAILSS", sysEmailSendEntity);

        //系统内部通知
        /*WebNoticeRecordAndEmailMqEntity mqEntity = new WebNoticeRecordAndEmailMqEntity(sysEmailSendEntity,
                customInfoTable.getCId(), customInfoTable.getId());
        mqSendService.send(Constants.WEB_NOTICE_PUT_RECORD, mqEntity);*/
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePassword(CustomUpdateEmailPasswordEntity entity) throws ServiceException {

        Long id = redisService.getEntity(entity.getToken(), Long.class);
        if (id == null) {
            throw new ServiceException(Constants.EMAIL_EXPIRE);
        }

        CustomInfoTable customInfoTable = customInfoRepository.findFirstById(id);

        if (customInfoTable == null) {
            throw new ServiceException(Constants.USER_NOT_EXIST_ERROR);
        }

        /**
         * 填写修改时间和密码
         */
        customInfoTable.setPassword(entity.getPassword());
        customInfoTable.setModifyIp(entity.getModifyIp());
        customInfoTable.setModifyTime(entity.getModifyTime());
        customInfoTable.setModifyUser(customInfoTable.getModifyUser());

        customInfoRepository.save(customInfoTable);
        redisService.remove(entity.getToken());
        sendUpdatePasswordCompleteSendEmailSysEmailEntity(customInfoTable);
    }

    private void addHistory(CustomInfoTable customInfoTable, Integer sourceType, BigDecimal amount, String remarks) throws ServiceException {
        CustomFundHistoryAddEntity entity = new CustomFundHistoryAddEntity();
        entity.setCustomId(customInfoTable.getId());
        entity.setCId(customInfoTable.getCId());
        entity.setAgentId(customInfoTable.getAgentId());
        entity.setAmount(amount);
        entity.setRemarks(remarks);
        entity.setSourceType(sourceType);
        customFundHistoryService.add(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAgentId(CustomInfoUpdateAgentEntity entity) throws ServiceException {
        CustomInfoTable customInfoTable = customInfoRepository.findFirstById(entity.getId());
        if (customInfoTable == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        if (!entity.getAgentId().equals(customInfoTable.getAgentId())) {
            BeanUtils.copyProperties(entity, customInfoTable);
            customInfoRepository.save(customInfoTable);

            customLoginService.updateAgentId(entity);
            customLoginDemoService.updateAgentId(entity);
            customLoginFirmOfferService.updateAgentId(entity);
            customLoginAssetManagementService.updateAgentId(entity);

            UserInfoTable userInfoTable = userInfoRepository.findFirstById(customInfoTable.getIbId());
            if (userInfoTable != null) {
                userInfoTable.setPid(entity.getAgentId());
                userInfoTable.setPStamp(entity.getPStamp());
                userInfoTable.setStamp(entity.getStamp());
                userInfoTable.setSalesId(entity.getSalesId());
                userInfoRepository.save(userInfoTable);
            }

        }
    }

    /**
     * 根据id获取用户信息
     *
     * @param id
     * @return
     */
    private CustomInfoTable findFirstById(Long id) throws ServiceException {
        CustomInfoTable customInfoTable = customInfoRepository.findFirstById(id);

        if (customInfoTable == null) {
            throw new ServiceException(Constants.USER_NOT_EXIST_ERROR);
        }
        return customInfoTable;
    }

    /**
     * 验证邮箱是否已存在
     *
     * @param email
     * @throws ServiceException
     */
    private void existByEmail(String email) throws ServiceException {
        boolean existByEmail = customInfoRepository.existsByEmail(email);
        if (existByEmail) {
            throw new ServiceException(Constants.EMAIL_IS_EXIST_ERROR);
        }
    }

    /**
     * 验证证件是否已存在
     *
     * @param identity
     * @throws ServiceException
     */
    private void existByIdentity(String identity) throws ServiceException {
        //如果为空 则直接返回
        if (Strings.isNullOrEmpty(identity)) {
            return;
        }
        boolean existsByIdentity = customInfoRepository.existsByIdentity(identity);
        if (existsByIdentity) {
            throw new ServiceException(Constants.IDENTITY_IS_EXIST_ERROR);
        }
    }

    private void existBySno(String sno) throws ServiceException {
        //如果为空 则直接返回
        if (Strings.isNullOrEmpty(sno)) {
            return;
        }
        CustomInfoTable customInfoTable = customInfoRepository.getFirstBySno(sno);
        if (customInfoTable != null) {
            throw new ServiceException(String.format(localeMessage.getMessage("sno_is_exist_error"),
                    customInfoTable.getSno(), customInfoTable.getEmail()));
        }
    }

    /**
     * 构建注册发送邮件实体
     *
     * @param entity
     * @return
     */
    private SysEmailSendEntity createRegisterSendEmailCodeSysEmailEntity(CustomInfoRegisterSendEmailCodeEntity entity) {
        SysEmailSendEntity sysEmailSendEntity = new SysEmailSendEntity();

        Map<String, String> map = new HashMap<>(4);
        String code = GetRandom.getRandom(6);
        map.put(MapConstants.CODE, code);
        Date time = DateUtil.operationMinute(new Date(), Constants.EMAIL_REGISTER_VALIDATECODE_TIME);
        map.put(MapConstants.EXPIRE_TIME, DateUtil.formatTime(time));
        map.put(MapConstants.DATE_TIME, DateUtil.formatTime());

        sysEmailSendEntity.setAddIp(entity.getIp());
        sysEmailSendEntity.setAddTime(entity.getTime());

        sysEmailSendEntity.setUsers(entity.getEmail());
        sysEmailSendEntity.setEmailSendEnum(EmailSendEnum.REGISTER_CODE);
        sysEmailSendEntity.setTemplateName(GlobalSystemEmailCodeConstants.CUSTOM_REGISTER_SEND_EMAIL_CODE_CN);

        sysEmailSendEntity.setMap(map);
        sysEmailSendEntity.setMap(map);

        return sysEmailSendEntity;
    }

    private SysEmailSendEntity createRegisterCompleteSysEmailEntity(CustomInfoTable entity) {
        SysEmailSendEntity sysEmailSendEntity = new SysEmailSendEntity();

        Map<String, String> map = new HashMap<>(3);

        map.put(MapConstants.C_ID, entity.getCId() + "");
        map.put(MapConstants.EMAIL, entity.getEmail());
        map.put(MapConstants.DATE_TIME, DateUtil.formatTime());

        sysEmailSendEntity.setAddIp(entity.getAddIp());
        sysEmailSendEntity.setAddTime(entity.getAddTime());

        sysEmailSendEntity.setUsers(entity.getEmail());
        sysEmailSendEntity.setEmailSendEnum(EmailSendEnum.REGISTER_COMPLETE);
        sysEmailSendEntity.setTemplateName(GlobalSystemEmailCodeConstants.CUSTOM_REGISTER_COMPLETE_SEND_CN);
        sysEmailSendEntity.setMap(map);

        return sysEmailSendEntity;
    }

//    private SysEmailSendEntity createRegisterCompleteToMangerSysEmailEntity(CustomInfoTable entity) throws
//    ServiceException {
//        SysEmailSendEntity sysEmailSendEntity = new SysEmailSendEntity();
//
//        Map<String, String> map = new HashMap<>(3);
//
//        map.put(MapConstants.C_ID, entity.getCId() + "");
//        map.put(MapConstants.EMAIL, entity.getEmail());
//
//        map.put(MapConstants.DATE_TIME, DateUtil.formatTime());
//
//        sysEmailSendEntity.setAddIp(entity.getAddIp());
//        sysEmailSendEntity.setAddTime(entity.getAddTime());
//
//        SysConfigTable sysConfigTable = sysConfigService.getByCode(GlobalConfigConstants.REGISTER_EMAIL_NOTICE);
//        if (sysConfigTable != null) {
//            sysEmailSendEntity.setUsers(sysConfigTable.getValue());
//        }
//
//        sysEmailSendEntity.setEmailSendEnum(EmailSendEnum.REGISTER_COMPLETE_MANAGER);
//
//        sysEmailSendEntity.setTemplateName(SystemEmailCodeConstants.REGISTER_COMPLETE_NOTICE_NAME);
//
//        sysEmailSendEntity.setMap(map);
//
//        return sysEmailSendEntity;
//    }

    private SysEmailSendEntity createUpdateEmailSendEmailSysEmailEntity(CustomInfoUpdateEmailSendEmailCodeEntity entity) {
        SysEmailSendEntity sysEmailSendEntity = new SysEmailSendEntity();

        Map<String, String> map = new HashMap<>(2);
        String code = GetRandom.getRandom(6);
        map.put(MapConstants.CODE, code);
        Date time = DateUtil.operationMinute(new Date(), Constants.EMAIL_VALIDATECODE_TIME);
        map.put(MapConstants.EXPIRE_TIME, DateUtil.formatTime(time));
        map.put(MapConstants.DATE_TIME, DateUtil.formatTime());

        sysEmailSendEntity.setAddIp(entity.getIp());
        sysEmailSendEntity.setAddTime(entity.getTime());

        sysEmailSendEntity.setUsers(entity.getEmail());
        sysEmailSendEntity.setEmailSendEnum(EmailSendEnum.UPDATE_EMAIL_CODE);
        sysEmailSendEntity.setTemplateName(GlobalSystemEmailCodeConstants.CUSTOM_UPDATE_EMAIL_CODE_SEND_CN);
        sysEmailSendEntity.setMap(map);

        return sysEmailSendEntity;
    }

    /**
     * 发送后台申请核验发送邮件实体
     *
     * @param customInfoTable
     * @return
     * @throws ServiceException
     */
    private void sendCustomApplyVerificationSysEmailEntity(CustomInfoTable customInfoTable) throws ServiceException {

        if (customInfoTable == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
        SysEmailSendEntity sysEmailSendEntity = new SysEmailSendEntity();

        SysConfigTable sysConfigTable =
                sysConfigService.getByCode(ConfigConstants.CUSTOM_SUBMIT_VERIFICATION_MANAGER_EMAIL);
        if (sysConfigTable != null) {
            sysEmailSendEntity.setUsers(sysConfigTable.getValue());
        }

        Map<String, String> map = new HashMap<>(6);

        String name = CustomInfoUtil.getName(customInfoTable);

        map.put(MapConstants.NAME, name);
        map.put(MapConstants.C_ID, String.valueOf(customInfoTable.getCId()));
        map.put(MapConstants.EMAIL, customInfoTable.getEmail());

        map.put(MapConstants.APPLY_TIME, DateUtil.formatTime());
        map.put(MapConstants.DATE_TIME, DateUtil.formatTime());

        sysEmailSendEntity.setAddIp(customInfoTable.getModifyIp());
        sysEmailSendEntity.setAddTime(new Date());

        sysEmailSendEntity.setEmailSendEnum(EmailSendEnum.SUBMIT_VERIFICATION);
        String templateName = GlobalSystemEmailCodeConstants.SUBMIT_VERIFICATION_NOTICE_NAME;

        sysEmailSendEntity.setTemplateName(templateName);

        sysEmailSendEntity.setMap(map);
        emailService.sendEmail(sysEmailSendEntity);

    }

    /**
     * 发送到客户提交核验
     *
     * @param customInfoTable
     * @throws ServiceException
     */
    private void sendCustomApplyVerificationToCustom(CustomInfoTable customInfoTable) throws ServiceException {

        if (customInfoTable == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
        SysEmailSendEntity sysEmailSendEntity = new SysEmailSendEntity();

        sysEmailSendEntity.setUsers(customInfoTable.getEmail());

        Map<String, String> map = new HashMap<>(3);

        String name = CustomInfoUtil.getName(customInfoTable);

        map.put(MapConstants.NAME, name);
        map.put(MapConstants.C_ID, String.valueOf(customInfoTable.getCId()));
        map.put(MapConstants.EMAIL, customInfoTable.getEmail());
        map.put(MapConstants.DATE_TIME, DateUtil.formatTime());

        sysEmailSendEntity.setAddIp(customInfoTable.getModifyIp());
        sysEmailSendEntity.setAddTime(new Date());

        sysEmailSendEntity.setEmailSendEnum(EmailSendEnum.CUSTOM_SUBMIT_VERIFICATION);
        String templateName;
        templateName = GlobalSystemEmailCodeConstants.CUSTOM_SUBMIT_VERIFICATION_NOTICE_NAME_CN;

        sysEmailSendEntity.setTemplateName(templateName);

        sysEmailSendEntity.setMap(map);
        emailService.sendEmail(sysEmailSendEntity);

        WebNoticeRecordAndEmailMqEntity mqEntity = new WebNoticeRecordAndEmailMqEntity(sysEmailSendEntity,
                customInfoTable.getCId(), customInfoTable.getId());
        mqSendService.send(Constants.WEB_NOTICE_PUT_RECORD, mqEntity);
    }

    /**
     * 构建修改密码发送邮件实体
     *
     * @param entity
     * @param customInfoTable
     * @return
     */
    private SysEmailSendEntity createUpdatePasswordSendEmailSysEmailEntity(CustomUpdatePasswordSendEmailEntity entity
            , CustomInfoTable customInfoTable) {
        SysEmailSendEntity sysEmailSendEntity = new SysEmailSendEntity();
        String token =
                MD5Util.getMD5(AESUtil.encrypt(entity.getEmail() + Constants.LOGIN_LINK + UUIDUtil.getUUID() + Constants.LOGIN_LINK + customInfoTable.getId()));
        Date time = DateUtil.operationMinute(new Date(), Constants.EMAIL_TOKEN_TIME);
        Map<String, String> map = new HashMap<>(4);
        String name = CustomInfoUtil.getName(customInfoTable);
        map.put(MapConstants.TOKEN, token);
        map.put(MapConstants.EXPIRE_TIME, DateUtil.formatTime(time));
        map.put(MapConstants.DATE_TIME, DateUtil.formatTime());

        map.put(MapConstants.NAME, name);

        sysEmailSendEntity.setAddIp(entity.getIp());
        sysEmailSendEntity.setAddTime(entity.getTime());
        sysEmailSendEntity.setAddUser(customInfoTable.getAddUser());
        sysEmailSendEntity.setUsers(entity.getEmail());
        sysEmailSendEntity.setEmailSendEnum(EmailSendEnum.FORGET_PASSWORD);
        if (CountryUtil.isCN(customInfoTable.getCountry())) {
            sysEmailSendEntity.setTemplateName(GlobalSystemEmailCodeConstants.CUSTOM_UPDATE_PASSWORD_SEND_CN);
        } else {
            sysEmailSendEntity.setTemplateName(GlobalSystemEmailCodeConstants.CUSTOM_UPDATE_PASSWORD_SEND_EN);
        }
        sysEmailSendEntity.setMap(map);

        return sysEmailSendEntity;
    }

    /**
     * @param customInfoTable
     */
    private void sendUpdatePasswordCompleteSendEmailSysEmailEntity(CustomInfoTable customInfoTable) throws ServiceException {
        SysEmailSendEntity sysEmailSendEntity = new SysEmailSendEntity();
        Map<String, String> map = new HashMap<>(2);

        String name = CustomInfoUtil.getName(customInfoTable);
        map.put(MapConstants.NAME, name);
        map.put(MapConstants.DATE_TIME, DateUtil.formatTime());

        sysEmailSendEntity.setAddIp(customInfoTable.getModifyIp());
        sysEmailSendEntity.setAddTime(customInfoTable.getModifyTime());
        sysEmailSendEntity.setAddUser(customInfoTable.getAddUser());
        sysEmailSendEntity.setUsers(customInfoTable.getEmail());
        sysEmailSendEntity.setEmailSendEnum(EmailSendEnum.FORGET_PASSWORD);
        sysEmailSendEntity.setTemplateName(GlobalSystemEmailCodeConstants.CUSTOM_UPDATE_PASSWORD_COMPLETE_SEND_CN);
        sysEmailSendEntity.setMap(map);

        emailService.sendEmail(sysEmailSendEntity);
    }

    private CustomInfoEntity transform(CustomInfoTable customInfoTable, UserInfoEntity ibInfoEntity,
                                       CustomInfoLoginEntity entity) {

        CustomInfoEntity infoEntity = new CustomInfoEntity();

        BeanUtils.copyProperties(customInfoTable, infoEntity);
        if (!Strings.isNullOrEmpty(customInfoTable.getAddressLine())) {

            infoEntity.setAddressLines(Arrays.asList(customInfoTable.getAddressLine().split("@#")));
        }
        infoEntity.setIbInfo(ibInfoEntity);
        /*infoEntity.setFiles(fileDtos);
        if (customBankTable != null) {
            infoEntity.setBankAddr(customBankTable.getBankAddr());
            infoEntity.setBankBack(customBankTable.getBankBack());
            infoEntity.setBankBranchName(customBankTable.getBankBranchName());
            infoEntity.setBankCode(customBankTable.getBankCode());
            infoEntity.setBankUname(customBankTable.getBankUname());
            infoEntity.setBankName(customBankTable.getBankName());
            infoEntity.setSwiftCode(customBankTable.getSwiftCode());
            infoEntity.setBankFront(customBankTable.getBankFront());
            infoEntity.setBankCardNum(customBankTable.getBankCardNum());
        }*/

        return infoEntity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteInBatch(LongEntitys entitys) throws Exception {
        /*
            删除基本信息
         */
        customInfoDao.deleteInBatch(entitys);

        /*
            删除文件信息
         */
        List<String> files = customFileDao.getAllPathByCustomId(entitys);
        customFileDao.deleteInBatchByCustomId(entitys);
        /*
            删除文件
         */
        FileProcessUtil.deleteFiles(files);

    }

    @Override
    public CustomInfoTable getById(Long id) throws ServiceException {
        CustomInfoTable customInfoTable = customInfoRepository.getFirstById(id);
        if (customInfoTable == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        return customInfoTable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePosition(Long customId, Integer position) throws ServiceException {
        CustomInfoTable customInfoTable = customInfoRepository.findFirstById(customId);

        if (customInfoTable == null) {
            throw new ServiceException(Constants.USER_NOT_EXIST_ERROR);
        }
        customInfoTable.setPosition(position);
        customInfoRepository.save(customInfoTable);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void validPosition(Long customId, Integer position) throws ServiceException {
        CustomInfoTable customInfoTable = customInfoRepository.getFirstById(customId);

        if (customInfoTable == null) {
            throw new ServiceException(Constants.USER_NOT_EXIST_ERROR);
        }
        if (customInfoTable.getPosition() == null) {
            customInfoTable.setPosition(CustomConstants.POSITION1);
        }
        if (!customInfoTable.getPosition().equals(position)) {
            throw new ServiceException(Constants.NOT_PERMIT);
        }

    }

    @Override
    public Integer getPosition(Long customId) throws ServiceException {
        CustomInfoTable customInfoTable = customInfoRepository.getFirstById(customId);

        if (customInfoTable == null) {
            throw new ServiceException(Constants.USER_NOT_EXIST_ERROR);
        }
        return customInfoTable.getPosition();
    }

    @Override
    public BigDecimal getBalance(Long id) throws ServiceException {
        CustomInfoTable customInfoTable = customInfoRepository.getFirstById(id);
        return customInfoTable.getBalance() == null ? BigDecimal.ZERO : customInfoTable.getBalance();
    }

}
