package com.hys.app.service.base.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.hys.app.framework.exception.ServiceException;
import com.hys.app.model.errorcode.SystemErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hys.app.framework.util.StringUtil;
import com.hys.app.model.system.dos.SmsTemplate;
import com.hys.app.model.system.enums.SmsTemplateTypeEnum;
import com.hys.app.service.base.plugin.sms.SmsAliPlugin;
import com.hys.app.service.base.service.AliSmsApiManager;
import com.hys.app.service.system.SmsPlatformManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 阿里云短信API
 *
 * @author zhangsong
 * @version v1.0
 * @since v7.3.0
 * 2021-01-27
 */
@Service
public class AliSmsApiManagerImpl implements AliSmsApiManager {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    private final String SUCCESS_CODE = "OK";

    private final String GATEWAY_CODE = "isp.GATEWAY_ERROR";
    @Autowired
    private SmsAliPlugin smsAliPlugin;
    @Autowired
    private SmsPlatformManager smsPlatformManager;

    @Override
    public void addSmsTemplate(SmsTemplate model) {
        //发起请求
        AddSmsTemplateResponseBody result = null;
        try {
            Client client = this.createClient();
            AddSmsTemplateRequest addSmsTemplateRequest = new AddSmsTemplateRequest()
                    //模板类型
                    .setTemplateType(SmsTemplateTypeEnum.valueOf(model.getTemplateType()).aliTypeCode())
                    //模板名称
                    .setTemplateName(model.getTemplateName())
                    //模板内容
                    .setTemplateContent(model.getTemplateContent())
                    //申请说明
                    .setRemark(model.getRemark());
            AddSmsTemplateResponse response = client.addSmsTemplate(addSmsTemplateRequest);
            //请求结果
            result = response.getBody();
        } catch (Exception e) {
            throw new ServiceException(SystemErrorCode.E931.code(), "接口调用失败");
        }
        //请求状态码
        String code = result.getCode();
        //返回的模板code
        String templateCode = result.getTemplateCode();
        logger.info("阿里云短信接口返回" + result.toMap());
        if (GATEWAY_CODE.equals(code)) {
            throw new ServiceException(SystemErrorCode.E931.code(), "阿里云网络请求限制,不能连续提交请1分钟后再试");
        }
        if (!SUCCESS_CODE.equals(code)) {
            throw new ServiceException(SystemErrorCode.E931.code(), "接口调用失败");
        }
        //设置返回的模板code
        model.setTemplateCode(templateCode);
    }

    @Override
    public void deleteSmsTemplate(String templateCode) {

        try {
            Client client = this.createClient();
            DeleteSmsTemplateRequest deleteSmsTemplateRequest = new DeleteSmsTemplateRequest().setTemplateCode(templateCode);
            //发起请求
            DeleteSmsTemplateResponse response = client.deleteSmsTemplate(deleteSmsTemplateRequest);
            //请求结果
            DeleteSmsTemplateResponseBody result = response.getBody();

            //请求状态码
            String code = result.getCode();

            logger.info("阿里云短信接口返回" + result.toMap());
            if (!SUCCESS_CODE.equals(code)) {
                throw new ServiceException(SystemErrorCode.E931.code(), "接口调用失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(SystemErrorCode.E931.code(), "接口调用失败");
        }
    }

    /**
     * 创建阿里云请求客户端
     *
     * @return
     */
    private Client createClient() throws Exception {

        //获取配置参数
        Map<String, String> configMap = smsPlatformManager.getConfigMap(smsAliPlugin.getPluginId());
        this.checkConfig(configMap);

        String accessKeyId = configMap.get("access_key_id");
        String accessKeySecret = configMap.get("access_key_secret");

        Config config = new Config();
        config.accessKeyId = accessKeyId;
        config.accessKeySecret = accessKeySecret;
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }


    private void checkConfig(Map<String, String> configMap) {
        if (StringUtil.isEmpty(configMap.get("sign_name"))) {
            throw new ServiceException(SystemErrorCode.E931.code(), "短信签名未配置，请联系管理员");
        }
        if (StringUtil.isEmpty(configMap.get("access_key_id"))) {
            throw new ServiceException(SystemErrorCode.E931.code(), "access_key_id未正确配置，请联系管理员");
        }
        if (StringUtil.isEmpty(configMap.get("access_key_secret"))) {
            throw new ServiceException(SystemErrorCode.E931.code(), "access_key_secret未正确配置，请联系管理员");
        }
    }

}
