package com.bootdo.datas.service.impl;

import java.io.UnsupportedEncodingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bootdo.datas.service.LogInfoService;
import com.bootdo.datas.service.SmsService;
import com.bootdo.datas.tools.OkHttpUtil;
import com.bootdo.datas.tools.SmsMD5;

/**
 * @date 2022/3/17 14:47
 * @author wangp
 * @description
 */
@Service
public class SmsServiceimpl implements SmsService {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private LogInfoService logService;

    //@Value("${sms.cpcode}")
    public String cpcode;

    //@Value("${sms.key}")
    public String key;

    //@Value("${sms.templetid}")
    public String templetid;

   // @Value("${sms.smsUrl}")
    public String smsUrl;

    /**
     * @Description: 短信下发
     * @Author: wangp
     * @Date: 2022/3/17 14:51
     * @param mobile
     * @param content
     * @Return: void
     */
    @Override
    public void sendSMS(String mobile, String content) {
        // 开始时间
        long requestTime = System.currentTimeMillis();
        String result = "fail";
        String result_desc = "调用失败";
        String excode = "";
        String md5source = cpcode + content + mobile + excode + templetid + key;
        log.info("md5source:" + md5source);
        String md5str = "";
        try {
            md5str = SmsMD5.makeMD5(new String(md5source.getBytes("UTF-8"), "UTF-8")).toLowerCase();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        log.info("md5str:" + md5str);
        // 参数拼装
        JSONObject smsJson = new JSONObject();
        smsJson.put("cpcode", cpcode);
        smsJson.put("msg", content);
        smsJson.put("mobiles", mobile);
        smsJson.put("excode", excode);
        smsJson.put("templetid", templetid);
        smsJson.put("sign", md5str);
        log.info("smsJson:" + smsJson);
        String resultInfo = OkHttpUtil.postJsons(smsUrl, smsJson.toString());
        // 结果遍历
        JSONObject jsonObject = JSON.parseObject(resultInfo);
        result = jsonObject.getString("resultcode");
        result_desc = jsonObject.getString("resultmsg");
        log.info("result:" + result + ",result_desc:" + result_desc);
        // 结束时间
        long responseTime = System.currentTimeMillis();
        long cost = responseTime - requestTime;
        logService.saveThird("sms", mobile, String.valueOf(cost), result, result_desc, "sms", content);
    }
}
