package com.hzs.third.sms.util;

import cn.hutool.json.JSONUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.hzs.common.core.constant.Constants;
import com.hzs.common.core.enums.EAliSmsTemplate;
import com.hzs.common.core.utils.SpringUtils;
import com.hzs.third.sms.config.SmsConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.models.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 发送短信工具类
 */
@Slf4j
@Component
public class SmsUtil implements InitializingBean {

    private static SmsConfig smsConfig;

    /**
     * 发送阿里短信
     *
     * @param phone 手机号
     * @param code  验证码
     * @return
     */
    public static String sendAliSms(String phone, String code, EAliSmsTemplate aliSmsTemplate) {
        if (StringUtils.isAnyEmpty(phone, code)) {
            return "手机号或验证码为空";
        }
        log.info("短信验证码,发送手机号：{}, code:{}", phone, code);
        if (smsConfig.isEnable()) {
            // 只有当开启发送短信才进行发送
            try {
                Map<String, String> templateParam = new HashMap<>();
                templateParam.put("code", code);

                Client client = new Client(new Config()
                        .setAccessKeyId(smsConfig.getAliAccessKeyId())
                        .setAccessKeySecret(smsConfig.getAliAccessKeySecret())
                        // 短信发送域
                        .setEndpoint(smsConfig.getAliEndpoint()));

                SendSmsRequest sendSmsRequest = new SendSmsRequest()
                        .setPhoneNumbers(phone)
                        // 短信签名
                        .setSignName(smsConfig.getAliSign())
                        // 短信模板
                        .setTemplateCode(aliSmsTemplate.getCode())
                        .setTemplateParam(JSONUtil.toJsonStr(templateParam));

//                log.info("阿里云短信发送参数: {}", sendSmsRequest);

                SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);

//                log.info("阿里云短信发送结果: {}", sendSmsResponse.getBody());

                if (Constants.SUCCESS.equals(sendSmsResponse.getStatusCode())) {
                    if ("OK".equals(sendSmsResponse.getBody().getCode())) {
                        return null;
                    }
                    log.error("阿里云短信发送失败: {}", sendSmsResponse.getBody().getMessage());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public void afterPropertiesSet() {
        smsConfig = SpringUtils.getBean(SmsConfig.class);
    }

}
