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.enums.ESmsTemplate;
import com.hzs.common.core.utils.HttpClientUtil;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

    private static SmsConfig smsConfig;

    // 会员预置短信模板
    private static List<String> memberTemplateList;

    // 订单预置短信模板
    private static List<String> orderTemplateList;

    /**
     * 发送短信
     *
     * @param phone   手机号
     * @param content 发送内容
     * @return
     */
    public static String sendSms(String phone, String content) {
        if (StringUtils.isAnyEmpty(phone, content)) {
            return "手机号或内容为空";
        }

        if (smsConfig.isEnable()) {
            // 只有当开启发送短信才进行发送

            String corpid = smsConfig.getCorpId();
            String pwd = smsConfig.getPwd();
            String url = smsConfig.getUrl();

            if (phone.length() == 10 && phone.startsWith("09")) {
                // 台湾手机号码处理（10位长度，以09开头）
                corpid = smsConfig.getCorpIdInter();
                pwd = smsConfig.getPwdInter();
                url = smsConfig.getUrl();
            }

            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("corpid", corpid);
            paramMap.put("pwd", pwd);
            paramMap.put("mobile", phone);
            paramMap.put("content", content);

            log.info("短信发送参数: {}", paramMap);

            String result = HttpClientUtil.get(url, paramMap);

            log.info("短信发送结果: {}", result);

            if (StringUtils.isNotEmpty(result)) {
                if (Integer.parseInt(result) > 0) {
                    return null;
                } else {
                    log.error("短信发送失败, status: {}", result);
                }
            }
            return "发送失败";
        } else {
            log.info("短信发送手机：{}, 内容: {}", phone, content);
        }
        return null;
    }

    /**
     * 发送阿里短信
     *
     * @param phone 手机号
     * @param code  验证码
     * @return
     */
    public static String sendAliSms(String phone, String code, EAliSmsTemplate aliSmsTemplate) {
        if (StringUtils.isAnyEmpty(phone, code)) {
            return "手机号或验证码为空";
        }
        System.out.println("手机验证码："+ 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;
    }

    public static List<String> getMemberTemplateList() {
        return memberTemplateList;
    }

    public static List<String> getOrderTemplateList() {
        return orderTemplateList;
    }

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

        // 会员预置短信模板初始化
        memberTemplateList = new ArrayList<>();

        // 订单预置短信模板初始化
        orderTemplateList = new ArrayList<>();
        orderTemplateList.add(ESmsTemplate.SMS21.getCode());
        orderTemplateList.add(ESmsTemplate.SMS22.getCode());
        orderTemplateList.add(ESmsTemplate.SMS23.getCode());
        orderTemplateList.add(ESmsTemplate.SMS24.getCode());
        orderTemplateList.add(ESmsTemplate.SMS25.getCode());
        orderTemplateList.add(ESmsTemplate.SMS26.getCode());
        orderTemplateList.add(ESmsTemplate.SMS27.getCode());
        orderTemplateList.add(ESmsTemplate.SMS28.getCode());
        orderTemplateList.add(ESmsTemplate.SMS29.getCode());
    }

}
