package com.huyi.service.util.impl;

import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huyi.service.base.entity.PubVerifyCode;
import com.huyi.service.base.service.IPubVerifyCodeService;
import com.huyi.service.constant.MessageConstants;
import com.huyi.service.util.IMessageUtilsService;
import com.tianhu.common.core.exception.BaseException;
import com.tianhu.common.core.utils.CommonUtil;
import com.tianhu.common.core.utils.DateUtils;
import com.tianhu.common.core.utils.IdUtils;
import com.tianhu.common.redis.common.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 消息推送工具类
 *
 * @author tianhu
 */
@Service
public class MessageUtilsServiceImpl implements IMessageUtilsService
{
    @Autowired
    private IPubVerifyCodeService iPubVerifyCodeService;
    //手机号格式校验
    public static String MOBILE = "^1\\d{10}$";
    //验证码状态(未校验)
    static final String  NO_CHECK = "00";

    /**
     * 发送短信验证码
     * @param mobileNo 手机号码
     * @param verificationCode 模板id
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public void sendMessageCode(String mobileNo, String verificationCode, HttpServletRequest request)
    {
        if (CommonUtil.isEmpty(mobileNo)) {
            throw new BaseException("手机号不能为空！");
        } else {
            // 校验手机号
            Pattern pattern = Pattern.compile(MOBILE);
            Matcher matcher = pattern.matcher(mobileNo);
            boolean rs = matcher.matches();
            if (!rs) {
                throw new BaseException("手机号格式错误");
            }
        }

        // 验证是否已经发送验证码
        HttpSession httpSession = request.getSession();
        //查询验证码
        LambdaQueryWrapper<PubVerifyCode> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PubVerifyCode::getPvcPhone,mobileNo);
        queryWrapper.eq(PubVerifyCode::getPvcState,NO_CHECK);
        queryWrapper.orderByDesc(PubVerifyCode::getPvcLastTime);
        List<PubVerifyCode> staffInfList = iPubVerifyCodeService.findPubVerifyCodes(queryWrapper);
        // 如果已经发送过短`信验证码，并且在60S以内，稍后再发送
        if(staffInfList.size()>0){
            //取得指定时间间隔后的系统时间
            GregorianCalendar calendar = (GregorianCalendar) Calendar.getInstance();
            calendar.add( Calendar.MINUTE, -1);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
            System.out.println("比较时间"+formatter.format(calendar.getTime()));
            System.out.println("最后时间"+formatter.format(staffInfList.get(0).getPvcLastTime()));
            if(formatter.format(calendar.getTime()).compareTo(formatter.format(staffInfList.get(0).getPvcLastTime()))<0){
                System.out.println("请勿频繁发送验证码");
                throw new BaseException("请勿频繁发送验证码！");
            }
        }

        // 获取随机数
        String random = genRandomNum(6);
        //调试模式
        boolean isTest = true;
        // 获取验证码时间
        httpSession.setAttribute(MessageConstants.LAST_MOBILE_TIME, DateUtils.getNowDate());
        // 验证码
        httpSession.setAttribute(MessageConstants.MOBILE_RANDOM, random);
        // 手机号
        httpSession.setAttribute(MessageConstants.MOBILE_NO, mobileNo);
        String regVal = RedisUtils.getDictValue("pub_verification_code", verificationCode);
        // 发送短信
        String msg = regVal.replaceAll("@", random);

        PubVerifyCode pubVerifyCode = new PubVerifyCode();
        pubVerifyCode.setPvcId(IdUtils.fastSimpleUUID());
        pubVerifyCode.setPvcCode(random);
        pubVerifyCode.setPvcPhone(mobileNo);
        pubVerifyCode.setPvcLastTime(DateUtils.getNowDate());
        pubVerifyCode.setPvcState("00");
        iPubVerifyCodeService.createPubVerifyCode(pubVerifyCode);
		if(!isTest) {
			System.out.println("mobileNo："+mobileNo+"====ccc======msg:"+msg);
			StringBuilder sb = new StringBuilder();
			sb.append("mobile=");
			sb.append(mobileNo);
			sb.append("&content=");
			sb.append(msg);
			sb.append("&appkey=");
            String appKey = RedisUtils.getDictValue("pub_jisu_app_key", "000000_app_key");
			sb.append(appKey);
			try {
				System.out.println("======sb："+ sb.toString());
				HttpUtil.get("http://api.jisuapi.com/sms/send?" + sb.toString());
			} catch (Exception ex) {
                System.out.println("获取短信验证码失败");
				throw new BaseException("获取短信验证码失败");
			}
		}
    }

    public static String genRandomNum(int card_len){
        //35是因为数组是从0开始的，26个字母+10个数字
        final int maxNum = 36;
        //生成的随机数
        int i;
        //生成的密码的长度
        int count = 0;
        char[] str = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
        StringBuffer pwd = new StringBuffer("");
        Random r = new Random();
        while(count < card_len){
            //生成随机数，取绝对值，防止生成负数 生成的数最大为36-1
            i = Math.abs(r.nextInt(maxNum));
            if (i >= 0 && i < str.length) {
                pwd.append(str[i]);
                count ++;
            }
        }
        return pwd.toString();
    }
}
