package cn.pluss.platform.util;

import cn.hutool.core.date.DateUtil;
import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.constants.Constant;
import cn.pluss.platform.entitiy.ReqRecords;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.service.ReqRecordsService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.tea.TeaException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.aliyun.dysmsapi20170525.Client;

/**
 * 获取验证码相关工具
 */
@Component
public class ValidateCodeUtil {

    @Value("${juhe.send.url}")
    private String URL;
    /**
     * 短信接口appKey
     */
    @Value("${juhe.send.key}")
    private String KEY;
    /**
     * 阿里云key
     */
    @Value("${aliyun.keyid}")
    private String ACCESSKEYID;
    /**
     * 阿里云secret
     */
    @Value("${aliyun.keysecret}")
    private String ACCESSKEYSECRET;


    @Autowired
    private ReqRecordsService reqRecordService;

    @Autowired
    private HttpServletRequest request;

    /**
     * 获取验证码
     */
    public Result<Object> requestValidateCode(String phone, String checkCode) {
        String requestUri = request.getRequestURI();
        String myLoginName = request.getHeader("myLoginName");

        ReqRecords reqRecords = new ReqRecords();
        reqRecords.setIp(IpUtils.getIpAddr(request));
        reqRecords.setPhone(phone);
        reqRecords.setLoginName(myLoginName);
        reqRecords.setUri(requestUri);

        // 短信一天限制10次
        ReqRecords reqRecords1 = new ReqRecords();
        reqRecords1.setIp(reqRecords.getIp());
        reqRecords1.setCreateTimeStart(DateUtil.beginOfDay(new Date()).toJdkDate());
        reqRecords1.setCreateTimeEnd(new Date());
        int count = reqRecordService.count(new QueryWrapper<>(reqRecords1));
        if (count >= 50) {
            return ResultGenerator.genFailResult("限制请求");
        }

        // 短信一周限制45次
        // ReqRecords reqRecords2 = new ReqRecords();
        // reqRecords2.setIp(reqRecords.getIp());
        // reqRecords2.setCreateTimeStart(DateUtil.beginOfWeek(new Date()).toJdkDate());
        // reqRecords2.setCreateTimeEnd(new Date());
        // count = reqRecordService.count(new QueryWrapper<>(reqRecords2));
        // if (count >= 250) {
        //     return ResultGenerator.genFailResult("限制请求");
        // }

        try {
            reqRecordService.checkLimit(reqRecords, 60000);
        } catch (Exception e) {
            return ResultGenerator.genFailResult(e.getMessage());
        }

        Map<String, Object> sendDataMap = new HashMap<>();
        sendDataMap.put("mobile", phone);
        sendDataMap.put("tpl_id", "247236");
        sendDataMap.put("tpl_value", "#code#=" + checkCode);
        sendDataMap.put("key", KEY);
        HttpResult httpResult;
        try {
            httpResult = HttpUtil.doPost(URL, sendDataMap);
        } catch (Exception e) {
            return ResultGenerator.genFailResult(e.getMessage());
        }
        JSONObject json = JSON.parseObject(httpResult.getBody());

        if (!"0".equalsIgnoreCase(json.getString("error_code"))) {
            return ResultGenerator.genFailResult(json.getString("reason"));
        }

        return null;
    }


    /**
     * 生成验证码图片
     * @param request 设置session
     * @param response 转成图片
     * @param captchaProducer 生成图片方法类
     * @param validateSessionKey session名称
     * @throws Exception
     */
    public static void validateCode(HttpServletRequest request, HttpServletResponse response, DefaultKaptcha captchaProducer, String validateSessionKey) throws Exception{
        // Set to expire far in the past.
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");

        // return a jpeg
        response.setContentType("image/jpeg");

        // create the text for the image
        String capText = captchaProducer.createText();

        // store the text in the session
        request.getSession().setAttribute(validateSessionKey, capText);

        // create the image with the text
        BufferedImage bi = captchaProducer.createImage(capText);

        ServletOutputStream out = response.getOutputStream();

        // write the data out
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }

