package com.tofly.xrtygis.custom.service.impl;

import cn.hutool.crypto.digest.MD5;
import cn.hutool.http.HttpRequest;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.xrtygis.custom.service.SendSmsService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Bubble
 */
@Service
public class SendSmsServiceImpl implements SendSmsService {

  @Value("${sms.push.appid}")
  private String appid;

  @Value("${sms.push.appkey}")
  private String appkey;

  @Value("${sms.push.sendUrl}")
  private String sendUrl;

  /**
   * 发送短信接口
   *
   * @param phone 电话
   * @param content 内容
   * @return boolean
   */
  @Override
  public String sendSms(String phone, String content) {
    if (StringUtils.isBlank(phone)) {
      throw new RuntimeException("手机号码不能为空");
    }
    if (StringUtils.isBlank(content)) {
      throw new RuntimeException("短信内容不能为空");
    }
    Map<String, Object> params = new HashMap<>();
    params.put("appid", appid);
    params.put("mobile", phone);
    params.put("msg", content);
    params.put("sign", new MD5().digestHex(appid + phone + content + appkey).toLowerCase());

    return HttpRequest.post(sendUrl).form(params).execute().body();
  }

  /**
   * 获取短信签名
   *
   * @return list
   */
  @Override
  public List<String> getSmsSignature() {
    // 缺少【】短信签名会返回异常信息
    String resultMsg = sendSms("13611111111", "获取短信签名");
    if (resultMsg.contains("【") && resultMsg.contains("】")) {
        String substring = resultMsg.substring(resultMsg.indexOf("【"),resultMsg.lastIndexOf("】") + 1);
        return Arrays.asList(substring.split(","));
    }else {
        throw new ToflyDeniedException(resultMsg);
    }
  }
}
