package com.crm.manager.service.impl;

import com.crm.manager.dao.mapper.SysEmailTemplateMapper;
import com.crm.manager.dao.repository.SysEmailTemplateRepository;
import com.crm.manager.service.SysEmailTemplateService;
import com.crm.manager.service.impl.base.BaseUploadServiceImpl;
import com.crm.rely.backend.core.constant.*;
import com.crm.rely.backend.core.dto.base.BaseResultDto;
import com.crm.rely.backend.core.dto.base.PageDto;
import com.crm.rely.backend.core.dto.base.ResultWithPagerDto;
import com.crm.rely.backend.core.dto.system.email.template.SysEmailTemplateSearchDto;
import com.crm.rely.backend.core.entity.base.SingleLongEntity;
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.template.*;
import com.crm.rely.backend.model.entity.user.info.*;
import com.crm.rely.backend.core.pojo.table.SysEmailTemplateTable;
import com.crm.rely.backend.core.pojo.view.SysEmailTemplateView;
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 org.springframework.web.multipart.MultipartFile;

import java.util.*;

@Service
public class SysEmailTemplateServiceImpl extends BaseUploadServiceImpl implements SysEmailTemplateService {

    @Autowired
    private SysEmailTemplateRepository sysEmailTemplateRepository;

    @Autowired
    private SysEmailTemplateMapper sysEmailTemplateMapper;

    @Autowired
    private EmailService emailService;

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

        existCode(entity.getCode());

        SysEmailTemplateTable sysEmailTemplateTable = new SysEmailTemplateTable();
        BeanUtils.copyProperties(entity, sysEmailTemplateTable);
        sysEmailTemplateRepository.save(sysEmailTemplateTable);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(SysEmailTemplateDeleteEntity entity, UserInfoEntity infoEntity) throws ServiceException {
        emailService.validateCode(entity.getEmail(), entity.getEmailCode());

        List<SysEmailTemplateTable> sysEmailTemplateTables = sysEmailTemplateRepository.findByIdIn(entity.getIds());

        if (sysEmailTemplateTables == null || sysEmailTemplateTables.size() <= 0) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        /**
         * 判断是否是超级管理员 如果是则可以操作 如果不是 则在删除系统标识的邮件模版提示无权限
         */
        if (!PrefixEnum.PREFIX_SYSTEM.equals(infoEntity.getPrefix())) {
            for (SysEmailTemplateTable sysEmailTemplateTable : sysEmailTemplateTables) {
                if (Constants.EMAIL_TYPE_SYSTEM.equals(sysEmailTemplateTable.getType())) {
                    throw ServiceException.exception(Constants.NOT_PERMIT);
                }
            }
        }
        sysEmailTemplateRepository.delete(sysEmailTemplateTables);
    }

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

        SysEmailTemplateTable sysEmailTemplateTable = sysEmailTemplateRepository.findFirstById(entity.getId());
        if (!PrefixEnum.PREFIX_SYSTEM.equals(infoEntity.getPrefix())) {
            if (Constants.EMAIL_TYPE_SYSTEM.equals(sysEmailTemplateTable.getType())) {
                throw ServiceException.exception(Constants.NOT_PERMIT);
            }
        }
        BeanUtils.copyProperties(entity, sysEmailTemplateTable);

