package com.ruoyi.business.common;

import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.business.util.ConfigParam;
import com.ruoyi.business.util.StringKit;
import com.ruoyi.cache.SmsCache;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.database.domain.vo.SmsVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @Auther: cyFeng
 * @Date: 2024/4/24 17:57
 * @Description:
 */
@Api(tags = "短信验证码")
@RestController
@RequestMapping("/base/sendMes")
public class sendMes {

    String auth_code = ConfigParam.auth_code;
    String spid = ConfigParam.spid;
    String smsid = ConfigParam.smsid;
    String auth_key = ConfigParam.auth_key;
    String extport = "";
    String sendtime = "";
    String timestamp = System.currentTimeMillis() + "";


    @GetMapping
    @ApiOperation("获取短信验证码")
    public R getMes(@RequestParam(required = false) @ApiParam("手机号") String mobiles) {

        String msgVoStr = SmsCache.get(mobiles);
        if (!"".equals(StringKit.toString(msgVoStr))) {
            SmsVO msgVO = JSON.parseObject(msgVoStr, SmsVO.class, Feature.IgnoreNotMatch);
            Long oldTime = msgVO.getTime();
            Long nowTime = System.currentTimeMillis()/1000;
            if((nowTime - oldTime) < 60){
                return R.fail("请勿频繁点击");
            }
        }

        String message = getMessage(mobiles);
        if (!"1".equals(message)) {
            return R.fail("短信发送失败");
        }
        return R.ok("短信发送成功");
    }

    public String getSHA(String mobiles, String content) {
        try {
            String str = auth_code + spid + extport + smsid + mobiles + sendtime + URLEncoder.encode(content, "utf-8") + timestamp + auth_key;
            MessageDigest digest = MessageDigest
                    .getInstance("SHA");
            digest.update(str.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    public String getMessage(String mobiles) {
        try {
            String captcha = getCapcha();
            String content ="【浦星科技】本次登录验证码为" + captcha;
            String sign = getSHA(mobiles, content);
//            System.out.println(content);
            String urlString = "https://swdxzdzh.cn:7443/receive/SMSController/sendSms";
            HttpClient httpClient = HttpClientBuilder.create().build();
            HttpPost httpPost = new HttpPost(urlString);
            Map<String, Object> params = new HashMap<>();
            params.put("auth_code", auth_code);
            params.put("spid", spid);
            params.put("extport", extport);
            params.put("smsid", smsid);
            params.put("mobiles", mobiles);
            params.put("sendtime", sendtime);
            params.put("content", content);
            params.put("timestamp", timestamp);
            params.put("auth_key", auth_key);
            params.put("sign", sign);
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonString = objectMapper.writeValueAsString(params);
            StringEntity entity = new StringEntity(jsonString, "UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            String responseString = EntityUtils.toString(responseEntity, "UTF-8");

            SmsVO msgVO = new SmsVO();
            msgVO.setMsg(captcha);
            msgVO.setContent(content);
            msgVO.setPhone(mobiles);
            msgVO.setTime(System.currentTimeMillis()/1000);
            SmsCache.put(msgVO);

            return new JSONObject(responseString).getStr("code");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public String getCapcha() {
        Random random = new Random();
        int captcha = random.nextInt(900000) + 100000;
        return StringKit.toString(captcha);
    }
}
