package com.starry.admin.utils;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSONObject;
import com.starry.common.redis.RedisCache;
import com.starry.common.utils.StringUtils;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

/**
 * @Author: huchuansai
 * @Date: 2024/7/29 5:41 PM
 * @Description:
 */
@Slf4j
@Service
public class SmsUtils {
    @Resource
    private RedisCache redisCache;

    // 发送短信验证码接口
    public void sendSmsApi(String phone) {
        String code = RandomUtil.randomNumbers(4);
        sendSmsV2(phone, code);
        String key = "sms:phone:" + phone;
        // 存放到redis里
        redisCache.setCacheObject(key, code, 10L, java.util.concurrent.TimeUnit.MINUTES);
    }

    // 校验短信验证码是否正确
    public void checkSmsCode(String phone, String code) {
        if(StringUtils.isEmpty(code)){
            throw new RuntimeException("短信验证码必填");
        }
        String key = "sms:phone:" + phone;
        Object data = redisCache.getCacheObject(key);
        if (Objects.isNull(data)) {
            throw new RuntimeException("短信验证码无效或已过期");
        }
        if (!code.equals(data.toString())) {
            throw new RuntimeException("短信验证码错误");
        }
    }

    private static void sendSms(String phone, String code, String templateId) {
        String host = "https://wwsms.market.alicloudapi.com";
        String path = "/send_sms";
        String method = "POST";
        String appcode = "18639b38538849e1bc8a3413a8d0c0e5";
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "APPCODE " + appcode);
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<>();
        Map<String, String> bodys = new HashMap<>();
        bodys.put("content", "code:" + code);
        bodys.put("template_id", templateId);   //注意，模板CST_11253 仅作调试使用，下发短信不稳定，请联系客服报备自己的专属签名模板，以保障业务稳定使用
        bodys.put("phone_number", phone);
        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            String resp = EntityUtils.toString(response.getEntity());
            log.info("send sms result：" + resp);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

    public static void sendSmsV2(String phone, String code) {
        String host = "https://dfsns.market.alicloudapi.com";
        String path = "/data/send_sms";
        String method = "POST";
        String appcode = "18639b38538849e1bc8a3413a8d0c0e5";
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "APPCODE " + appcode);
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<>();
        Map<String, String> bodys = new HashMap<>();
        bodys.put("content", "code:" + code);
        bodys.put("template_id", "CST_kdnetfmdrsqe11552");  //注意，CST_ptdie100该模板ID仅为调试使用，调试结果为"status": "OK" ，即表示接口调用成功，然后联系客服报备自己的专属签名模板ID，以保证短信稳定下发
        bodys.put("phone_number", phone);

        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            HttpEntity entity = response.getEntity();
            if (entity == null) {
                log.error("send sms code failed: empty http entity, statusLine={}", response.getStatusLine());
                throw new RuntimeException("发送短信验证码失败，短信服务无响应");
            }

            String result = EntityUtils.toString(entity, "UTF-8");
            if (StringUtils.isEmpty(result)) {
                log.error("send sms code failed: empty response body, statusLine={}", response.getStatusLine());
                throw new RuntimeException("发送短信验证码失败，短信服务返回空响应");
            }

            JSONObject parsed = JSONObject.parseObject(result);
            if (parsed == null) {
                log.error("send sms code failed: invalid json response, statusLine={}, body={}",
                        response.getStatusLine(), result);
                throw new RuntimeException("发送短信验证码失败，短信服务响应格式异常");
            }

            log.info("send sms code result:" + result);
            if (!"ok".equalsIgnoreCase(parsed.getString("status"))) {
                log.error("send sms code failed: status not ok, statusLine={}, body={}", response.getStatusLine(),
                        result);
                throw new RuntimeException("发送短信验证码失败，错误信息：" + result);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        sendSmsV2("13210055630", "1234");
    }
}
