package com.njcn.msgpush.module.push.client.channel.sms.Impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.njcn.msgpush.module.push.client.channel.sms.SmsClient;
import com.njcn.msgpush.module.push.client.setting.sms.AliYunSmsSetting;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import static com.aliyun.teautil.Common.toJSONString;


/**
 * @author caozehui
 * @data 2026-02-11
 * @description 阿里云短信服务实现
 */
@Slf4j
@Service
public class AliYunSmsClient implements SmsClient {

    public static final String SIGN_NAME = "signName";
    public static final String TEMPLATE_CODE = "templateCode";
    public static final String TEMPLATE_PARAM = "templateParam";
    public static final String OK = "OK";


    @Autowired
    private AliYunSmsSetting aliYunSmsSetting;
    private Client client;

    private static final ThreadPoolExecutor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(
            5,
            5,
            1000,
            TimeUnit.MILLISECONDS,
            new java.util.concurrent.ArrayBlockingQueue<>(1000),
            r -> {
                Thread thread = new Thread(r);
                thread.setName("AliYunSmsClient-Pool-" + thread.getId());
                thread.setDaemon(false);
                return thread;
            },
            new ThreadPoolExecutor.CallerRunsPolicy()
    );

    @PostConstruct
    public void init() {
        Config config = new Config()
                .setAccessKeyId(aliYunSmsSetting.getAccessKeyId())
                .setAccessKeySecret(aliYunSmsSetting.getAccessKeySecret())
                .setRegionId(aliYunSmsSetting.getRegionId())
                .setEndpoint(aliYunSmsSetting.getEndpoint());

        try {
            this.client = new Client(config);
        } catch (Exception e) {
            log.error("阿里云-短信服务初始化失败，请检查配置信息");
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean sendSms(Map<String, Object> params, String phoneNumber) throws Exception {
        Future<Boolean> future = THREAD_POOL_EXECUTOR.submit(() -> {
            // todo 修改消息的状态为 sending

            RuntimeOptions runtimeOptions = new RuntimeOptions();
            // 设置自动重试，默认是不开启的。重试次数默认是3次
            runtimeOptions.autoretry = true;
            SendSmsRequest request = new SendSmsRequest()
                    .setPhoneNumbers(phoneNumber)
                    .setSignName(params.get(SIGN_NAME).toString())
                    .setTemplateCode(params.get(TEMPLATE_CODE).toString())
                    .setTemplateParam(params.get(TEMPLATE_PARAM).toString());
            try {
                SendSmsResponse response = this.client.sendSmsWithOptions(request, runtimeOptions);
                System.out.println(toJSONString(response));
                if (OK.equals(response.body.code)) {
                    return true;
                } else {
                    return false;
                }
            } catch (Exception e) {
                log.error("阿里云-短信服务发送失败");
                throw new Exception(e);
            }
        });
        Boolean b = future.get(3, TimeUnit.SECONDS);
        if (b) {
            // todo 修改消息的状态为 success
        } else {
            // todo 修改消息的状态为 failed
        }
        return b;
    }

    @Override
    public boolean sendBatchSms(Map<String, Object> params, List<String> phoneNumbers) {
        RuntimeOptions runtimeOptions = new RuntimeOptions();
        // 设置自动重试，默认是不开启的。重试次数默认是3次
        runtimeOptions.autoretry = true;
        SendBatchSmsRequest request = new SendBatchSmsRequest()
                .setPhoneNumberJson(toJSONString(phoneNumbers))
                .setSignNameJson(toJSONString(params.get(SIGN_NAME)))
                .setTemplateCode(params.get(TEMPLATE_CODE).toString())
                .setTemplateParamJson(toJSONString(params.get(TEMPLATE_PARAM)));
        try {
            SendBatchSmsResponse response = this.client.sendBatchSmsWithOptions(request, runtimeOptions);
            System.out.println(toJSONString(response));
            if (OK.equals(response.body.code)) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            log.error("阿里云-短信服务发送失败");
            throw new RuntimeException(e);
        }
    }

    @Override
    public void querySmsTemplateList() {
        QuerySmsTemplateListRequest request = new QuerySmsTemplateListRequest();
        request.setPageIndex(1);
        request.setPageSize(10);
        try {
            QuerySmsTemplateListResponse querySmsTemplateListResponse = this.client.querySmsTemplateList(request);
            System.out.println(toJSONString(querySmsTemplateListResponse));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
