package com.yihu.jw.sms.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.sms.dao.HospitalSysDictDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: yeshijie
 * @Date: 2021/5/24
 * @Description:
 */
@Service
public class TXYSmsService {
    private Logger logger= LoggerFactory.getLogger(ZBSmsService.class);
    @Autowired
    private HospitalSysDictDao sysDictDao;
    @Autowired
    private StringRedisTemplate redisTemplate;

    private String key = "hz_yxyzh_wx_sms";

    private String SecretId;
    private String SecretKey;
    private String signName;
    private String smsSdkAppId;
    private String VerificationCode;

    /**
     * 初始化接口参数
     */
    private void init(){
        if(redisTemplate.hasKey(key+ ":SecretId")){
            SecretId = redisTemplate.opsForValue().get(key + ":SecretId");
            SecretKey = redisTemplate.opsForValue().get(key + ":SecretKey");
            signName = redisTemplate.opsForValue().get(key + ":signName");
            smsSdkAppId = redisTemplate.opsForValue().get(key + ":smsSdkAppId");
            VerificationCode = redisTemplate.opsForValue().get(key + ":VerificationCode");
            return;
        }

        List<WlyyHospitalSysDictDO> dictDOList = sysDictDao.findByDictName(key);
        for (WlyyHospitalSysDictDO wlyyHospitalSysDictDO:dictDOList){
            if (wlyyHospitalSysDictDO.getDictCode().equalsIgnoreCase("SecretId")){
                SecretId=wlyyHospitalSysDictDO.getDictValue();
                redisTemplate.opsForValue().set(key + ":SecretId",SecretId);
            }else if (wlyyHospitalSysDictDO.getDictCode().equalsIgnoreCase("SecretKey")){
                SecretKey=wlyyHospitalSysDictDO.getDictValue();
                redisTemplate.opsForValue().set(key + ":SecretKey",SecretKey);
            }else if (wlyyHospitalSysDictDO.getDictCode().equalsIgnoreCase("signName")){
                signName=wlyyHospitalSysDictDO.getDictValue();
                redisTemplate.opsForValue().set(key + ":signName",signName);
            }else if (wlyyHospitalSysDictDO.getDictCode().equalsIgnoreCase("smsSdkAppId")){
                smsSdkAppId=wlyyHospitalSysDictDO.getDictValue();
                redisTemplate.opsForValue().set(key + ":smsSdkAppId",smsSdkAppId);
            }else if (wlyyHospitalSysDictDO.getDictCode().equalsIgnoreCase("VerificationCode")){
                VerificationCode=wlyyHospitalSysDictDO.getDictValue();
                redisTemplate.opsForValue().set(key + ":VerificationCode",VerificationCode);
            }
        }
    }

    public String sendMessage(String mobile,String code){
        try{
            init();
            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, "ap-nanjing", clientProfile);

            SendSmsRequest req = new SendSmsRequest();
            String[] phoneNumberSet1 = {"+86"+mobile};
            req.setPhoneNumberSet(phoneNumberSet1);

            req.setSmsSdkAppId(smsSdkAppId);
            req.setSignName(signName);
            req.setTemplateId(VerificationCode);

            String[] templateParamSet1 = {code};
            req.setTemplateParamSet(templateParamSet1);

            SendSmsResponse resp = client.SendSms(req);
            JSONObject json = JSON.parseObject(SendSmsResponse.toJsonString(resp));
            String res = json.getJSONArray("SendStatusSet").getJSONObject(0).getString("Code");
            if(!"Ok".equals(res)){
                logger.info("腾讯短信发送失败："+SendSmsResponse.toJsonString(resp));
            }
            return res;
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
            logger.info("腾讯短信报错："+e.toString());
        }
        return "error";
    }

    /**
     *
     * @param mobile
     * @param jsonObj {"templateCode":"974603","templateParamArr":["param1","param2","param3"]}
     * @return   模板id暂时写死
     */
    public String sendMessageJson(String mobile,JSONObject jsonObj){
        try {
            init();
            Credential cred = new Credential(SecretId, SecretKey);

            String templateId = jsonObj.getString("templateCode");
            JSONArray templateParamArr = jsonObj.getJSONArray("templateParamArr");
            String[] templateParamSet1 = templateParamArr.toArray(new String[0]);

            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("sms.tencentcloudapi.com");

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

            SmsClient client = new SmsClient(cred, "ap-nanjing", clientProfile);

            SendSmsRequest req = new SendSmsRequest();
            String[] phoneNumberSet1 = {"+86"+mobile};

            req.setPhoneNumberSet(phoneNumberSet1);

            req.setSmsSdkAppId(smsSdkAppId);
            req.setSignName(signName);
            req.setTemplateId(templateId);

            if(templateParamSet1.length>0){
                req.setTemplateParamSet(templateParamSet1);
            }
            SendSmsResponse resp = client.SendSms(req);

            JSONObject json = JSON.parseObject(SendSmsResponse.toJsonString(resp));
            String res = json.getJSONArray("SendStatusSet").getJSONObject(0).getString("Code");
            if(!"Ok".equals(res)){
                logger.info("腾讯短信发送失败："+SendSmsResponse.toJsonString(resp));
            }
            return res;


        }catch (TencentCloudSDKException e){
            e.printStackTrace();
            logger.info("腾讯短信报错："+e.toString());
        }
        return "error";
    }

}
