package com.ichangzuo.module.sms.service.impl;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import com.ichangzuo.module.sms.service.SmsService;
import com.ichangzuo.config.property.AliyunSmsProperties;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * 阿里云短信业务类
 *
 * @author Ray
 * @since  2024/8/17
 */
@Service
@RequiredArgsConstructor
public class AliyunSmsService implements SmsService {

    private static final Logger log = LoggerFactory.getLogger(AliyunSmsService.class);
    private final AliyunSmsProperties aliyunSmsProperties;

    /**
     * 发送短信验证码
     *
     * @param mobile   手机号 13388886666
     * @param templateCode  短信模板 SMS_194640010
     * @param templateParam 模板参数 "[{"code":"123456"}]"
     *
     * @return  boolean 是否发送成功
     */
    @Override
    public boolean sendSms(String mobile,String templateCode,String templateParam) {
        if(aliyunSmsProperties.getAccessKeyId().equals("123456")) //测试版本
            return true;

        DefaultProfile profile = DefaultProfile.getProfile(aliyunSmsProperties.getRegionId(),
                aliyunSmsProperties.getAccessKeyId(), aliyunSmsProperties.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);

        SendSmsRequest request = new SendSmsRequest();
        request.setSignName(aliyunSmsProperties.getSignName());
        request.setTemplateCode(templateCode);
        request.setPhoneNumbers(mobile);
        request.setTemplateParam(templateParam);

        try {
            SendSmsResponse response = client.getAcsResponse(request);
            log.info("Send sms response: " + response.getMessage());
            return response.getCode().equals("OK");
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            log.error(e.getErrMsg());
//            System.out.println("ErrCode:" + e.getErrCode());
//            System.out.println("ErrMsg:" + e.getErrMsg());
//            System.out.println("RequestId:" + e.getRequestId());
        }

        return false;
    }


}
