package com.zhongzheng.modules.alisms.service.impl;


import cn.hutool.core.lang.Validator;
import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhongzheng.common.constant.Constants;
import com.zhongzheng.common.core.redis.RedisCache;
import com.zhongzheng.common.exception.CustomException;
import com.zhongzheng.common.utils.ServletUtils;
import com.zhongzheng.common.utils.SmsUtils;
import com.zhongzheng.common.utils.ToolsUtils;
import com.zhongzheng.common.utils.ip.IpUtils;
import com.zhongzheng.modules.alisms.service.IAliSmsService;
import com.zhongzheng.modules.alisms.vo.ResultBean;
import com.zhongzheng.modules.base.bo.SmsAddBo;
import com.zhongzheng.modules.base.service.ISmsService;
import com.zhongzheng.modules.user.domain.User;
import com.zhongzheng.modules.user.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Service
public class AliSmsServiceImpl implements IAliSmsService {
    private static final Logger LOGGER = LoggerFactory.getLogger(AliSmsServiceImpl.class);

    @Value("${aliyun.sms.signName}")
    private String SIGNNAME;
    @Value("${aliyun.sms.registerTemplateCode}")
    private String REGISTERTEMPLATECODE;
    @Value("${aliyun.sms.accessKeyId}")
    private String ACCESSKEYID;
    @Value("${aliyun.sms.accessKeySecret}")
    private String ACCESSKEYSECRET;
    @Value("${aliyun.sms.loginTemplateCode}")
    private String LOGINTEMPLATECODE;
    @Value("${aliyun.sms.forgetTemplateCode}")
    private String FORGETTEMPLATECODE;
    @Value("${aliyun.sms.pwdTemplateCode}")
    private String PWDTEMPLATECODE;

    @Autowired
    private IUserService iUserService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISmsService iSmsService;


    @Override
    public ResultBean sendSms(String tel, String param) {
        try{
            SendSmsResponse response = SmsUtils.sendSms(tel,SIGNNAME,REGISTERTEMPLATECODE,param,ACCESSKEYID,ACCESSKEYSECRET);
            System.out.println(response);
        }catch (Exception e){

        }

        return null;
    }

    @Override
    public ResultBean sendInformSms(String tel, String param,String code) {
        try{
            SendSmsResponse response = SmsUtils.sendSms(tel,SIGNNAME,code,param,ACCESSKEYID,ACCESSKEYSECRET);
            System.out.println(response);
        }catch (Exception e){

        }

        return null;
    }

    @Override
    public Boolean sendRegisterSms(String tel) {
        if(tel==null){
            throw new CustomException("手机号码不能为空");
        }
        User user = iUserService.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getTelphone,tel).last("limit 1"));
        if(Validator.isNotNull(user)){
            throw new CustomException("该手机号已注册");
        }
        String code = ToolsUtils.getSmsCode();
        String key = Constants.REGISTER_SMS + tel;
        redisCache.setCacheObject(key,code,5, TimeUnit.MINUTES);//5分钟
        try{
            Map<String,Object> param = new HashMap<>();
            param.put("code",code);
            SendSmsResponse response = SmsUtils.sendSms(tel,SIGNNAME,REGISTERTEMPLATECODE, JSON.toJSONString(param),ACCESSKEYID,ACCESSKEYSECRET);
            System.out.println(response.getBody().getMessage());
            if(response.getBody().getMessage().equals("OK")){
                SmsAddBo smsAddBo = new SmsAddBo();
                smsAddBo.setCode(code);
                smsAddBo.setTel(tel);
                smsAddBo.setType(1L);
                smsAddBo.setIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
                iSmsService.insertByAddBo(smsAddBo);
                return true;
            }
        }catch (Exception e){
            throw new CustomException(e.getMessage());
        }
        return false;
    }

    @Override
    public Boolean sendForgetSms(String tel) {
        if(tel==null){
            throw new CustomException("手机号码不能为空");
        }
        User user = iUserService.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getTelphone,tel).last("limit 1"));
        if(Validator.isEmpty(user)){
            throw new CustomException("该手机号未注册");
        }
        String code = ToolsUtils.getSmsCode();
        String key = Constants.FORGET_SMS + tel;
        redisCache.setCacheObject(key,code,5, TimeUnit.MINUTES);//5分钟
        try{
            Map<String,Object> param = new HashMap<>();
            param.put("code",code);
            SendSmsResponse response = SmsUtils.sendSms(tel,SIGNNAME,FORGETTEMPLATECODE, JSON.toJSONString(param),ACCESSKEYID,ACCESSKEYSECRET);
            if(response.getBody().getMessage().equals("OK")){
                SmsAddBo smsAddBo = new SmsAddBo();
                smsAddBo.setCode(code);
                smsAddBo.setTel(tel);
                smsAddBo.setType(2L);
                smsAddBo.setIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
                iSmsService.insertByAddBo(smsAddBo);
                return true;
            }
        }catch (Exception e){
            throw new CustomException(e.getMessage());
        }
        return false;
    }

    @Override
    public Boolean sendLoginSms(String tel) {
        if(tel==null){
            throw new CustomException("手机号码不能为空");
        }
        User user = iUserService.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getTelphone,tel).last("limit 1"));
        if(Validator.isEmpty(user)){
            throw new CustomException("该手机号未注册");
        }
        String code = ToolsUtils.getSmsCode();
        String key = Constants.LOGIN_SMS + tel;
        redisCache.setCacheObject(key,code,5, TimeUnit.MINUTES);//5分钟
        try{
            Map<String,Object> param = new HashMap<>();
            param.put("code",code);
            SendSmsResponse response = SmsUtils.sendSms(tel,SIGNNAME,LOGINTEMPLATECODE, JSON.toJSONString(param),ACCESSKEYID,ACCESSKEYSECRET);
            if(response.getBody().getMessage().equals("OK")){
                SmsAddBo smsAddBo = new SmsAddBo();
                smsAddBo.setCode(code);
                smsAddBo.setTel(tel);
                smsAddBo.setType(3L);
                smsAddBo.setIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
                iSmsService.insertByAddBo(smsAddBo);
                return true;
            }
        }catch (Exception e){
            throw new CustomException(e.getMessage());
        }
        return false;
    }

    @Override
    public Boolean sendPwdSms(String tel,String code) {
        try{
            Map<String,Object> param = new HashMap<>();
            param.put("code",code);
            SmsAddBo smsAddBo = new SmsAddBo();
            smsAddBo.setCode(code);
            smsAddBo.setTel(tel);
            smsAddBo.setType(4L);
            smsAddBo.setIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
            iSmsService.insertByAddBo(smsAddBo);
            SendSmsResponse response = SmsUtils.sendSms(tel,SIGNNAME,PWDTEMPLATECODE, JSON.toJSONString(param),ACCESSKEYID,ACCESSKEYSECRET);
            if(response.getBody().getMessage().equals("OK")){
                return true;
            }
        }catch (Exception e){
            throw new CustomException(e.getMessage());
        }
        return false;
    }
}
