package com.ghy.web.controller.tool;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ghy.common.config.SmsConfig;
import com.ghy.common.constant.SmsConstants;
import com.ghy.common.core.domain.AjaxResult;
import com.ghy.common.utils.CacheUtils;
import com.ghy.common.utils.ExceptionUtil;
import com.ghy.common.utils.http.HttpUtils;
import com.ghy.common.utils.security.Md5Utils;
import com.ghy.web.pojo.vo.SmsRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 容联云短信
 * @author clunt
 */
@Slf4j
@Controller
@RequestMapping("/tool/sms")
public class SMSController {

    private static final ThreadLocal<SimpleDateFormat> timeFormat = ThreadLocal.withInitial(()->new SimpleDateFormat("yyyyMMddHHmmss"));

    @Autowired
    private SmsConfig smsConfig;

    @PostMapping("/send")
    @ResponseBody
    public AjaxResult sendSms(@RequestBody SmsRequest request){
        try {
            // 短信验证码
            String code = String.valueOf((int)((Math.random() * 9 + 1) * Math.pow(10,5)));

            // 拼接请求题
            List<String> dataList = new ArrayList<>();
            dataList.add(code);
            dataList.add("3");
            request.setAppId(smsConfig.getAppId());
            request.setTemplateId(SmsConstants.TEMPLATE_ID);
            request.setDatas(dataList);

            String url = (smsConfig.getUrl() + SmsConstants.TEMPLATE_PATH).replace("{accountSid}", smsConfig.getAccount());
            String time = timeFormat.get().format(new Date());
            String sigParameter = Md5Utils.hash(smsConfig.getAccount() + smsConfig.getToken() + time).toUpperCase();
            String authorization = Base64.getEncoder().encodeToString((smsConfig.getAccount() + ":" + time).getBytes(StandardCharsets.UTF_8));
            url = url.replace("{SigParameter}", sigParameter);
            Map<String, String> headerMap = new HashMap<>();
            headerMap.put("Content-Type", "application/json;charset=utf-8");
            headerMap.put("Accept", "application/json;");
            headerMap.put("Authorization", authorization);
            // 调用第三方短信服务
            String result = HttpUtils.sendPost(url, JSON.toJSONString(request), headerMap);
            if("000000".equals(JSONObject.parseObject(result).getString("statusCode"))){
                // 将短信验证码放进系统内存
                CacheUtils.put(request.getTo(), code);
                return AjaxResult.success("验证码发送成功!");
            }else {
                return AjaxResult.error(JSONObject.parseObject(result).getString("statusMsg"));
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error(ExceptionUtil.getExceptionMessage(e));
            return AjaxResult.error(e.getMessage());
        }
    }

}
