package com.crm.manager.service.impl;

import com.crm.manager.dao.mapper.CustomFileDao;
import com.crm.manager.dao.mapper.CustomInfoDao;
import com.crm.manager.dao.mapper.CustomLoginDao;
import com.crm.manager.dao.repository.CustomBankRepository;
import com.crm.manager.dao.repository.CustomFileRepository;
import com.crm.manager.dao.repository.CustomInfoRepository;
import com.crm.manager.dao.repository.UserInfoRepository;
import com.crm.manager.service.*;
import com.crm.rely.backend.configuration.LocaleMessage;
import com.crm.rely.backend.core.constant.*;
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.file.CustomFileDto;
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.CustomFileTable;
import com.crm.rely.backend.model.dto.custom.CustomInfoDto;
import com.crm.rely.backend.model.dto.custom.potential.CustomListDto;
import com.crm.rely.backend.model.entity.custom.info.CustomApproveEntity;
import com.crm.rely.backend.model.entity.custom.info.CustomInfoEntity;
import com.crm.rely.backend.model.entity.custom.info.CustomSearchEntity;
import com.crm.rely.backend.model.pojo.table.CustomBankTable;
import com.crm.rely.backend.model.pojo.table.CustomInfoTable;
import com.crm.rely.backend.model.pojo.table.UserInfoTable;
import com.crm.rely.backend.model.pojo.view.CustomView;
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.DateUtil;
import com.crm.rely.backend.util.FormatPage;
import com.crm.rely.backend.util.RexUtil;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

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

    @Autowired
    private CustomInfoDao customInfoDao;
    @Autowired
    private CustomInfoRepository customInfoRepository;
    @Autowired
    private CustomFileRepository customFileRepository;
    @Autowired
    private CustomBankRepository customBankRepository;
    @Autowired
    private CustomLoginDao customLoginDao;
    @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 SysConfigService sysConfigService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private CustomBankService customBankService;

    @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 {
        /*
            获取列表
         */
        List<CustomView> views = customInfoDao.listCustom(entity);

        List<CustomListDto> dtos = Lists.newArrayList();
        for (CustomView view : views) {
            CustomListDto dto = new CustomListDto();
            BeanUtils.copyProperties(view, dto);

            /*if (!Strings.isNullOrEmpty(entity.getStamp())) {
                dto.setPhone(RexUtil.rexPhone(dto.getPhone()));
            }*/
            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 (StatusConstants.APPLY_STATUS.equals(entity.getStatus())) {
//            if (!StatusConstants.PASSED_STATUS.equals(customInfoTable.getStatus())
//                    || !StatusConstants.PASSED_STATUS.equals(customInfoTable.getApplyRealStatus())) {
//                throw ServiceException.exception(Constants.CANNOT_APPROVE);
//            }
//        } else {
//            //判断是否可申请条件 申请状态为初始状态
//            //申请转正状态为申请中 如果不满足这些条件 返回不符合申请状态
//            if (customInfoTable.getApplyRealStatus() == null
//                    || customInfoTable.getApplyRealStatus().equals(StatusConstants.PASSED_STATUS)
//                    || StatusConstants.PASSED_STATUS.equals(customInfoTable.getStatus())) {
//                throw ServiceException.exception(Constants.CANNOT_APPROVE);
//            }
//        }

//        //验证学号
//        if (Strings.isNullOrEmpty(entity.getSno())) {
//            entity.setSno(customInfoTable.getSno());
//        } else {
//            if (!entity.getSno().equals(customInfoTable.getSno())) {
//                existBySno(entity.getSno());
//            }
//        }
//
//        //验证证件号
//        if (Strings.isNullOrEmpty(entity.getIdentity())) {
//            entity.setIdentity(customInfoTable.getIdentity());
//        } else {
//            if (!entity.getIdentity().equals(customInfoTable.getIdentity())) {
//                existByIdentity(entity.getIdentity());
//            }
//        }

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

        BeanUtils.copyProperties(entity, customInfoTable);

        List<CustomFileTable> fileTables = null;
        Integer status;
        //判断是否审核通过 如果审核通过 将还属于审核中的文件设置为通过 重新上传的文件需要手动审批
        if (StatusConstants.PASSED_STATUS.equals(entity.getStatus())) {

            if (!Strings.isNullOrEmpty(customInfoTable.getSno())) {
                existsBySnoAndIdNot(customInfoTable.getSno(), customInfoTable.getId());
            }

            fileTables = customFileRepository.findAllByCustomIdAndStatus(customInfoTable.getId(),
                    StatusConstants.APPLY_STATUS);
            status = StatusConstants.PASSED_STATUS;
            fileTables.forEach(v -> v.setStatus(StatusConstants.PASSED_STATUS));

            //添加代理信息
            UserInfoTable ibTable = userInfoService.add(customInfoTable);
            customInfoTable.setIbId(ibTable.getId());

            customInfoTable.setApplyRealStatus(StatusConstants.PASSED_STATUS);
            customInfoTable.setStatus(StatusConstants.PASSED_STATUS);

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

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

        if (fileTables != null && fileTables.size() > 0) {
            fileTables.forEach(v -> v.setStatus(status));
            customFileRepository.save(fileTables);
        }

        customInfoRepository.save(customInfoTable);

        //修改银行卡信息
//        CustomBankAddEntity customBankAddEntity = new CustomBankAddEntity();
//        BeanUtils.copyProperties(entity, customBankAddEntity);
//        customBankAddEntity.setCustomId(entity.getId());
//        customBankService.add(customBankAddEntity);

        try {

            //发送审核结果邮件
            SysEmailSendEntity sysEmailSendEntity = null;
            if (StatusConstants.PASSED_STATUS.equals(customInfoTable.getStatus())) {
                sysEmailSendEntity = createCustomVerificationSuccessSysEmailEntity(customInfoTable);
            } else if (StatusConstants.REJECTED_STATUS.equals(customInfoTable.getStatus())) {
                sysEmailSendEntity = createCustomVerificationFailSysEmailEntity(customInfoTable, entity);
            }
            if (sysEmailSendEntity != null) {
                emailService.sendEmail(sysEmailSendEntity);

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

            //更新redis数据
            CustomInfoEntity custom = redisService.getEntity(PrefixEnum.PREFIX_CUSTOM.getCode() + entity.getId(),
                    CustomInfoEntity.class);
            if (custom != null) {

                BeanUtils.copyProperties(entity, custom);
                custom.setIbId(customInfoTable.getIbId());
                redisService.save(PrefixEnum.PREFIX_CUSTOM.getCode() + entity.getId(), custom);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    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()));
        }
    }

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

    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 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 = "CUSTOM_VERIFICATION_SUCCESS_SEND_CN";
        String lang = customInfoTable.getLang();

        if (Strings.isNullOrEmpty(lang)) {
            lang = customInfoTable.getCountry();
        }

        sysEmailSendEntity.setTemplateName(templateName);

        sysEmailSendEntity.setMap(map);

        return sysEmailSendEntity;
    }

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

        if (customInfoTable == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
        String reasonsRefusal = entity.getApproveDesc();


        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;
        templateName = "CUSTOM_VERIFICATION_FAIL_SEND_CN";

        sysEmailSendEntity.setTemplateName(templateName);

        sysEmailSendEntity.setMap(map);

        return sysEmailSendEntity;
    }

    @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);
    }

    @Override
    public CustomInfoTable getSingleCustomInfoByEmail(String email) {
         /*
            获取基本信息
         */
        CustomInfoTable customInfoTable = customInfoRepository.getFirstByEmail(email);


        return customInfoTable;
    }

    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);

        CustomBankTable bankTable = customBankRepository.findFirstByCustomId(id);
        if (bankTable != null) {
            infoDto.setBankAddr(bankTable.getBankAddr());
            infoDto.setBankBack(bankTable.getBankBack());
            infoDto.setBankBranchName(bankTable.getBankBranchName());
            infoDto.setBankCardNum(bankTable.getBankCardNum());
            infoDto.setBankFront(bankTable.getBankFront());
            infoDto.setBankCode(bankTable.getBankCode());
            infoDto.setBankUname(bankTable.getBankUname());
            infoDto.setSwiftCode(bankTable.getSwiftCode());
            infoDto.setBankName(bankTable.getBankName());
        }

        infoDto.setFiles(fileDtos);
        return infoDto;
    }

    private CustomInfoDto getCustomInfo(CustomInfoTable infoTable) throws Exception {

        CustomInfoDto infoDto = new CustomInfoDto();

        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);
        /*
            删除文件信息
         */
        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);
//        }
//
//    }

}
