package com.czg.service.system.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.czg.constants.ParamCodeCst;
import com.czg.exception.CzgException;
import com.czg.system.service.SmsService;
import com.czg.system.service.SysParamsService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;

import java.util.Map;
import java.util.Set;

/**
 * 验证码工具类
 *
 * @author Administrator
 */
@DubboService
@Slf4j
public class SmsServiceImpl implements SmsService {
    @Resource
    private SysParamsService sysParamsService;

    /**
     * 短信模板id
     */
    private String templateCode;

    public Client init() throws Exception {
        Config config = new Config();
        Map<String, String> aliOssKeys = sysParamsService.getParamsByMap("ali_oss_key_set", ParamCodeCst.ALI_OSS_KEY_SET);
        config.accessKeyId = aliOssKeys.get(ParamCodeCst.AliYun.ALI_SMS_KEY);
        config.accessKeySecret = aliOssKeys.get(ParamCodeCst.AliYun.ALI_SMS_SECRET);
        templateCode = aliOssKeys.get(ParamCodeCst.AliYun.ALI_SMS_TEMPLATE_CODE);
        return new Client(config);
    }

    @Override
    public void sendCode(String phone, String checkCode) {
        try {
            Client client = init();
            // 1.发送短信
            com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                    .setSignName("陕西超掌柜科技")
                    .setTemplateCode(templateCode)
                    .setTemplateParam("{\"code\":" + "'" + checkCode + "'" + "}")
                    .setPhoneNumbers(phone);
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            log.info("短信发送请求参数: 手机号: {}, 短信模板: {}, 短信内容: {}", phone, templateCode, checkCode);
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
            if (sendSmsResponse.getStatusCode() != 200) {
                throw new CzgException("短信发送失败");
            }
        } catch (Exception e) {
            log.info("发送短信失败", e);
        }
    }
}
