//package com.backendsys.service.SDKService.SDKTencent;
//
//import cn.hutool.core.date.DateUtil;
//import cn.hutool.core.util.RandomUtil;
//import cn.hutool.json.JSONArray;
//import cn.hutool.json.JSONObject;
//import cn.hutool.json.JSONUtil;
//import com.backendsys.modules.common.config.redis.utils.RedisUtil;
//import com.backendsys.entity.System.SysSMSDTO;
//import com.backendsys.exception.CustException;
//import com.backendsys.mapper.System.SysMobileSMSHistoryMapper;
//import com.backendsys.utils.MapUtil;
//import com.tencentcloudapi.common.Credential;
//import com.tencentcloudapi.common.exception.TencentCloudSDKException;
//import com.tencentcloudapi.common.profile.ClientProfile;
//import com.tencentcloudapi.sms.v20210111.SmsClient;
//import com.tencentcloudapi.sms.v20210111.models.*;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.util.Date;
//import java.util.LinkedHashMap;
//import java.util.Map;
//import java.util.concurrent.TimeUnit;
//
//@Service
//public class SDKTencentSMSServiceImpl implements SDKTencentSMSService {
//
//    @Value("${tencent.sms.secret-id}")
//    private String SECRET_ID;
//    @Value("${tencent.sms.secret-key}")
//    private String SECRET_KEY;
//
//    /* 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId*/
//    @Value("${tencent.sms.sdk-app-id}")
//    private String sdkAppId;
//
//    /* 短信签名内容: 使用 UTF-8 编码，必须填写已审核通过的签名 */
//    @Value("${tencent.sms.sign-name}")
//    private String signName;
//
//    /* 模板 ID: 必须填写已审核通过的模板 ID */
//    @Value("${tencent.sms.template-id-of-common}")
//    private String templateIdOfCommon;
//
//    @Autowired
//    private RedisUtil redisUtil;
//
//    @Autowired
//    private SysMobileSMSHistoryMapper sysMobileSMSHistoryMapper;
//
//    /** 腾讯云文档：https://cloud.tencent.com/document/product/382/43194 */
//
//
//    /**
//     * [方法] 获得当前时间与 n 天前的时间
//     */
//    private Map<String, Object> getCurrentAndBeforeDate(String beginTime, String endTime, Integer n) {
//
//        if (beginTime != null && endTime != null && Long.valueOf(beginTime) > Long.valueOf(endTime)) {
//            throw new CustException("开始时间不能大于结束时间");
//        }
//        // 获取当前时间
//        Date now = new Date();
//        String currentDateFormatted = DateUtil.format(now, "yyyyMMddHH");
//        // 从当前时间减去7天
//        Date sevenDaysAgo = DateUtil.offsetDay(now, -n);
//        String sevenDaysAgoFormatted = DateUtil.format(sevenDaysAgo, "yyyyMMddHH");
//
//        /* 开始时间，yyyymmddhh 需要拉取的起始时间，精确到小时 */
//        String beginTimeData = beginTime != null ? beginTime : sevenDaysAgoFormatted;
//
//        /* 结束时间，yyyymmddhh 需要拉取的截止时间，精确到小时 */
//        String endTimeData = endTime != null ? endTime : currentDateFormatted;
//
//        Map<String, Object> result = new LinkedHashMap<>();
//        result.put("beginTime", beginTimeData);
//        result.put("endTime", endTimeData);
//
//        return result;
//    }
//
//    /**
//     * [腾讯云] 发送短信
//     */
//    @Transactional
//    public Map<String, Object> sendSMS(SysSMSDTO sysSMSDTO) {
//
//        try {
//
//            String origin = sysSMSDTO.getOrigin();
//            String phone = sysSMSDTO.getPhone();
//            Integer phoneAreaCode = sysSMSDTO.getPhone_area_code();
//
////            // [腾讯云] 号码信息查询 (判断手机号码是否有效)
////            List<Map<String, Object>> phoneInfoList = getDescribePhoneNumberInfo(phoneAreaCode + phone);
////            if (phoneInfoList != null) {
////                Map<String, Object> phoneInfo = phoneInfoList.get(0);
////                String code = (String) phoneInfo.get("code");
////                if (!"Ok".equals(code)) {
////                    String message = (String) phoneInfo.get("message");
////                    throw new CustException("发送失败，请检查手机号码格式", 6001, phoneInfo);
////                }
////            }
//
//            // ----------------------------------------------------------------------
//            Credential cred = new Credential(SECRET_ID, SECRET_KEY);
//            ClientProfile clientProfile = new ClientProfile();
//            SmsClient client = new SmsClient(cred, "ap-guangzhou",clientProfile);
//
//            SendSmsRequest req = new SendSmsRequest();
//            req.setSmsSdkAppId(sdkAppId);
//            req.setSignName(signName);
//            req.setTemplateId(templateIdOfCommon);
//
//            // 生成一个6位的随机整数 (验证码)
//            Integer smsCode =  RandomUtil.randomInt(100000, 999999);
//            Integer smsExpire = 5;
//            sysSMSDTO.setSms_code(String.valueOf(smsCode));
//
//            /* 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致，若无模板参数，则设置为空 */
//            // {1} 验证码, {2} 过期时间(5分钟)
//            String[] templateParamSet = {String.valueOf(smsCode), String.valueOf(smsExpire)};
//            req.setTemplateParamSet(templateParamSet);
//            String redisKey = "sms-" + origin + "-" + phone;
//            redisUtil.setCacheObject(redisKey, smsCode, smsExpire, TimeUnit.MINUTES);
//
//            /* 下发手机号码，采用 E.164 标准，+[国家或地区码][手机号]
//             * 示例如：+8613711112222， 其中前面有一个+号 ，86为国家码，13711112222为手机号，最多不要超过200个手机号 */
//            String[] phoneNumberSet = {"+" + phoneAreaCode + phone};
//            req.setPhoneNumberSet(phoneNumberSet);
//
//    //        /* 用户的 session 内容（无需要可忽略）: 可以携带用户侧 ID 等上下文信息，server 会原样返回 */
//    //        String sessionContext = "";
//    //        req.setSessionContext(sessionContext);
//
//    //        /* 国内短信无需填写该项；国际/港澳台短信已申请独立 SenderId 需要填写该字段，默认使用公共 SenderId，无需填写该字段。注：月度使用量达到指定量级可申请独立 SenderId 使用，详情请联系 [腾讯云短信小助手](https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81)。*/
//    //        String senderid = "";
//    //        req.setSenderId(senderid);
//
//
//            /* 通过 client 对象调用 SendSms 方法发起请求。注意请求方法名与请求对象是对应的
//             * 返回的 res 是一个 SendSmsResponse 类的实例，与请求对象对应 */
//            SendSmsResponse res = client.SendSms(req);
//
//            // 输出json格式的字符串回包
//            String resString = SendSmsResponse.toJsonString(res);
//            System.out.println(resString);
//
//            JSONObject resp = JSONUtil.parseObj(resString);
//            JSONArray sendStatusSet = JSONUtil.parseArray(resp.get("SendStatusSet"));
//
//            JSONObject statusSet = JSONUtil.parseObj(sendStatusSet.get(0));
//            String code = (String) statusSet.get("Code");
//            String message = (String) statusSet.get("Message");
//
//            if ("Ok".equals(code)) {
//                // 发送成功后，留下记录
//                sysMobileSMSHistoryMapper.insertMobileSMSHistory(sysSMSDTO);
//            } else {
//                throw new CustException(message);
//            }
//
//        } catch (TencentCloudSDKException e) {
//            e.printStackTrace();
//        }
//
//        return Map.of("phone", sysSMSDTO.getPhone());
//    }
//
//    /**
//     * [腾讯云] 短信回执数据统计
//     */
//    @Override
//    public Map<String, Object> getSMSCallbackStatistics(String beginTime, String endTime, String limit) {
//        try {
//
//            // 设置拉取最大条数，最多100条 (默认100条)
//            Long limitCount = limit != null ? Long.valueOf(limit) : null;
//            if (limitCount == null) {
//                limitCount = 100L;
//            } else if (limitCount <= 0 || limitCount > 100) {
//                throw new CustException("limit 范围在 1~100");
//            }
//
//            // ----------------------------------------------------------------------
//            Credential cred = new Credential(SECRET_ID, SECRET_KEY);
//            ClientProfile clientProfile = new ClientProfile();
//            SmsClient client = new SmsClient(cred, "ap-guangzhou",clientProfile);
//
//            CallbackStatusStatisticsRequest req = new CallbackStatusStatisticsRequest();
//            req.setSmsSdkAppId(sdkAppId);
//            req.setLimit(limitCount);
//            req.setOffset(0L);
//            req.setBeginTime((String) getCurrentAndBeforeDate(beginTime, endTime, 7).get("beginTime"));
//            req.setEndTime(((String) getCurrentAndBeforeDate(beginTime, endTime, 7).get("endTime")));
//
//            CallbackStatusStatisticsResponse res = client.CallbackStatusStatistics(req);
//
//            // 输出json格式的字符串回包
//            String resString = SendStatusStatisticsResponse.toJsonString(res);
//            JSONObject resp = JSONUtil.parseObj(resString);
//
//            System.out.println(resp);
//            /*
//            {
//                "CallbackStatusStatistics": {
//                    "CallbackCount": 0,
//                    "RequestSuccessCount": 0,
//                    "CallbackFailCount": 0,
//                    "CallbackSuccessCount": 0,
//                    "InternalErrorCount": 0,
//                    "InvalidNumberCount": 0,
//                    "ShutdownErrorCount": 0,
//                    "BlackListCount": 0,
//                    "FrequencyLimitCount": 0
//                },
//                "RequestId": "b8ace58a-20cc-4829-9cb7-0681a82450fb"
//            }
//             */
//            Map<String, Object> result = new LinkedHashMap<>();
//            result.put("callback_count", MapUtil.get(resp, "CallbackStatusStatistics.CallbackCount"));
//            result.put("request_success_count", MapUtil.get(resp, "CallbackStatusStatistics.RequestSuccessCount"));
//            result.put("callback_fail_count", MapUtil.get(resp, "CallbackStatusStatistics.CallbackFailCount"));
//            result.put("callback_success_count", MapUtil.get(resp, "CallbackStatusStatistics.CallbackSuccessCount"));
//            result.put("internal_error_count", MapUtil.get(resp, "CallbackStatusStatistics.InternalErrorCount"));
//            result.put("invalid_number_count", MapUtil.get(resp, "CallbackStatusStatistics.InvalidNumberCount"));
//            result.put("shutdown_error_count", MapUtil.get(resp, "CallbackStatusStatistics.ShutdownErrorCount"));
//            result.put("black_list_count", MapUtil.get(resp, "CallbackStatusStatistics.BlackListCount"));
//            result.put("frequency_limit_count", MapUtil.get(resp, "CallbackStatusStatistics.FrequencyLimitCount"));
//
//            return result;
//
//        } catch (TencentCloudSDKException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }
//
//    /**
//     * [腾讯云] 短信发送数据统计
//     */
//    @Override
//    public Map<String, Object> getSMSStatistics(String beginTime, String endTime) {
//        try {
//
//            // ----------------------------------------------------------------------
//            Credential cred = new Credential(SECRET_ID, SECRET_KEY);
//            ClientProfile clientProfile = new ClientProfile();
//            SmsClient client = new SmsClient(cred, "ap-guangzhou",clientProfile);
//
//            SendStatusStatisticsRequest req = new SendStatusStatisticsRequest();
//            req.setSmsSdkAppId(sdkAppId);
//
//            // 设置拉取最大条数，最多100条
//            Long limit = 5L;
//            req.setLimit(limit);
//
//            /* 偏移量 注：目前固定设置为0 */
//            Long offset = 0L;
//            req.setOffset(offset);
//            req.setBeginTime((String) getCurrentAndBeforeDate(beginTime, endTime, 7).get("beginTime"));
//            req.setEndTime(((String) getCurrentAndBeforeDate(beginTime, endTime, 7).get("endTime")));
//
//            /* 通过 client 对象调用 SendStatusStatistics 方法发起请求。注意请求方法名与请求对象是对应的
//             * 返回的 res 是一个 SendStatusStatisticsResponse 类的实例，与请求对象对应 */
//            SendStatusStatisticsResponse res = client.SendStatusStatistics(req);
//
//            // 输出json格式的字符串回包
//            String resString = SendStatusStatisticsResponse.toJsonString(res);
//            JSONObject resp = JSONUtil.parseObj(resString);
//
//            System.out.println(resp);
//            /*
//            {
//                "SendStatusStatistics": {
//                    "FeeCount": 12,                 // 短信计费条数统计，例如提交成功量为100条，其中有20条是长短信（长度为80字）被拆分成2条，则计费条数为： 80 * 1 + 20 * 2 = 120 条。
//                    "RequestCount": 23,             // 短信提交量统计
//                    "RequestSuccessCount": 12       // 短信提交成功量统计
//                },
//                "RequestId": "9ef2b426-ee33-4a3d-80f0-b31876f82fb8"
//            }
//            */
//
//            Map<String, Object> result = new LinkedHashMap<>();
//            result.put("fee_count", MapUtil.get(resp, "SendStatusStatistics.FeeCount"));
//            result.put("request_count", MapUtil.get(resp, "SendStatusStatistics.RequestCount"));
//            result.put("request_success_count", MapUtil.get(resp, "SendStatusStatistics.RequestSuccessCount"));
//
//            return result;
//
//        } catch (TencentCloudSDKException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }
//
//    /**
//     * [腾讯云] 套餐包信息统计
//     */
////    @Override
////    public List<Map<String, Object>> getSmsPackagesStatistics(String beginTime, String endTime) {
////        try {
////
////            // ----------------------------------------------------------------------
////            Credential cred = new Credential(SECRET_ID, SECRET_KEY);
////            ClientProfile clientProfile = new ClientProfile();
////            SmsClient client = new SmsClient(cred, "ap-guangzhou",clientProfile);
////
////            SmsPackagesStatisticsRequest req = new SmsPackagesStatisticsRequest();
////            req.setSmsSdkAppId(sdkAppId);
////            req.setLimit(100L);
////            req.setOffset(0L);
////            req.setBeginTime((String) getCurrentAndBeforeDate(beginTime, endTime, 7).get("beginTime"));
////            req.setEndTime(((String) getCurrentAndBeforeDate(beginTime, endTime, 7).get("endTime")));
////
////            /* 通过 client 对象调用 SendStatusStatistics 方法发起请求。注意请求方法名与请求对象是对应的
////             * 返回的 res 是一个 SendStatusStatisticsResponse 类的实例，与请求对象对应 */
////            SmsPackagesStatisticsResponse res = client.SmsPackagesStatistics(req);
////
////            // 输出json格式的字符串回包
////            String resString = SendStatusStatisticsResponse.toJsonString(res);
////            JSONObject resp = JSONUtil.parseObj(resString);
////
////            System.out.println(resp);
////            /*
////            {
////                "SmsPackagesStatisticsSet": [
////                    {
////                        "PackageCreateTime": 1713863741,
////                        "PackageEffectiveTime": 1713863741,
////                        "PackageExpiredTime": 1721726141,
////                        "PackageAmount": 500,
////                        "PackageType": 0,
////                        "PackageId": 1002730611,
////                        "CurrentUsage": 13
////                    }
////                ],
////                "RequestId": "15f81795-7a14-43cc-9215-efcc8886e1af"
////            }
////             */
////            List<Map<String, Object>> list = (List<Map<String, Object>>) MapUtil.get(resp, "SmsPackagesStatisticsSet");
////            List<Map<String, Object>> result = ListUtil.convertToUnderscoreCase(list);
////
////            return result;
////
////
////        } catch (TencentCloudSDKException e) {
////            e.printStackTrace();
////        }
////        return null;
////    }
//
//    /**
//     * [腾讯云] 号码信息查询
//     */
////    @Override
////    public List<Map<String, Object>> getDescribePhoneNumberInfo(String phones) {
////        try {
////
////            if (phones == null) {
////                throw new CustException("手机号码不能为空");
////            }
////            String[] phoneNumberSet = phones.split(",");
////
////            // ----------------------------------------------------------------------
////            Credential cred = new Credential(SECRET_ID, SECRET_KEY);
////            ClientProfile clientProfile = new ClientProfile();
////            SmsClient client = new SmsClient(cred, "ap-guangzhou",clientProfile);
////
////            DescribePhoneNumberInfoRequest req = new DescribePhoneNumberInfoRequest();
////            req.setPhoneNumberSet(phoneNumberSet);
////
////            DescribePhoneNumberInfoResponse res = client.DescribePhoneNumberInfo(req);
////
////            // 输出json格式的字符串回包
////            String resString = SendStatusStatisticsResponse.toJsonString(res);
////            JSONObject resp = JSONUtil.parseObj(resString);
////            /*
////            {
////                "PhoneNumberInfoSet": [
////                    {
////                        "Code": "InvalidParameterValue.IncorrectPhoneNumber",
////                        "Message": "incorrect phoneNumber format",
////                        "NationCode": "",
////                        "SubscriberNumber": "",
////                        "PhoneNumber": "13670511519",
////                        "IsoCode": "DEF",
////                        "IsoName": ""
////                    }
////                ],
////                "RequestId": "b49704fe-5286-4d4a-87eb-f560a72320ab"
////            }
////             */
////
////            List<Map<String, Object>> list = (List<Map<String, Object>>) MapUtil.get(resp, "PhoneNumberInfoSet");
////            List<Map<String, Object>> result = ListUtil.convertToUnderscoreCase(list);
////
////            return result;
////
////
////        } catch (TencentCloudSDKException e) {
////            e.printStackTrace();
////        }
////        return null;
////    }
//}
