package com.izouma.dingdong.service.sms;

import com.izouma.dingdong.domain.SmsRecord;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.SmsRecordRepo;
import com.izouma.dingdong.service.sms.SmsService;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Arrays;

/**
 * Tencent Cloud Sms Sendsms
 * https://cloud.tencent.com/document/product/382/38778
 */
@Service
@Slf4j
public class TencentSmsService {
    @Value("${tencent.secret_id}")
    private String        secretId;
    @Value("${tencent.secret_key}")
    private String        secretKey;
    @Value("${tencent.sms_appid}")
    private String        appId;
    @Autowired
    private SmsRecordRepo smsRecordRepo;


    public String sendVerify(String phone, String templateId) {
        // 签名，使用的是`签名内容`，而不是`签名ID`
        String smsSign = "弗雷登";

        String param = RandomStringUtils.randomNumeric(4);

        try {
            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey
            Credential cred = new Credential(secretId, secretKey);
            //请求李心洁
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("sms.tencentcloudapi.com");

            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);

            SmsClient client = new SmsClient(cred, "", clientProfile);

            String params = "{\"PhoneNumberSet\":[\"" + phone
                    + "\"],\"TemplateID\":\"" + templateId
                    + "\",\"Sign\":\"" + smsSign
                    + "\",\"TemplateParamSet\":[\"" + param
                    + "\"],\"SmsSdkAppid\":\"" + appId + "\"}";

            //发送请求
            SendSmsRequest req = SendSmsRequest.fromJsonString(params, SendSmsRequest.class);
            //国际短信必传
            req.setSenderId("Qcloud");
            //回调
            SendSmsResponse resp = client.SendSms(req);
            log.info("send sms response {}", Arrays.toString(resp.getSendStatusSet()));
            //String s = SendSmsResponse.toJsonString(resp);
            SendStatus status = resp.getSendStatusSet()[0];
            if (!status.getCode().equals("Ok")) {
                throw new BusinessException("发送失败，请稍后再试", status.getCode() + "," + status.getMessage());
            }
            //保存到sms表
            smsRecordRepo.expire(phone);
            String sessionId = RandomStringUtils.randomAlphabetic(10);
//            String sessionId = resp.getRequestId();
            smsRecordRepo.save(SmsRecord.builder()
                    .sessionId(sessionId)
                    .phone(phone)
                    .code(param)
                    .expiresAt(LocalDateTime.now().plusMinutes(5))
                    .expired(false)
                    .build());

            //System.out.println(s);
            return sessionId;
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
            throw new BusinessException("发送失败，请稍后再试", e.getMessage());
        }

    }

}