package com.crm.manager.service.impl;

import com.crm.manager.dao.mapper.SysEmailConfigMapper;
import com.crm.manager.dao.repository.SysEmailConfigRepository;
import com.crm.manager.service.SysEmailConfigService;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.constant.EmailSendEnum;
import com.crm.rely.backend.core.constant.MapConstants;
import com.crm.rely.backend.core.constant.GlobalSystemEmailCodeConstants;
import com.crm.rely.backend.core.dto.base.PageDto;
import com.crm.rely.backend.core.dto.base.ResultWithPagerDto;
import com.crm.rely.backend.core.dto.system.email.config.SysEmailConfigSearchDto;
import com.crm.rely.backend.core.entity.system.config.SendUpdateEmailCodeEntity;
import com.crm.rely.backend.core.entity.system.email.SysEmailSendEntity;
import com.crm.rely.backend.core.entity.system.email.config.*;
import com.crm.rely.backend.core.pojo.table.SysEmailConfigTable;
import com.crm.rely.backend.core.exception.ServiceException;
import com.crm.rely.backend.service.EmailService;
import com.crm.rely.backend.util.DateUtil;
import com.crm.rely.backend.util.GetRandom;
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.*;

@Service
public class SysEmailConfigServiceImpl implements SysEmailConfigService {
    @Autowired
    private SysEmailConfigRepository sysEmailConfigRepository;

    @Autowired
    private SysEmailConfigMapper sysEmailConfigMapper;