    /**
     * @description:比较验证码
     * @date: 2021/12/20 11:10
     * @param request:
     * @param verifyCode:
     * @return boolean
     */
    public static boolean checkVerifyCode(HttpServletRequest request,String verifyCode) {
        //获取生成的验证码
        Object verifyCodeExpected = request.getSession().getAttribute(Constant.LOGIN_VALIDATE_CODE);
        if(verifyCodeExpected == null){
            MsgException.throwException("图形验证码已过期！");
        }
        if(StringUtil.isEmpty(verifyCode)){
            MsgException.throwException("请输入图形验证码！");
        }
        //获取用户输入的验证码
        if(!verifyCode.equalsIgnoreCase(verifyCodeExpected.toString())) {
            MsgException.throwException("图形验证码有误！");
        }
        return true;
    }

    /**
     * 获取手机验证码
     * @param phone
     * @param code
     */
    public JSONObject requestManageValidateCode(String phone,String code) {
        Map<String, Object> params = new HashMap<>();
        params.put("mobile", phone);
        params.put("tpl_id", "186650");
        params.put("tpl_value", "#code#=" + code);
        params.put("key", KEY);
        try {
            HttpResult httpResult = HttpUtil.doPost(URL, params);
            if(httpResult == null){
                return ResultGenerator.genFailJsonResult("获取失败，网络请求异常！");
            }
            JSONObject json = JSON.parseObject(httpResult.getBody());
            if (!"0".equalsIgnoreCase(json.getString("error_code"))) {
                return ResultGenerator.genFailJsonResult(json.getString("reason"));
            }
            return ResultGenerator.genSuccessJsonResult("获取成功",null);
        } catch (Exception e) {
            return ResultGenerator.genFailJsonResult(e.getMessage());
        }
    }
    /**
     * 获取验证码（阿里云）
     */
    public Result<Object> requestValidateCodeALi(String phone, String checkCode) {
        String requestUri = request.getRequestURI();
        String myLoginName = request.getHeader("myLoginName");

        ReqRecords reqRecords = new ReqRecords();
        reqRecords.setIp(IpUtils.getIpAddr(request));
        reqRecords.setPhone(phone);
        reqRecords.setLoginName(myLoginName);
        reqRecords.setUri(requestUri);

        // 短信一天限制10次
        ReqRecords reqRecords1 = new ReqRecords();
        reqRecords1.setIp(reqRecords.getIp());
        reqRecords1.setCreateTimeStart(DateUtil.beginOfDay(new Date()).toJdkDate());
        reqRecords1.setCreateTimeEnd(new Date());
        int count = reqRecordService.count(new QueryWrapper<>(reqRecords1));
        if (count >= 50) {
            return ResultGenerator.genFailResult("限制请求");
        }

        // 短信一周限制45次
        // ReqRecords reqRecords2 = new ReqRecords();
        // reqRecords2.setIp(reqRecords.getIp());
        // reqRecords2.setCreateTimeStart(DateUtil.beginOfWeek(new Date()).toJdkDate());
        // reqRecords2.setCreateTimeEnd(new Date());
        // count = reqRecordService.count(new QueryWrapper<>(reqRecords2));
        // if (count >= 250) {
        //     return ResultGenerator.genFailResult("限制请求");
        // }

        try {
            reqRecordService.checkLimit(reqRecords, 60000);
        } catch (Exception e) {
            return ResultGenerator.genFailResult(e.getMessage());
        }


        Client client = null;
        try {
            client = createClient();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 1.发送短信
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setSignName("超掌柜")
                .setTemplateCode("SMS_244665149")
                .setTemplateParam("{\"code\":" +"'"+checkCode +"'"+"}")
                .setPhoneNumbers(phone);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();

        try {
            assert client != null;
            return ResultGenerator.genSuccessResult(client.sendSmsWithOptions(sendSmsRequest, runtime));
        } catch (Exception e) {
            return ResultGenerator.genFailResult(e.getMessage());
        }

    }
    /**
     * 发送短信(阿里云)
     *
     * @return
     * @throws Exception
     */
    public  Client createClient() throws Exception {
        Config config = new Config();
        config.accessKeyId = ACCESSKEYID;
        config.accessKeySecret = ACCESSKEYSECRET;
        return new com.aliyun.dysmsapi20170525.Client(config);
    }


}
