package com.crm.manager.service.impl;

import com.alibaba.fastjson.JSON;
import com.crm.manager.dao.mapper.*;
import com.crm.manager.dao.repository.CustomFileRepository;
import com.crm.manager.dao.repository.CustomInfoRepository;
import com.crm.manager.dao.repository.CustomSurveyRepository;
import com.crm.manager.dao.repository.UserInfoRepository;
import com.crm.manager.service.*;
import com.crm.manager.service.ib.AgentApplyFeignService;
import com.crm.manager.service.ib.IbInfoFeignService;
import com.crm.manager.service.shop.ShopCustomInfoFeignService;
import com.crm.rely.backend.configuration.LocaleMessage;
import com.crm.rely.backend.core.constant.*;
import com.crm.rely.backend.core.dto.base.BaseResultDto;
import com.crm.rely.backend.core.dto.base.BaseResultWithPagerDto;
import com.crm.rely.backend.core.dto.base.PageDto;
import com.crm.rely.backend.core.dto.custom.CustomGetEmailDto;
import com.crm.rely.backend.core.dto.custom.CustomInfoDto;
import com.crm.rely.backend.core.dto.custom.file.CustomFileDto;
import com.crm.rely.backend.core.dto.custom.potential.CustomListDto;
import com.crm.rely.backend.core.dto.custom.survey.CustomSurveyDto;
import com.crm.rely.backend.core.dto.ib.info.IbInfoDto;
import com.crm.rely.backend.core.dto.system.reasons.refusal.SysReasonsRefusalSearchDto;
import com.crm.rely.backend.core.entity.base.LongEntitys;
import com.crm.rely.backend.core.entity.base.SingleLongEntity;
import com.crm.rely.backend.core.entity.custom.info.*;
import com.crm.rely.backend.core.entity.custom.kyc.CustomKycVerifyRecodeEntity;
import com.crm.rely.backend.core.entity.custom.login.CustomLoginDayWithdrawLimitUpdateEntity;
import com.crm.rely.backend.core.entity.custom.shop.CustomInfoSyncEntity;
import com.crm.rely.backend.core.entity.ib.info.IbLoginEntity;
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.pojo.table.*;
import com.crm.rely.backend.core.pojo.view.CustomInfoGetEmailView;
import com.crm.rely.backend.core.pojo.view.CustomView;
import com.crm.rely.backend.exception.ServiceException;
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 com.google.common.collect.Lists;
import lombok.extern.log4j.Log4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.View;

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

/**
 * Created by max on 2020/6/16.
 */
@SuppressWarnings({"unused", "SpringJavaAutowiringInspection"})
@Log4j
@Service
public class CustomInfoServiceImpl implements CustomInfoService {

    @Autowired
    private CustomInfoDao customInfoDao;
    @Autowired
    private CustomInfoRepository customInfoRepository;
    @Autowired
    private CustomSurveyRepository customSurveyRepository;
    @Autowired
    private CustomFileRepository customFileRepository;
    @Autowired
    private CustomLoginDao customLoginDao;
    @Autowired
    private CustomSurveyDao customSurveyDao;
    @Autowired
    private CustomFileDao customFileDao;
    @Autowired
    private EmailService emailService;
    @Autowired
    private MqSendService mqSendService;
    @Autowired
    private SysReasonsRefusalService sysReasonsRefusalService;

    @Autowired
    private UserInfoRepository userInfoRepository;

    @Autowired
    private RedisService redisService;

    @Autowired
    private LocaleMessage localeMessage;
    @Autowired
    private AgentApplyFeignService agentApplyFeignService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private ShopCustomInfoFeignService shopCustomInfoFeignService;
    @Autowired
    private CustomSurveyService customSurveyService;

    @Autowired
    private IbInfoFeignService ibInfoFeignService;
    @Autowired
    private KycFeignService kycFeignService;
    @Autowired
    private SysKycConfigService sysKycConfigService;
    @Autowired
    private SysApproveEmailMapper sysApproveEmailMapper;
    @Autowired
    private View error;
    @Autowired
    private SysCountryService sysCountryService;



    @Override
    public BaseResultWithPagerDto<List<CustomListDto>> getPageList(CustomSearchEntity entity) throws Exception {

        /*
            获取总数
         */
        Integer count = customInfoDao.countCustom(entity);
        PageDto pageDto = FormatPage.format(entity.getPage(), count);
        if (count == null || count == 0) {
            return BaseResultWithPagerDto.success(Lists.newArrayList(), pageDto);
        }

        /*
            获取列表
         */
        List<CustomListDto> dtos = getList(entity);
        return BaseResultWithPagerDto.success(dtos, pageDto);
    }

