package com.sunda.spmsorder.service.impl;

import com.alibaba.druid.filter.config.ConfigTools;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmsorder.entity.MaterialMarmSap;
import com.sunda.spmsorder.mapper.MaterialMarmSapMapper;
import com.sunda.spmsorder.service.IMailService;
import com.sunda.spmsorder.service.IMaterialMarmSapService;
import com.sunda.spmsuser.mapper.SpmsUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;
import java.time.Duration;
import java.util.Random;

/**
 * <p>
 * 邮件发送
 * </p>
 *
 * @author HZC
 * @since 2023-04-23
 */
@Slf4j
@Service
public class MailServiceImpl  implements IMailService {

    // JavaMailSender 在Mail 自动配置类 MailSenderAutoConfiguration 中已经导入，这里直接注入使用即可
    @Autowired
    JavaMailSender javaMailSender;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${spring.mail.sender}")
    String sender;

    @Autowired
    SpmsUserMapper spmsUserMapper;

    //方法4个参数分别表示：收件人、抄送人、邮件主题以及邮件内容
    public void sendSimpleMail(String to, String cc, String subject, String content) {
        // 简单邮件直接构建一个 SimpleMailMessage 对象进行配置并发送即可
        SimpleMailMessage simpMsg = new SimpleMailMessage();
        simpMsg.setFrom(sender);//邮件发送者
        simpMsg.setTo(to);
        if(StringUtils.isNotBlank(cc)){
            simpMsg.setCc(cc);
        }
        simpMsg.setSubject(subject);
        simpMsg.setText(content);
        javaMailSender.send(simpMsg);
    }

    //判断验证码生成次数，5分钟内不能超过三次
    public int checkGenerateSecond(String userId,String email) {
        String code =  redisTemplate.opsForValue().get(userId+email);//缓存三分钟
        int seon = 0;
        if(code!=null) {
            seon = Integer.parseInt(code);
        }
        if(seon>3){
            return seon;
        }else{
            seon = seon+1;
            redisTemplate.opsForValue().set(userId+email,seon+"", Duration.ofMinutes(5));//缓存5分钟
        }

        return seon;
    }

    public String generateCodeToEmail(String userKey,String userId) {
        String valiteCode = null;
        try {
            Random rand = SecureRandom.getInstanceStrong();
            valiteCode = String.valueOf(rand.nextInt(999999));
            redisTemplate.opsForValue().set(userKey,valiteCode, Duration.ofMinutes(3));//缓存三分钟
            redisTemplate.opsForValue().set(userKey+"USERID",userId, Duration.ofMinutes(3));//缓存三分钟
        }catch (Exception e){
            log.error("邮件验证码生成异常："+e.getMessage());
        }
        return valiteCode;
    }

    public String checkCodeByUser(String userKey,String valiteCode) throws Exception{
        boolean result = false;
        String errorSecon =  redisTemplate.opsForValue().get(userKey+"ERROR");//缓存5分钟
        String code =  redisTemplate.opsForValue().get(userKey);//获取缓存的验证码
        String userId =  redisTemplate.opsForValue().get(userKey+"USERID");//获取缓存的用户账号
        int seon = 0;
        if(errorSecon!=null) {
            seon = Integer.parseInt(errorSecon);
        }
        if(seon>=3){
            throw new Exception("Verification code error ! Obtain the verification code again!" );//输入验证码错误达到3次
        }else{
            if(!valiteCode.equals(code)){//验证码是否相等
                seon = seon+1;
                redisTemplate.opsForValue().set(userKey+"ERROR",seon+"", Duration.ofMinutes(5));//缓存5分钟
                throw new Exception("Verification code error!" );
            }else{
                return userId;
            }
        }

    }

    //随机生成6位验证码
    public String getCode() {
        String str = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // no zero
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int index = (int) (Math.random() * str.length());
            code.append(str.charAt(index));
        }
        return code.toString();
    }

}