    @Autowired
    private EmailService emailService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SysEmailConfigAddEntity entity) throws ServiceException {
        emailService.validateCode(entity.getEmail(), entity.getEmailCode());

        SysEmailConfigTable sysEmailConfigTable = new SysEmailConfigTable();
        BeanUtils.copyProperties(entity, sysEmailConfigTable);
        sysEmailConfigRepository.save(sysEmailConfigTable);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysEmailConfigUpdateEntity entity) throws ServiceException {
        emailService.validateCode(entity.getEmail(), entity.getEmailCode());

        SysEmailConfigTable sysEmailConfigTable = sysEmailConfigRepository.findFirstById(entity.getId());

        if (sysEmailConfigTable == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }

        BeanUtils.copyProperties(entity, sysEmailConfigTable);
        sysEmailConfigRepository.save(sysEmailConfigTable);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void save(SysEmailConfigBatchUpdateEntity entity, List<SysEmailConfigBaseUpdateEntity> entitys) throws ServiceException {

        emailService.validateCode(entity.getEmail(), entity.getEmailCode());


        List<SysEmailConfigTable> sysEmailConfigTables = sysEmailConfigRepository.findAll();

        if (entitys == null || entitys.size() <= 0) {
            sysEmailConfigRepository.delete(sysEmailConfigTables);
        }


        List<SysEmailConfigTable> emailConfigSaveTables = new ArrayList<>(entitys.size());

        int size = entitys.size();
        for (int i = 0; i < size; i++) {
            SysEmailConfigBaseUpdateEntity sysEmailConfigBaseUpdateEntity = entitys.get(i);
            SysEmailConfigTable sysEmailConfigSaveTable = null;
            if (sysEmailConfigBaseUpdateEntity.getId() != null) {
                int sysEmailConfigTableSize = sysEmailConfigTables.size();
                for (int j = 0; j < sysEmailConfigTableSize; ) {
                    SysEmailConfigTable sysEmailConfigTable = sysEmailConfigTables.get(j);
                    if (sysEmailConfigTable.getId().equals(sysEmailConfigBaseUpdateEntity.getId())) {
                        sysEmailConfigSaveTable = sysEmailConfigTable;
                        BeanUtils.copyProperties(sysEmailConfigBaseUpdateEntity, sysEmailConfigSaveTable);
                        sysEmailConfigTables.remove(sysEmailConfigTable);
                        sysEmailConfigTableSize--;
                    } else {
                        j++;
                    }
                }
            }
            if (sysEmailConfigSaveTable == null) {
                sysEmailConfigSaveTable = new SysEmailConfigTable();
                BeanUtils.copyProperties(sysEmailConfigBaseUpdateEntity, sysEmailConfigSaveTable);
                sysEmailConfigSaveTable.setId(null);
                sysEmailConfigSaveTable.setAddIp(sysEmailConfigBaseUpdateEntity.getModifyIp());
                sysEmailConfigSaveTable.setAddUser(sysEmailConfigBaseUpdateEntity.getModifyUser());
                sysEmailConfigSaveTable.setAddTime(sysEmailConfigBaseUpdateEntity.getModifyTime());
                sysEmailConfigSaveTable.setModifyTime(null);
                sysEmailConfigSaveTable.setModifyIp(null);
                sysEmailConfigSaveTable.setModifyUser(null);
            }
            emailConfigSaveTables.add(sysEmailConfigSaveTable);
        }


        if (emailConfigSaveTables != null && !emailConfigSaveTables.isEmpty()) {
            sysEmailConfigRepository.save(emailConfigSaveTables);
        }

        if (sysEmailConfigTables != null && !sysEmailConfigTables.isEmpty()) {
            sysEmailConfigRepository.delete(sysEmailConfigTables);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(SysEmailConfigDeleteEntity entity) throws ServiceException {
        emailService.validateCode(entity.getEmail(), entity.getEmailCode());
        List<SysEmailConfigTable> sysEmailConfigTables = sysEmailConfigRepository.findByIdIn(entity.getIds());

        if (sysEmailConfigTables == null && sysEmailConfigTables.size() <= 0) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        sysEmailConfigRepository.delete(sysEmailConfigTables);
    }

    @Override
    public ResultWithPagerDto<SysEmailConfigSearchDto> searchPageList(SysEmailConfigSearchEntity entity) throws ServiceException {
        Integer count = sysEmailConfigMapper.countList(entity);
        PageDto pageDto = PageDto.format(entity, count);
        if (count == null || count <= 0) {
            return ResultWithPagerDto.success(pageDto);
        }
        List<SysEmailConfigTable> sysEmailConfigTables = sysEmailConfigMapper.pageList(entity);

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

            throw new ServiceException(Constants.SYSTEM_ERROR);
        }
        List<SysEmailConfigSearchDto> sysEmailConfigSearchDtos = new ArrayList<>(sysEmailConfigTables.size());

        for (SysEmailConfigTable sysEmailConfigTable : sysEmailConfigTables) {
            SysEmailConfigSearchDto sysConfigSearchDto = transform(sysEmailConfigTable);
            sysEmailConfigSearchDtos.add(sysConfigSearchDto);
        }

        return ResultWithPagerDto.success(pageDto, sysEmailConfigSearchDtos);
    }

    @Override
    public List<SysEmailConfigSearchDto> searchList() throws ServiceException {

        List<SysEmailConfigTable> sysEmailConfigTables = sysEmailConfigRepository.findAll();

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

            return null;
        }
        List<SysEmailConfigSearchDto> sysEmailConfigSearchDtos = new ArrayList<>(sysEmailConfigTables.size());

        for (SysEmailConfigTable sysEmailConfigTable : sysEmailConfigTables) {
            SysEmailConfigSearchDto sysConfigSearchDto = transform(sysEmailConfigTable);
            sysEmailConfigSearchDtos.add(sysConfigSearchDto);
        }

        return sysEmailConfigSearchDtos;
    }

    @Override
    public SysEmailConfigSearchDto searchSingle(SysEmailConfigSingleEntity entity) throws ServiceException {
        SysEmailConfigTable emailConfigTable = sysEmailConfigRepository.getFirstById(entity.getId());

        if (emailConfigTable == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        return transform(emailConfigTable);

    }

    @Override
    public void sendEmailCode(SendUpdateEmailCodeEntity entity) throws ServiceException {

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

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

    private SysEmailSendEntity createSendEmailCodeEntity(SendUpdateEmailCodeEntity 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_CONFIG_EMAIL_CODE);

        sysEmailSendEntity.setTemplateName(GlobalSystemEmailCodeConstants.CONFIG_UPDATE_EMAIL_CODE_SEND);

        sysEmailSendEntity.setMap(map);

        return sysEmailSendEntity;
    }

    private SysEmailConfigSearchDto transform(SysEmailConfigTable sysConfigTable) {
        SysEmailConfigSearchDto sysEmailConfigSearchDto = new SysEmailConfigSearchDto();
        BeanUtils.copyProperties(sysConfigTable, sysEmailConfigSearchDto);
        return sysEmailConfigSearchDto;
    }
}
