package com.fs.sms.service.impl;

import com.alibaba.fastjson.JSON;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.sms.config.SmsConfig;
import com.fs.sms.domain.*;
import com.fs.sms.service.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.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

@Service
public class SmsTServiceImpl implements SmsService {
    @Autowired
    private RedisCache redisCache;

    @Override
    public R sendTSms(String mobile, String code) {
        try {
            Credential cred = new Credential("AKIDdAdvzoQpzuOo11mq2TntjKI5eqrhNp22", "zmLgpzzcwAFNJ4dx2iDTVHgw3ELCrIVg");
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("sms.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            SmsClient client = new SmsClient(cred, "ap-beijing", clientProfile);
            String params = "{\"PhoneNumberSet\":[\"86" + mobile + "\"],\"TemplateID\":\"1982054\",\"Sign\":\"重庆润方数字科技有限公司\",\"TemplateParamSet\":[\"" + code + "\"],\"SmsSdkAppid\":\"1400867365\"}";
            SendSmsRequest req = SendSmsRequest.fromJsonString(params, SendSmsRequest.class);

            SendSmsResponse resp = client.SendSms(req);
            if (resp.getSendStatusSet() != null && resp.getSendStatusSet()[0].getCode().equals("Ok")) {
                // 将手机号写入redis
                redisCache.setCacheObject(mobile, String.valueOf(code), 120, TimeUnit.SECONDS);
                return R.ok("短信成功发送");
            } else {
                return R.error("短信发送失败:" + resp.getSendStatusSet()[0].getCode());
            }


        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
            return R.error(e.toString());
        }

    }

    @Override
    public SendSmsReturn sendSms(String account, String password, String content, String phone) {

        SendSms sendSmS = new SendSms();
        sendSmS.setAccount(account);
        sendSmS.setPassword(password);
        sendSmS.setContent(content);
        sendSmS.setPhones(phone);
        String sendReturn = sendHttp(SmsConfig.smsSubmit, sendSmS);
        SendSmsReturn sendSmsReturn = JSON.parseObject(sendReturn, SendSmsReturn.class);
        System.out.println(sendSmsReturn);
        return sendSmsReturn;
    }

    @Override
    public R querySms(String account, String password, String starttime, String endtime, String tjtype) {

        QuerySms sms = new QuerySms();
        sms.setAccount(account);
        sms.setPassword(password);
        sms.setStarttime(starttime);
        sms.setEndtime(endtime);
        sms.setTjtype(tjtype);
        sms.setMessagetype("1");
        String sendReturn = sendHttp(SmsConfig.querySms, sms);
        QuerySmsReturn querySmsReturn = JSON.parseObject(sendReturn, QuerySmsReturn.class);
        System.out.println(querySmsReturn);
        return R.ok();
    }

    @Override
    public R uploadTemplate(String account, String password, String content,String sign, String remark) {
        SmsUpTemp sms = new SmsUpTemp();
        sms.setAccount(account);
        sms.setPassword(password);
        sms.setContent(content);
        sms.setSign(sign);
        sms.setRemark(remark);
        String sendReturn = sendHttp(SmsConfig.uploadTemplate, sms);
        SmsTempReturn smsTempReturn = JSON.parseObject(sendReturn, SmsTempReturn.class);
        System.out.println(smsTempReturn);
        return R.ok();
    }
    @Override
    public R showTemplate(String account, String password, String templateIds) {
        SmsShowTemp sms = new SmsShowTemp();
        sms.setAccount(account);
        sms.setPassword(password);
        sms.setTemplateIds(templateIds);
        String sendReturn = sendHttp(SmsConfig.showTemplate, sms);
        SmsShowTempReturn smsTempReturn = JSON.parseObject(sendReturn, SmsShowTempReturn.class);
        System.out.println(smsTempReturn);
        return R.ok();
    }
    public R updateTemplate(String account, String password, String content,String templateIds, String remark) {
        SmsUpdateTemp sms = new SmsUpdateTemp();
        sms.setAccount(account);
        sms.setPassword(password);
        sms.setContent(content);
        sms.setTemplateIds(templateIds);
        sms.setRemark(remark);
        String sendReturn = sendHttp(SmsConfig.updateTemplate, sms);
        SmsUpdateTempReturn smsTempReturn = JSON.parseObject(sendReturn, SmsUpdateTempReturn.class);
        System.out.println(smsTempReturn);
        return R.ok();
    }
    public R deleteTemplate(String account, String password, String templateIds) {
        SmsDeleteTemplate sms = new SmsDeleteTemplate();
        sms.setAccount(account);
        sms.setPassword(password);
        sms.setTemplateIds(templateIds);
        String sendReturn = sendHttp(SmsConfig.deleteTemplate, sms);
        SmsDeleteTemplateReturn smsTempReturn = JSON.parseObject(sendReturn, SmsDeleteTemplateReturn.class);
        System.out.println(smsTempReturn);
        return R.ok();
    }

    String sendHttp(String url,Object o){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String responseText="";
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/json");

            String jsonString = JSON.toJSONString(o);
            StringEntity stringEntity = new StringEntity(jsonString, StandardCharsets.UTF_8);
            httpPost.setEntity(stringEntity);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                responseText = EntityUtils.toString(entity, "UTF-8");
            }
            response.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseText;
    }


}
