package com.reyun.saas.mob.user.service.impl;

import com.reyun.saas.common.constants.MailEnumType;
import com.reyun.saas.common.constants.RoleEnumType;
import com.reyun.saas.common.properties.CommonProperties;
import com.reyun.saas.mob.user.domain.User;
import com.reyun.saas.mob.user.service.MailService;
import com.reyun.saas.mob.util.SendCloudComponent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@Transactional
public class MailServiceImpl implements MailService {

    @Autowired
    private SendCloudComponent sendCloudComponent;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private CommonProperties commonProperties;


    /**
     *
     * 发送 忘记密码时生成临时随机密码
     * @param user 目标用户
     * @return 是否成功
     * @throws Exception 在调用该方法处处理异常
     */
    @Override
    public Boolean sendNewPwd(User user, String newPwd, MailEnumType enumType) throws Exception {

        String title = null;
        String content = null;
        if(MailEnumType.ACTIVATE.equals(enumType)){
            //用户激活模板
            title = commonProperties.getActivateTitle();
            content = String.format(commonProperties.getActivateContent(),user.getActualName(),user.getUsername(),user.getUsername(), RoleEnumType.SUPER_USER.getRoleName(user.getRoleCategory()),newPwd);
        }else if(MailEnumType.FORGETPWD.equals(enumType)){
            //忘记密码模板
            title = commonProperties.getForgetPwdTitle();
            content = String.format(commonProperties.getForgetPwdContent(),newPwd);
        }else{
            //其他
            title = commonProperties.getPwdPastTitle();
            content = String.format(commonProperties.getPwdPastContent(),newPwd);
        }

        List<String> email = new LinkedList<>();
        email.add(user.getUsername());

        return sendCloudComponent.sendMailReuse(email, title, content.toString(), null, null);

    }


    @Override
    public Boolean isRepetitionSend(String email) {

        if(StringUtils.isEmpty(email)){
            return true;
        }
        String key = "sendEmail:"+email;
        return redisTemplate.opsForValue().setIfAbsent(key, "Send", 60, TimeUnit.SECONDS);
    }
}
