package com.cm.manager.sms.service.impl;

import com.cm.common.base.AbstractService;
import com.cm.common.exception.RemoveException;
import com.cm.common.exception.SaveException;
import com.cm.common.exception.SearchException;
import com.cm.common.exception.UpdateException;
import com.cm.common.pojo.ListPage;
import com.cm.common.result.SuccessResult;
import com.cm.common.result.SuccessResultList;
import com.cm.common.utils.HashMapUtil;
import com.cm.common.utils.UUIDUtil;
import com.cm.common.utils.email.SimpleMailSenderUtil;
import com.cm.manager.sms.config.properties.EmailProperties;
import com.cm.manager.sms.dao.email.IEmailDao;
import com.cm.manager.sms.pojo.dtos.email.EmailDTO;
import com.cm.manager.sms.pojo.vos.email.EmailVO;
import com.cm.manager.sms.service.IEmailService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: EmailServiceImpl
 * @Description: 邮件业务
 * @Author: WangGeng
 * @Date: 2020/7/31 4:19 下午
 * @Version: 1.0
 **/
@Service
public class EmailServiceImpl extends AbstractService implements IEmailService {

    @Autowired
    private EmailProperties emailProperties;
    @Autowired
    private IEmailDao emailDao;

    @Override
    public SuccessResult saveAndSendSystemEmail(EmailVO emailVO) throws Exception {
        if (!emailProperties.getActive()) {
            throw new SaveException("邮件未激活");
        }
        List<String> ccPersons = emailProperties.getCcPersons();
        StringBuilder ccSB = new StringBuilder();
        for (String ccPerson : ccPersons) {
            if (ccSB.length() > 0) {
                ccSB.append(",");
            }
            ccSB.append(ccPerson);
        }
        emailVO.setEmailCc(ccSB.toString());
        LOG.debug("发送邮件");
        boolean sendSuccess = SimpleMailSenderUtil.sendEmail(emailProperties.getSmtp(), emailProperties.getPort(),
                emailProperties.getSenderEmail(), emailProperties.getSenderPassword(),
                emailVO.getEmailReceiver(), emailVO.getEmailCc(), emailVO.getEmailSubject(),
                emailVO.getEmailContent(), emailVO.getEmailType());
        if (!sendSuccess) {
            LOG.error("邮件发送失败");
        }
        emailVO.setEmailSender(emailProperties.getSenderEmail());
        emailVO.setSendingStatus(sendSuccess ? 1 : 0);
        Map<String, Object> params = HashMapUtil.beanToMap(emailVO);
        params.put("emailId", UUIDUtil.getUUID());
        setSaveInfoByUserId(params, "1");
        emailDao.saveEmail(params);
        return new SuccessResult();
    }

    @Override
    public SuccessResult removeEmail(String ids) throws RemoveException {
        Map<String, Object> params = getHashMap(3);
        params.put("emailIds", Arrays.asList(ids.split("_")));
        setUpdateInfo(params);
        emailDao.removeEmail(params);
        return new SuccessResult();
    }

    @Override
    public SuccessResult updateReSendSystemEmailByEmailId(String emailId) throws Exception {
        EmailDTO emailDTO = getEmailById(emailId);
        if (emailDTO == null) {
            throw new SearchException("邮件信息不存在");
        }
        if (emailDTO.getSendingStatus() == 1) {
            throw new UpdateException("邮件已发送成功，无需重新发送");
        }
        LOG.debug("发送邮件");
        boolean sendSuccess = SimpleMailSenderUtil.sendEmail(emailProperties.getSmtp(), emailProperties.getPort(),
                emailProperties.getSenderEmail(), emailProperties.getSenderPassword(),
                emailDTO.getEmailReceiver(), emailDTO.getEmailCc(), emailDTO.getEmailSubject(),
                emailDTO.getEmailContent(), emailDTO.getEmailType());
        Map<String, Object> params = getHashMap(6);
        params.put("emailId", emailId);
        params.put("sendingStatus", sendSuccess ? 1 : 0);
        setUpdateInfo(params);
        emailDao.updateEmailSendingStatus(params);
        return new SuccessResult();
    }

    @Override
    public EmailDTO getEmailById(String emailId) throws SearchException {
        Map<String, Object> params = super.getHashMap(1);
        params.put("emailId", emailId);
        return emailDao.getEmail(params);
    }

    @Override
    public List<EmailDTO> listEmail(Map<String, Object> params) throws SearchException {
        return emailDao.listEmail(params);
    }

    @Override
    public SuccessResultList<List<EmailDTO>> listPageEmail(ListPage page) throws SearchException {
        PageHelper.startPage(page.getPage(), page.getRows());
        List<EmailDTO> emailDTOs = emailDao.listEmail(page.getParams());
        PageInfo<EmailDTO> pageInfo = new PageInfo<>(emailDTOs);
        return new SuccessResultList<>(emailDTOs, pageInfo.getPageNum(), pageInfo.getTotal());
    }
}