        sysEmailTemplateRepository.save(sysEmailTemplateTable);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysEmailTemplateBatchEntity entity, List<SysEmailTemplateBaseEntity> entitys) throws ServiceException {
        emailService.validateCode(entity.getEmail(), entity.getEmailCode());
        List<SysEmailTemplateTable> sysEmailTemplateTables = sysEmailTemplateRepository.findAllByNotificationObject(entity.getNotificationObject());

        if (entitys == null || entitys.size() <= 0) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }

        List<SysEmailTemplateTable> emailTemplateSaveTables = new ArrayList<>(entitys.size());

        int size = entitys.size();
        for (int i = 0; i < size; i++) {
            SysEmailTemplateBaseEntity sysEmailTemplateBaseEntity = entitys.get(i);
            SysEmailTemplateTable emailTemplateSaveTable = null;
            if (sysEmailTemplateBaseEntity.getId() != null) {
                int sysEmailConfigTableSize = sysEmailTemplateTables.size();
                for (int j = 0; j < sysEmailConfigTableSize; ) {
                    SysEmailTemplateTable sysEmailTemplateTable = sysEmailTemplateTables.get(j);
                    if (sysEmailTemplateTable.getId().equals(sysEmailTemplateBaseEntity.getId())) {
                        emailTemplateSaveTable = sysEmailTemplateTable;
                        BeanUtils.copyProperties(sysEmailTemplateBaseEntity, emailTemplateSaveTable);

                        sysEmailTemplateTables.remove(sysEmailTemplateTable);
                        sysEmailConfigTableSize--;
                    } else {
                        j++;
                    }
                }
            }
            if (emailTemplateSaveTable == null) {
                emailTemplateSaveTable = new SysEmailTemplateTable();
                BeanUtils.copyProperties(sysEmailTemplateBaseEntity, emailTemplateSaveTable);
                emailTemplateSaveTable.setId(null);
                emailTemplateSaveTable.setAddIp(sysEmailTemplateBaseEntity.getModifyIp());
                emailTemplateSaveTable.setAddUser(sysEmailTemplateBaseEntity.getModifyUser());
                emailTemplateSaveTable.setAddTime(sysEmailTemplateBaseEntity.getModifyTime());
                emailTemplateSaveTable.setModifyTime(null);
                emailTemplateSaveTable.setModifyIp(null);
                emailTemplateSaveTable.setModifyUser(null);
            }
            emailTemplateSaveTables.add(emailTemplateSaveTable);
        }


        if (emailTemplateSaveTables != null && !emailTemplateSaveTables.isEmpty()) {
            sysEmailTemplateRepository.save(emailTemplateSaveTables);
        }

        if (sysEmailTemplateTables != null && !sysEmailTemplateTables.isEmpty()) {
            sysEmailTemplateRepository.delete(sysEmailTemplateTables);
        }
    }

    @Override
    public ResultWithPagerDto<SysEmailTemplateSearchDto> searchPageList(SysEmailTemplateSearchEntity entity) throws ServiceException {
        Integer count = sysEmailTemplateMapper.countList(entity);
        PageDto pageDto = PageDto.format(entity, count);
        if (count == null || count <= 0) {
            return ResultWithPagerDto.success(pageDto);
        }
        List<SysEmailTemplateSearchDto> sysEmailTemplateSearchDtos = getEmailTemplateSearchDto(entity);
        if (sysEmailTemplateSearchDtos == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }

        return ResultWithPagerDto.success(pageDto, sysEmailTemplateSearchDtos);
    }

    @Override
    public BaseResultDto<List<SysEmailTemplateSearchDto>> searchList(SysEmailTemplateSearchEntity entity) throws ServiceException {

        List<SysEmailTemplateSearchDto> sysEmailTemplateSearchDtos = getEmailTemplateSearchDto(entity);

        return BaseResultDto.success(sysEmailTemplateSearchDtos);
    }

    private List<SysEmailTemplateSearchDto> getEmailTemplateSearchDto(SysEmailTemplateSearchEntity entity) throws ServiceException {
        List<SysEmailTemplateView> sysEmailTemplateViews = sysEmailTemplateMapper.pageList(entity);

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

            return null;
        }
        List<SysEmailTemplateSearchDto> sysEmailTemplateSearchDtos = new ArrayList<>(sysEmailTemplateViews.size());

        for (SysEmailTemplateView sysEmailTemplateView : sysEmailTemplateViews) {
            SysEmailTemplateSearchDto sysEmailTemplateSearchDto = transform(sysEmailTemplateView);
            sysEmailTemplateSearchDtos.add(sysEmailTemplateSearchDto);
        }
        return sysEmailTemplateSearchDtos;
    }

    @Override
    public BaseResultDto searchList() throws ServiceException {

        List<SysEmailTemplateView> sysEmailTemplateViews = sysEmailTemplateMapper.list();

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

            throw new ServiceException(Constants.SYSTEM_ERROR);
        }
        List<SysEmailTemplateSearchDto> sysEmailTemplateSearchDtos = new ArrayList<>(sysEmailTemplateViews.size());

        for (SysEmailTemplateView sysEmailTemplateView : sysEmailTemplateViews) {
            SysEmailTemplateSearchDto sysEmailTemplateSearchDto = transform(sysEmailTemplateView);
            sysEmailTemplateSearchDtos.add(sysEmailTemplateSearchDto);
        }

        return BaseResultDto.success(sysEmailTemplateSearchDtos);
    }

    @Override
    public SysEmailTemplateSearchDto searchSingle(SingleLongEntity entity) throws ServiceException {
        SysEmailTemplateView sysEmailTemplateView = sysEmailTemplateMapper.getOne(entity.getId());

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

    @Override
    public String uploadFile(MultipartFile file) throws Exception {
        String middlePath = "/email/template";
        String path = saveFile(middlePath, file);

        return path;
    }

    @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 SysEmailTemplateSearchDto transform(SysEmailTemplateView sysEmailTemplateView) {
        SysEmailTemplateSearchDto sysEmailTemplateSearchDto = new SysEmailTemplateSearchDto();
        BeanUtils.copyProperties(sysEmailTemplateView, sysEmailTemplateSearchDto);
        return sysEmailTemplateSearchDto;
    }

    private void existCode(String code) throws ServiceException {
        boolean exist = sysEmailTemplateRepository.existsByCode(code);
        if (exist) {
            throw ServiceException.exception(ManagerConstant.EMAIL_CODE_EXIST);
        }
    }
}