    @Override
    public List<CustomListDto> getList(CustomSearchEntity entity) throws Exception {
        return getList(entity, true);
    }

    @Override
    public List<CustomListDto> getList(CustomSearchEntity entity, Boolean isIb) throws Exception {
        /*
            获取列表
         */
        List<CustomView> views = customInfoDao.listCustom(entity);

        Map<Long, Integer> customAgentApplyMap = null;
        if (isIb != null && isIb) {
             /*
            获取客户申请状态
         */
            LongEntitys longEntitys = new LongEntitys();
            List<Long> ids = Lists.newArrayList();
            for (CustomView view : views) {
                ids.add(view.getId());
            }
            longEntitys.setIds(ids);
            BaseResultDto<Map<Long, Integer>> resultDto = agentApplyFeignService.statusList(longEntitys);
            if (resultDto.getCode() != Constants.SUCCESS_CODE) {
                throw ServiceException.exception(resultDto.getMsg());
            }
            customAgentApplyMap = resultDto.getData();
        }


        List<CustomListDto> dtos = Lists.newArrayList();
        for (CustomView view : views) {
            CustomListDto dto = new CustomListDto();
            BeanUtils.copyProperties(view, dto);
            dto.setIbInvalid(view.getIbInvalid() == null ? 0 : view.getIbInvalid());
            dto.setIbInvalidName(localeMessage.getMessage(TranslateUtil.ibInvalidToName(dto.getIbInvalid())));
            if (view.getIbId() == null || view.getIbId() <= 0) {
                if (isIb != null && isIb && customAgentApplyMap != null) {
                    if (customAgentApplyMap.get(view.getId()) == 1) {
                        dto.setIbStatus(3);
                    } else {
                        dto.setIbStatus(1);
                    }
                }
            } else {
                dto.setIbStatus(2);
            }
            if (!Strings.isNullOrEmpty(view.getExcludeShowLoginTypes())) {
                dto.setExcludeShowLoginTypes(Arrays.asList(view.getExcludeShowLoginTypes().split(",")));
            }

            dtos.add(dto);
        }
        return dtos;
    }

