package com.ruoyi.commonapi.service.impl;

import cn.hutool.json.JSONUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.commonapi.cache.CachePrefix;
import com.ruoyi.commonapi.entity.enums.VerificationEnums;
import com.ruoyi.commonapi.enums.ResultCode;
import com.ruoyi.commonapi.properties.SmsTemplateProperties;
import com.ruoyi.commonapi.service.SmsUtil;
import com.ruoyi.commonapi.utils.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 短信网管阿里云实现
 *
 * @author Chopper
 * @version v4.0
 * @since 2020/11/30 15:44
 */
@Component
@Slf4j
public class SmsUtilAliImplService implements SmsUtil {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SmsTemplateProperties smsTemplateProperties;

    @Override
    public void sendSmsCode(String mobile, VerificationEnums verificationEnums, String uuid) {
        //获取短信配置
        if (null == smsTemplateProperties) {
            throw new ServiceException(ResultCode.ALI_SMS_SETTING_ERROR.message());
        }
        //验证码
        String code = CommonUtil.getRandomNum();

        //准备发送短信参数
        Map<String, String> params = new HashMap<>(2);
        //验证码内容
        params.put("code", code);

        //模版 默认为登录验证
        String templateCode;

        //如果某个模版需要自定义，则在此处进行调整
        switch (verificationEnums) {
            //登录
            case LOGIN: {
                templateCode = smsTemplateProperties.getLOGIN();
                break;
            }
            //注册
            case REGISTER: {
                templateCode = smsTemplateProperties.getREGISTER();
                break;
            }
            //找回密码
            case FIND_USER: {
                templateCode = smsTemplateProperties.getFIND_USER();
                break;
            }
            //认证
            case AUTHENTICE: {
                templateCode = smsTemplateProperties.getAUTHENTICE();
                break;
            }

//            //修改密码
//            case UPDATE_PASSWORD: {
//                Member member = memberMapper.selectMemberById(Se.getCurrentUser().getId());
//                if (member == null || StringUtil.isEmpty(member.getMobile())) {
//                    return;
//                }
//                //更新为用户最新手机号
//                mobile = member.getMobile();
//                templateCode = smsTemplateProperties.getUPDATE_PASSWORD();
//                break;
//            }
//            //设置支付密码
//            case WALLET_PASSWORD: {
//                Member member = memberService.getById(UserContext.getCurrentUser().getId());
//                //更新为用户最新手机号
//                mobile = member.getMobile();
//                templateCode = smsTemplateProperties.getWALLET_PASSWORD();
//                break;
//            }
            //如果不是有效的验证码手段，则此处不进行短信操作
            default:
                return;
        }
        //如果是测试模式 默认验证码 6个1
        if (smsTemplateProperties.getIsTestModel()) {
            code = "111111";
            log.info("测试模式 - 接收手机：{},验证码：{}",mobile,code);
        } else {
            log.info("接收手机：{},验证码：{}",mobile,code);
            //发送短信
            this.sendSmsCode(smsTemplateProperties.getSignName(), mobile, params, templateCode);
        }
        //缓存中写入要验证的信息
        redisCache.setCacheObject(cacheKey(verificationEnums, mobile, uuid), code, 300, TimeUnit.SECONDS);
    }


    @Override
    public boolean verifyCode(String mobile, VerificationEnums verificationEnums, String uuid, String code) {
        Object result = redisCache.getCacheObject(cacheKey(verificationEnums, mobile, uuid));
        if (code.equals(result)) {
            //校验之后，删除
            redisCache.deleteObject(cacheKey(verificationEnums, mobile, uuid));
            return true;
        } else {
            return false;
        }

    }

    @Override
    public void sendSmsCode(String signName, String mobile, Map<String, String> param, String templateCode) {

        com.aliyun.dysmsapi20170525.Client client = this.createClient();
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(signName)
                .setPhoneNumbers(mobile)
                .setTemplateCode(templateCode)
                .setTemplateParam(JSONUtil.toJsonStr(param));
        try {
            SendSmsResponse response = client.sendSms(sendSmsRequest);
            if (!("OK").equals(response.getBody().getCode())) {
                throw new ServiceException(response.getBody().getMessage());
            }
        } catch (Exception e) {
            log.error("发送短信错误", e);
        }
    }


    /**
     * 初始化账号Client
     *
     * @return Client 短信操作util
     */
    public Client createClient() {
        try {
            Config config = new Config();
            //您的AccessKey ID
            config.accessKeyId = smsTemplateProperties.getAccessKeyId();
            //您的AccessKey Secret
            config.accessKeySecret = smsTemplateProperties.getAccessSecret();
            //访问的域名
            config.endpoint = "dysmsapi.aliyuncs.com";
            return new com.aliyun.dysmsapi20170525.Client(config);
        } catch (Exception e) {
            log.error("短信初始化错误", e);
        }
        return null;
    }

    /**
     * 生成缓存key
     *
     * @param verificationEnums 验证场景
     * @param mobile            手机号码
     * @param uuid              用户标识 uuid
     * @return
     */
    static String cacheKey(VerificationEnums verificationEnums, String mobile, String uuid) {
        return CachePrefix.SMS_CODE.getPrefix() + verificationEnums.name() + uuid + mobile;
    }
}