    @Override
    public List<CustomGetEmailDto> getEmailList(CustomSearchGetEmailEntity entity) throws Exception {

        /*
            获取列表
         */
        List<CustomInfoGetEmailView> views = customInfoDao.listCustomEmail(entity);

        List<CustomGetEmailDto> dtos = Lists.newArrayList();
        for (CustomInfoGetEmailView view : views) {
            CustomGetEmailDto dto = new CustomGetEmailDto();
            BeanUtils.copyProperties(view, dto);
            dto.setName(CustomInfoUtil.getName(view));
            dtos.add(dto);
        }

        return dtos;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void approve(CustomApproveEntity entity) throws ServiceException {
        //获取客户数据
        CustomInfoTable customInfoTable = customInfoRepository.findFirstById(entity.getId());
        if (customInfoTable == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }

        if (Constants.APPLY_STATUS.equals(entity.getStatus())) {
            if (!Constants.PASSED_STATUS.equals(customInfoTable.getStatus())
                    || !Constants.PASSED_STATUS.equals(customInfoTable.getApplyRealStatus())) {
                throw ServiceException.exception(Constants.CANNOT_APPROVE);
            }
        } else {
            //判断是否可申请条件 申请状态为初始状态
            //申请转正状态为申请中 如果不满足这些条件 返回不符合申请状态
            if (customInfoTable.getApplyRealStatus() == null
                    || customInfoTable.getApplyRealStatus().equals(Constants.PASSED_STATUS)
                    || Constants.PASSED_STATUS.equals(customInfoTable.getStatus())) {
                throw ServiceException.exception(Constants.CANNOT_APPROVE);
            }
        }

        BeanUtils.copyProperties(entity, customInfoTable);
        //customInfoTable.setAuthStatus(1);
        customInfoRepository.save(customInfoTable);
        List<CustomFileTable> fileTables = null;
        Integer status;
        //判断是否审核通过 如果审核通过 将还属于审核中的文件设置为通过 重新上传的文件需要手动审批
        if (Constants.PASSED_STATUS.equals(entity.getStatus())) {
            fileTables = customFileRepository.findAllByCustomIdAndStatus(customInfoTable.getId(),
                    Constants.APPLY_STATUS);
            status = Constants.PASSED_STATUS;
            fileTables.forEach(v -> v.setStatus(Constants.PASSED_STATUS));

        } else if (Constants.APPLY_STATUS.equals(entity.getStatus())) {
            fileTables = customFileRepository.findAllByCustomId(customInfoTable.getId());

            status = Constants.APPLY_STATUS;
        } else {
            status = Constants.APPLY_STATUS;
        }

        if (fileTables != null && fileTables.size() > 0) {
            fileTables.forEach(v -> v.setStatus(status));
            customFileRepository.save(fileTables);
        }
        //发送审核结果邮件
        SysEmailSendEntity sysEmailSendEntity = null;
        if (Constants.PASSED_STATUS.equals(customInfoTable.getStatus())) {
            sysEmailSendEntity = createCustomVerificationSuccessSysEmailEntity(customInfoTable);


        } else if (Constants.REJECTED_STATUS.equals(customInfoTable.getStatus())) {
            sysEmailSendEntity = createCustomVerificationFailSysEmailEntity(customInfoTable, entity);
        }
        if (sysEmailSendEntity != null) {
            emailService.sendEmail(sysEmailSendEntity);

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

        sendAgentEmail(entity, customInfoTable, sysEmailSendEntity);

        //更新redis数据
//        InfoEntity custom = redisService.getObject(PrefixEnum.PREFIX_CUSTOM.getCode() + entity.getId());
        InfoEntity custom = redisService.getEntity(PrefixEnum.PREFIX_CUSTOM.getCode() + entity.getId(),
                InfoEntity.class);
        if (custom != null) {
            CustomInfoEntity customInfoEntity = custom.getCustomInfo();
            BeanUtils.copyProperties(entity, customInfoEntity);
            custom.setCustomInfo(customInfoEntity);
            redisService.save(PrefixEnum.PREFIX_CUSTOM.getCode() + entity.getId(), custom);
        }
        /*
            同步积分商城数据
         */
        if (Constants.PASSED_STATUS.equals(customInfoTable.getStatus()) && sysConfigService.shopShow()) {
            CustomInfoSyncEntity customInfoSyncEntity = new CustomInfoSyncEntity();
            BeanUtils.copyProperties(customInfoTable, customInfoSyncEntity);
            try {
                shopCustomInfoFeignService.syncCustomInfo(customInfoSyncEntity);
            } catch (Exception e) {
                log.error(e.getMessage());
                //throw new ServiceException(e.getMessage());
            }
        }
    }

    private SysEmailSendEntity createCustomVerificationFailSysEmailEntity(CustomInfoTable customInfoTable,
                                                                          CustomApproveEntity entity) throws ServiceException {

        if (customInfoTable == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
        String reasonsRefusal = "";
        try {
            if (!Strings.isNullOrEmpty(entity.getApproveDesc())) {
                String[] idStrings = entity.getApproveDesc().split(",");
                List<Long> ids = new ArrayList<>();
                for (String idString : idStrings) {
                    ids.add(Long.parseLong(idString));
                }

                List<SysReasonsRefusalSearchDto> dtos =
                        sysReasonsRefusalService.searchList(ids);

                for (SysReasonsRefusalSearchDto dto : dtos) {

                    if (!Strings.isNullOrEmpty(reasonsRefusal)) {
                        reasonsRefusal += ",";
                    }
                    if (CountryUtil.isCN(customInfoTable.getCountry())) {
                        reasonsRefusal += dto.getContent();
                    } else {
                        reasonsRefusal += dto.getEnContent();
                    }
                }
            }

        } catch (Exception e) {
            reasonsRefusal = null;
        }

        SysEmailSendEntity sysEmailSendEntity = new SysEmailSendEntity();
        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.REASONS_REFUSAL, reasonsRefusal);
        map.put(MapConstants.DATE_TIME, DateUtil.formatTime());

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

        sysEmailSendEntity.setUsers(customInfoTable.getEmail());
        sysEmailSendEntity.setEmailSendEnum(EmailSendEnum.CUSTOM_APPROVE_FAIL);
        String templateName;

        if (CountryUtil.isCN(customInfoTable.getCountry())) {
            templateName = SystemEmailCodeConstants.CUSTOM_VERIFICATION_FAIL_SEND_CN;
        } else {
            templateName = SystemEmailCodeConstants.CUSTOM_VERIFICATION_FAIL_SEND_EN;
        }
        sysEmailSendEntity.setTemplateName(templateName);

        sysEmailSendEntity.setMap(map);

        return sysEmailSendEntity;
    }


    private SysEmailSendEntity createCustomVerificationSuccessSysEmailEntity(CustomInfoTable customInfoTable) throws ServiceException {

        if (customInfoTable == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
        SysEmailSendEntity sysEmailSendEntity = new SysEmailSendEntity();
        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.setUsers(customInfoTable.getEmail());
        sysEmailSendEntity.setEmailSendEnum(EmailSendEnum.CUSTOM_APPROVE_SUCCESS);
        String templateName;
        String lang = customInfoTable.getLang();

        if (Strings.isNullOrEmpty(lang)) {
            lang = customInfoTable.getCountry();
        }
        if (CountryUtil.isCN(customInfoTable.getCountry())) {
            templateName = SystemEmailCodeConstants.CUSTOM_VERIFICATION_SUCCESS_SEND_CN;
        } else {
            templateName = SystemEmailCodeConstants.CUSTOM_VERIFICATION_SUCCESS_SEND_EN;
        }
        sysEmailSendEntity.setTemplateName(templateName);

        sysEmailSendEntity.setMap(map);


        return sysEmailSendEntity;
    }

    private void sendAgentEmail(CustomApproveEntity entity, CustomInfoTable customInfoTable, SysEmailSendEntity sysEmailSendEntity) throws ServiceException {
        UserInfoTable agent = userInfoRepository.getFirstById(customInfoTable.getAgentId());
        if (agent == null) {
            return;
        }
        if(agent.getRoleId() < 0 ){
            UserInfoTable sales = userInfoRepository.getFirstById(agent.getSalesId());
            if (sales == null) {
                return;
            }
            if (Constants.PASSED_STATUS.equals(customInfoTable.getStatus())) {
                sendCustomVerifySuccessAgentEmail(customInfoTable,agent);
                sendCustomVerifySuccessSalesEmail(customInfoTable,sales);
            }else if (Constants.REJECTED_STATUS.equals(customInfoTable.getStatus())) {
                sendCustomVerifyFailAgentEmail(customInfoTable,agent,sysEmailSendEntity);
                sendCustomVerifyFailSalesEmail(customInfoTable,sales,sysEmailSendEntity);
            }
        }else{
            if (Constants.PASSED_STATUS.equals(customInfoTable.getStatus())) {
                sendCustomVerifySuccessSalesEmail(customInfoTable,agent);
            }else if (Constants.REJECTED_STATUS.equals(customInfoTable.getStatus())) {
                sendCustomVerifyFailSalesEmail(customInfoTable,agent,sysEmailSendEntity);
            }
        }
    }

    private void sendCustomVerifySuccessAgentEmail(CustomInfoTable customInfoTable,UserInfoTable agent) throws ServiceException {
        if (customInfoTable == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
        Map<String, String> map = new HashMap<>(5);
        String name = CustomInfoUtil.getName(customInfoTable);

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

        SysEmailSendEntity sysEmailSendEntity = new SysEmailSendEntity();
        sysEmailSendEntity.setSubject("CWG CUSTOM APPROVE AGENT SUCCESS");
        sysEmailSendEntity.setEmailSendEnum(EmailSendEnum.CUSTOM_APPROVE_AGENT_SUCCESS);
        sysEmailSendEntity.setMap(map);
        if (CountryUtil.isCN(customInfoTable.getCountry())) {
            sysEmailSendEntity.setTemplateName(SystemEmailCodeConstants.CUSTOM_VERIFICATION_SUCCESS_AGENT_CN);
        } else {
            sysEmailSendEntity.setTemplateName(SystemEmailCodeConstants.CUSTOM_VERIFICATION_SUCCESS_AGENT_EN);
        }

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

    private void sendCustomVerifySuccessSalesEmail(CustomInfoTable customInfoTable,UserInfoTable sales) throws ServiceException {
        if (customInfoTable == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
        Map<String, String> map = new HashMap<>(5);
        String name = CustomInfoUtil.getName(customInfoTable);

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

        SysEmailSendEntity sysEmailSendEntity = new SysEmailSendEntity();
        sysEmailSendEntity.setSubject("CWG CUSTOM APPROVE SALES SUCCESS");
        sysEmailSendEntity.setEmailSendEnum(EmailSendEnum.CUSTOM_APPROVE_SALES_SUCCESS);
        sysEmailSendEntity.setMap(map);
        if (CountryUtil.isCN(customInfoTable.getCountry())) {
            sysEmailSendEntity.setTemplateName(SystemEmailCodeConstants.CUSTOM_VERIFICATION_SUCCESS_SALES_CN);
        } else {
            sysEmailSendEntity.setTemplateName(SystemEmailCodeConstants.CUSTOM_VERIFICATION_SUCCESS_SALES_EN);
        }

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

    private void sendCustomVerifyFailAgentEmail(CustomInfoTable customInfoTable, UserInfoTable agent, SysEmailSendEntity sendEntity) throws ServiceException {
        if (customInfoTable == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
        Map<String, String> map = new HashMap<>(6);
        String name = CustomInfoUtil.getName(customInfoTable);

        map.put(MapConstants.DATE_TIME, DateUtil.formatTime(new Date()));
        map.put(MapConstants.NAME, name);
        map.put(MapConstants.EMAIL, customInfoTable.getEmail());
        map.put(MapConstants.V_ENGLISH_NAME_V, customInfoTable.getNameEn());
        map.put(MapConstants.C_ID, String.valueOf(customInfoTable.getCId()));
        map.put(MapConstants.REASONS_REFUSAL, sendEntity.getMap().get(MapConstants.REASONS_REFUSAL));

        SysEmailSendEntity sysEmailSendEntity = new SysEmailSendEntity();
        sysEmailSendEntity.setSubject("CWG CUSTOM APPROVE AGENT FAIL");
        sysEmailSendEntity.setEmailSendEnum(EmailSendEnum.CUSTOM_APPROVE_AGENT_FAIL);
        sysEmailSendEntity.setMap(map);
        if (CountryUtil.isCN(customInfoTable.getCountry())) {
            sysEmailSendEntity.setTemplateName(SystemEmailCodeConstants.CUSTOM_VERIFICATION_FAIL_AGENT_CN);
        } else {
            sysEmailSendEntity.setTemplateName(SystemEmailCodeConstants.CUSTOM_VERIFICATION_FAIL_AGENT_EN);
        }

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

    private void sendCustomVerifyFailSalesEmail(CustomInfoTable customInfoTable,UserInfoTable sales, SysEmailSendEntity sendEntity) throws ServiceException {
        if (customInfoTable == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
        Map<String, String> map = new HashMap<>(6);
        String name = CustomInfoUtil.getName(customInfoTable);

        map.put(MapConstants.DATE_TIME, DateUtil.formatTime(new Date()));
        map.put(MapConstants.NAME, name);
        map.put(MapConstants.EMAIL, customInfoTable.getEmail());
        map.put(MapConstants.V_ENGLISH_NAME_V, customInfoTable.getNameEn());
        map.put(MapConstants.C_ID, String.valueOf(customInfoTable.getCId()));
        map.put(MapConstants.REASONS_REFUSAL, sendEntity.getMap().get(MapConstants.REASONS_REFUSAL));


        SysEmailSendEntity sysEmailSendEntity = new SysEmailSendEntity();
        sysEmailSendEntity.setSubject("CWG CUSTOM APPROVE SALES FAIL");
        sysEmailSendEntity.setEmailSendEnum(EmailSendEnum.CUSTOM_APPROVE_SALES_FAIL);
        sysEmailSendEntity.setMap(map);
        if (CountryUtil.isCN(customInfoTable.getCountry())) {
            sysEmailSendEntity.setTemplateName(SystemEmailCodeConstants.CUSTOM_VERIFICATION_FAIL_SALES_CN);
        } else {
            sysEmailSendEntity.setTemplateName(SystemEmailCodeConstants.CUSTOM_VERIFICATION_FAIL_SALES_EN);
        }

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



    @Override
    public CustomInfoDto getSingleCustomInfo(Long id) throws Exception {
        /*
            获取基本信息
         */
        CustomInfoTable infoTable = customInfoRepository.getFirstByCId(id);
        if (infoTable == null) {
            throw new ServiceException(Constants.INFO_NOT_FOUND);
        }

        return getCustomInfo(infoTable);
    }

    @Override
    public CustomInfoDto getSingleCustomInfoByCId(Long id) throws Exception {
        /*
            获取基本信息
         */
        CustomView customView = customInfoDao.getOneByCId(id);
        if (customView == null) {
            throw new ServiceException(Constants.INFO_NOT_FOUND);
        }

        return getCustomInfo(customView);
    }

    private CustomInfoDto getCustomInfo(CustomView customView) throws Exception {

        CustomInfoDto infoDto = new CustomInfoDto();
        BeanUtils.copyProperties(customView, infoDto);
        if (customView.getAddressLine() != null) {
            infoDto.setAddressLines(Arrays.asList(customView.getAddressLine().split("@#")));
        }
        /*
            获取文件信息
         */
        return getCustomInfoDto(infoDto, customView.getId());
    }

    @NotNull
    private CustomInfoDto getCustomInfoDto(CustomInfoDto infoDto, Long id) {
        List<CustomFileTable> fileTables = customFileRepository.getAllByCustomId(id);
        List<CustomFileDto> fileDtos = Lists.newArrayList();
        for (CustomFileTable fileTable : fileTables) {
            CustomFileDto fileDto = new CustomFileDto();
            BeanUtils.copyProperties(fileTable, fileDto);
            fileDtos.add(fileDto);
        }
        infoDto.setFiles(fileDtos);

        return infoDto;
    }

    private CustomInfoDto getCustomInfo(CustomInfoTable infoTable) throws Exception {

        CustomInfoDto infoDto = new CustomInfoDto();

        /*
            获取财务背景信息
         */
        CustomSurveyTable surveyTable = customSurveyRepository.getTopByCustomId(infoTable.getId());
        if (surveyTable != null) {
            BeanUtils.copyProperties(surveyTable, infoDto);
        }
        if (infoTable.getAgentId() != null) {
            UserInfoTable userInfoTable = userInfoRepository.getFirstByCId(infoTable.getAgentId());
            if (userInfoTable != null) {
                infoDto.setAgent(userInfoTable.getIbNo() + " - " + userInfoTable.getName());
            }
        }

        if (infoTable.getCId() != null) {
            UserInfoTable userInfoTable = userInfoRepository.getFirstByCId(infoTable.getAgentId());
            if (userInfoTable != null) {
                infoDto.setIbNo(userInfoTable.getIbNo());
            }
        }

        BeanUtils.copyProperties(infoTable, infoDto);
        /*
            获取文件信息
         */
        return getCustomInfoDto(infoDto, infoTable.getId());
    }

    @Override
    public CustomInfoDto getSingleCustomByLogin(Long login) throws Exception {
        //根据login获取对应的客户ID
        Long customId = customLoginDao.getCustomIdByLogin(login);
        if (customId == null || customId <= 0) {
            throw new ServiceException(Constants.INFO_NOT_FOUND);
        }
        //获取信息
        CustomInfoDto customInfoDto = getSingleCustomInfo(customId);

        return customInfoDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDeleteByIdList(List<Long> ids) throws Exception {
        /*
            删除基本信息
         */
        customInfoDao.deleteInBatch(ids);
        /*
            删除调查信息
         */
        customSurveyDao.deleteInBatchByCustomId(ids);
        /*
            删除文件信息
         */
        List<String> files = customFileDao.getAllPathByCustomId(ids);
        customFileDao.deleteInBatchByCustomId(ids);
        /*
            删除文件
         */

        /*
            删除客户代理关系
         */

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePassword(CustomUpdatePasswordByManagerEntity entity) throws ServiceException {
        CustomInfoTable customInfoTable = customInfoRepository.findFirstById(entity.getId());

        if (customInfoTable == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        if (!entity.getPassword().equals(customInfoTable.getPassword())) {
            BeanUtils.copyProperties(entity, customInfoTable);
            customInfoRepository.save(customInfoTable);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDayWithdrawLimit(CustomLoginDayWithdrawLimitUpdateEntity entity) throws ServiceException {
        CustomInfoTable customInfoTable = customInfoRepository.findFirstById(entity.getId());

        if (customInfoTable == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        BeanUtils.copyProperties(entity, customInfoTable);
        customInfoRepository.save(customInfoTable);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateHide(CustomInfoUpdateHideEntity entity) throws ServiceException {
        if (entity.getHide() == null) {
            entity.setHide(0);
        }
        if (entity.getAgentId() != null) {
            //查找对应代理或者销售下的直客客户
            List<CustomInfoTable> customInfoTables = customInfoRepository.findAllByAgentId(entity.getAgentId());
            if (customInfoTables == null || customInfoTables.size() <= 0) {
                return;
            }
            List<CustomInfoTable> customInfoSaves = new ArrayList<>(customInfoTables.size());

            //构建并且判断和销售给直客暗点不同的客户
            for (CustomInfoTable customInfoTable : customInfoTables) {
                if (!entity.getHide().equals(customInfoTable.getHide())) {
                    customInfoTable.setHide(entity.getHide());
                    customInfoSaves.add(customInfoTable);
                }
            }
            //如果存在暗点不同的直客 则修改客户的暗点
            if (customInfoSaves != null && customInfoSaves.size() > 0) {
                customInfoRepository.save(customInfoSaves);
            }
        }
    }

    @Override
    public InfoEntity login(SingleLongEntity entity) throws ServiceException {

        //首先用邮箱和密码验证账号
        CustomInfoTable customInfoTable = customInfoRepository.getFirstById(entity.getId());

        log.error("customInfoTable:" + customInfoTable.toString());

        /*
            获取ib信息
         */
        IbInfoEntity ibInfoEntity = null;
        IbLoginEntity ibLoginEntity = new IbLoginEntity();
        ibLoginEntity.setLoginName(customInfoTable.getEmail());
        try {
            SingleLongEntity singleLongEntity = new SingleLongEntity();
            singleLongEntity.setId(customInfoTable.getCId());
            log.error("singleLongEntity:" + singleLongEntity.toString());
            BaseResultDto<IbInfoDto> ibInfoDtoBaseResultDto = ibInfoFeignService.getIbInfoByCid(singleLongEntity);
            log.error("ibInfoDtoBaseResultDto:" + ibInfoDtoBaseResultDto.toString());
            IbInfoDto ibInfoDto = null;
            if (ibInfoDtoBaseResultDto.getCode() == Constants.SUCCESS_CODE) {
                ibInfoDto = ibInfoDtoBaseResultDto.getData();
                if (ibInfoDto != null) {
                    ibInfoEntity = new IbInfoEntity();
                    BeanUtils.copyProperties(ibInfoDto, ibInfoEntity);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }

        CustomSurveyDto customSurveyDto = customSurveyService.getByCustomId(customInfoTable.getId());

        SysConfigTable sysConfigTable = sysConfigService.getByCode(ConfigConstants.SHOP_SHOW);
        boolean isShop = false;
        if (sysConfigTable != null) {
            int shopShow = Integer.parseInt(sysConfigTable.getValue());
            if (shopShow >= 1) {
                isShop = true;
            }
        }
        InfoEntity transform = transform(customInfoTable, ibInfoEntity, customSurveyDto, isShop);


        return transform;
    }

    @Override
    public Long getSalesIdByEmail(String email) {
        return customInfoDao.getSalesIdByEmail(email);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void verifyRealAgain(SingleLongEntity entity) throws ServiceException  {
        CustomInfoTable customInfoTable = customInfoRepository.findFirstById(entity.getId());

        SysConfigTable sysConfigTable = sysConfigService.getByCode(ConfigConstants.CUSTOM_VERIFY_KYC_PROPERTY);
        if (sysConfigTable == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
        SysKycConfigTable kycConfig = sysKycConfigService.getByCodeAndCountryAndEnable(sysConfigTable.getValue(),customInfoTable.getCountry(),1);
        if (kycConfig == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }

        customInfoTable.setSerial(UUIDUtil.getUUID());

        if(3!=kycConfig.getKycType()){
            CustomKycVerifyRecodeEntity customKycVerifyRecodeEntity = new CustomKycVerifyRecodeEntity();
            customKycVerifyRecodeEntity.setCountry(customInfoTable.getCountry());
            customKycVerifyRecodeEntity.setConfig(ConfigConstants.CUSTOM_VERIFY_KYC_PROPERTY);
            customKycVerifyRecodeEntity.setExternalUserId(customInfoTable.getSerial());
            customKycVerifyRecodeEntity.setVerifyId(customInfoTable.getId());
            customKycVerifyRecodeEntity.setCardType(customInfoTable.getCardType());
            customKycVerifyRecodeEntity.setApplicantId(kycFeignService.createApplicant(customKycVerifyRecodeEntity));

            /*List<CustomFileTable> fileList = customFileDao.findFileByType(customInfoTable.getId());
            if (fileList != null && fileList.size() > 0) {
                customKycVerifyRecodeEntity.setVerifyType(1);
                customKycVerifyRecodeEntity.setVerifyFile(fileList.stream().map(CustomFileTable::getPath).collect(Collectors.joining(",")));
                kycFeignService.uploadImage(customKycVerifyRecodeEntity);
            }*/

            customInfoTable.setApplicantId(customKycVerifyRecodeEntity.getApplicantId());
        }else{
            customInfoTable.setApplicantId(null);
        }

        customInfoTable.setAuthStatus(0);
        customInfoTable.setKycVerifyUrl(null);
        customInfoRepository.save(customInfoTable);
    }

    @Override
    public List<CustomListDto> getUcardCustomList(CustomSearchEntity entity) {
        List<CustomView> views = customInfoDao.getUcardCustomList(entity);

        List<CustomListDto> dtos = new ArrayList();
        for (CustomView view : views) {
            CustomListDto dto = new CustomListDto();
            BeanUtils.copyProperties(view, dto);
            dtos.add(dto);
        }
        return dtos;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CustomInfoTable addCustom(UserEntryTable entryTable, UserInfoTable userInfoTable) throws ServiceException  {
        CustomInfoTable customTable = new CustomInfoTable();
        customTable.setLastName(entryTable.getLastName());
        customTable.setFirstName(entryTable.getFirstName());
        customTable.setNameEn(entryTable.getEnglishName());
        customTable.setEmail(entryTable.getGoogleEmail());
        customTable.setPassword(MD5Util.getMD5(entryTable.getGooglePassword()));
        customTable.setNationality(entryTable.getNationality());
        customTable.setAreaCode(entryTable.getCallingCode());
        customTable.setPhone(entryTable.getPhoneNumbe());
        customTable.setAgentId(userInfoTable.getId());
        customTable.setHide(0);
        customTable.setComPoint(0f);
        customTable.setCId(userInfoTable.getCId());
        customTable.setIbId(userInfoTable.getId());
        customTable.setSalesSettingLevel(1);
        customTable.setGender(entryTable.getGender());
        customTable.setBirth(entryTable.getBirthday());
        customTable.setCountry(entryTable.getCountry());
        //获取国家信息
        SysCountryTable sysCountryTable = sysCountryService.getByCode(entryTable.getCountry());
        customTable.setCountryEnName(sysCountryTable.getEnName());
        customTable.setCountryName(sysCountryTable.getName());

        customTable.setCheckEmail(1);
        customTable.setCheckPhone(1);
        customTable.setStatus(2);
        customTable.setApplyRealStatus(2);
        customTable.setApplyRealTime(new Date());
        customTable.setValid(1);
        customTable.setIbInvalid(1);
        customTable.setBalance(BigDecimal.ZERO);
        customTable.setPayCommentValid(0);
        customTable.setAddTime(new Date());
        customTable.setAreaId(userInfoTable.getAreaId());
        customTable.setAuthStatus(Constants.APPLY_REAL_STATUS);
        customTable.setName(CustomInfoUtil.getName(customTable.getFirstName(),null, customTable.getLastName(),customTable.getCountry()));
        customTable.setApproveTime(new Date());
        customInfoRepository.save(customTable);

        if(!Strings.isNullOrEmpty(entryTable.getEntryFile())){
            String[] files = entryTable.getEntryFile().split(",");
            for (String filePatn : files){
                CustomFileTable fileTable = new CustomFileTable();
                fileTable.setCustomId(customTable.getId());
                fileTable.setType(1);
                fileTable.setPath(filePatn);
                fileTable.setStatus(2);
                fileTable.setAddTime(new Date());
                customFileRepository.save(fileTable);
            }
        }
        return customTable;
    }

    @JmsListener(destination = Constants.KYC_APPROVE_REAL)
    @Transactional(rollbackFor = Exception.class)
    public void callbackKycVerify(String content) throws ServiceException {
        log.info(String.format("KYC_APPROVE_REAL,content:%s", content));
        CustomApproveEntity entity = JSON.parseObject(content, CustomApproveEntity.class);
        if (null == entity) {
            log.error("KYC_APPROVE_REAL,callbackEntity is null");
            return;
        }
        this.approve(entity);
    }

    private InfoEntity transform(CustomInfoTable customInfoTable, IbInfoEntity ibInfoEntity,
                                 CustomSurveyDto customSurveyDto, boolean isShop) {

        InfoEntity infoEntity = new InfoEntity();

        CustomInfoEntity customInfoEntity = new CustomInfoEntity();
        BeanUtils.copyProperties(customInfoTable, customInfoEntity);


        UserInfoTable agent = userInfoRepository.getFirstById(customInfoTable.getAgentId());
        if (agent!=null)
        {
            customInfoEntity.setAgentTransfer(agent.getAgentTransfer());
        }

        if (!Strings.isNullOrEmpty(customInfoTable.getAddressLine())) {

            customInfoEntity.setAddressLines(Arrays.asList(customInfoTable.getAddressLine().split("@#")));
        }
        //默认返回到前端为0
        if (customInfoTable.getIbInvalid() == null) {
            customInfoEntity.setIbInvalid(0);
        }
        if (customSurveyDto != null) {
            BeanUtils.copyProperties(customSurveyDto, customInfoEntity);
        }
        infoEntity.setCustomInfo(customInfoEntity);
        infoEntity.setIbInfo(ibInfoEntity);

        infoEntity.setId(customInfoEntity.getId());
        infoEntity.setValid(customInfoEntity.getValid());
        infoEntity.setFirstName(customInfoEntity.getFirstName());
        infoEntity.setMiddle(customInfoEntity.getMiddle());
        infoEntity.setLastName(customInfoEntity.getLastName());
        infoEntity.setLang(customInfoTable.getLang());

        if (ibInfoEntity == null) {
            infoEntity.setIsIb(false);
        } else {
            infoEntity.setIsIb(true);
        }
        infoEntity.setIsShop(isShop);

        return infoEntity;
    }

}
