package org.dromara.resource.danmi_sms;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.dromara.resource.danmi_sms.common.*;
import org.dromara.resource.danmi_sms.config.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Service
public class DMSmsUtils {
  private static final Logger log = LoggerFactory.getLogger(DMSmsUtils.class);

  @Resource
  private Config config;

  @Value("${ruoyi.captchaSMS}")
  private int captchaSMS;

  private String accountTip = " 账号： %s ，密码：%s ，请及时登录更改登录密码";

  public DMSmsResult verificationCode(String sign, String mobile, String code) {
    SmsDto smsDto = signJsonToDto(sign);
    String params = code;
    return execute(mobile, params, smsDto.getVerification());
  }

  public DMSmsResult enterSuccess(String sign, String domain, String title, String mobile, String companyName, String password) {
    SmsDto smsDto = signJsonToDto(sign);
    String params = "";
    if (smsDto.getUnified() == null || smsDto.getUnified().intValue() == 0) {
      params = companyName;
    } else {
      params = companyName + "," + title + ",http://" + domain;
    }
    if (StringUtils.isNotEmpty(password)) {
      String account = String.format(this.accountTip, new Object[] { mobile, password });
      params = params + "," + account;
    } else {
      String account = String.format(this.accountTip, new Object[] { mobile, "" }).replaceAll(" ，密码：", "");
      params = params + "," + account;
    }
    return execute(mobile, params, smsDto.getMerchant());
  }

  public DMSmsResult rechargeInfoPush(String sign, String domain, String companyName, String taxSourcesName, String receiptAccount, String receiptBank, String receiptAccountName, String mobile, String routingNumber) {
    SmsDto smsDto = signJsonToDto(sign);
    if (smsDto != null && StringUtils.isBlank(smsDto.getRechargeInfo())) {
      log.error("充值信息发送短信：mobile:" + mobile + ",companyName:" + companyName + ",taxSourcesName:" + taxSourcesName + ",receiptAccount:" + receiptAccount + ",receiptAccountName:" + receiptAccountName + ",routingNumber:" + routingNumber);
      return new DMSmsResult();
    }
    if (StringUtils.isBlank(routingNumber))
      routingNumber = "无";
    String params = companyName + "," + taxSourcesName + "," + receiptAccountName + "," + receiptBank + "," + receiptAccount + "," + routingNumber;
    return execute(mobile, params, smsDto.getRechargeInfo());
  }

  public DMSmsResult invoicePush(String sign, String domain, String companyName, String params, String mobile) {
    SmsDto smsDto = signJsonToDto(sign);
    if (smsDto != null && StringUtils.isBlank(smsDto.getInvoce())) {
      log.error("开票短信推送：mobile:" + mobile + ",companyName:" + companyName + ",params:" + params);
      return new DMSmsResult();
    }
    params = companyName + "," + params;
    return execute(mobile, params, smsDto.getInvoce());
  }

  public DMSmsResult agentSuccess(String sign, String domain, String title, String mobile, String companyName, String password) {
    SmsDto smsDto = signJsonToDto(sign);
    String params = "";
    if (smsDto.getUnified() == null || smsDto.getUnified().intValue() == 0) {
      params = companyName + ",";
      if (StringUtils.isNotEmpty(password)) {
        String account = String.format(this.accountTip, new Object[] { mobile, password });
        params = companyName + "," + account;
      }
    } else {
      params = companyName + "," + title + ",http://" + domain;
      if (StringUtils.isNotEmpty(password)) {
        String account = String.format(this.accountTip, new Object[] { mobile, password });
        params = params + "," + account;
      }
    }
    return execute(mobile, params, smsDto.getAgent());
  }

  public DMSmsResult toSign(String sign, String domain, String mobile, String flowId) {
    SmsDto smsDto = signJsonToDto(sign);
    String params = "";
    if (smsDto.getUnified() == null || smsDto.getUnified().intValue() == 0) {
      params = flowId;
    } else {
      params = "http://" + domain + "," + flowId;
    }
    return execute(mobile, params, smsDto.getTosign());
  }

  public DMSmsResult recharge(String sign, String mobile, String companyName, String accountName, String money) {
    SmsDto smsDto = signJsonToDto(sign);
    String params = companyName + "," + accountName + "," + money;
    return execute(mobile, params, smsDto.getRecharge());
  }

  public DMSmsResult refund(String sign, String mobile, String companyName, String money, String number, String accountName) {
    SmsDto smsDto = signJsonToDto(sign);
    String params = companyName + "," + money + "," + number + "," + accountName;
    return execute(mobile, params, smsDto.getRefund());
  }

  public DMSmsResult giveout(String sign, String mobile, String companyName, String batchNumber, String successNum, String failNum) {
    SmsDto smsDto = signJsonToDto(sign);
    String params = companyName + "," + batchNumber + "," + successNum + "," + failNum;
    return execute(mobile, params, smsDto.getGiveout());
  }

  public DMSmsResult balance(String sign, String mobile, String companyName, String accountName, String money) {
    SmsDto smsDto = signJsonToDto(sign);
    String params = companyName + "," + accountName + "," + money;
    return execute(mobile, params, smsDto.getBalance());
  }

  public DMSmsResult toOnlineSign(String sign, String domain, String mobile, String flowId) {
    SmsDto smsDto = signJsonToDto(sign);
    String params = "";
    if (smsDto.getUnified() == null || smsDto.getUnified().intValue() == 0) {
      params = flowId;
    } else {
      params = "http://" + domain + "," + flowId;
    }
    return execute(mobile, params, smsDto.getToOnlineSign());
  }

  private DMSmsResult  execute(String mobile, String param, String templateid) {
    log.info("短信发送(验证码通知，会员营销):mobile:" + mobile + ",param:" + param + ",templateid:" + templateid);
    DMSmsResult dmSmsResult = new DMSmsResult();
    try {
      dmSmsResult.setSuccess(true);
      if (this.captchaSMS > 0) {
        StringBuilder sb = new StringBuilder();
        sb.append("accountSid").append("=").append(this.config.getAccount_sid());
        sb.append("&to").append("=").append(mobile);
        try {
          sb.append("&param").append("=").append(URLEncoder.encode(param, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
        }
        sb.append("&templateid").append("=").append(templateid);
        String body = sb.toString() + HttpUtil.createCommonParam(this.config.getAccount_sid(), this.config.getAuth_token());
        String result = HttpUtil.post(this.config.getBase_url(), body);
        log.info("短信发送(验证码通知，会员营销):result:" + result);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if ("0000".equals(jsonObject.getStr("respCode"))) {
          dmSmsResult.setSuccess(true);
          dmSmsResult.setSmsId(jsonObject.getStr("smsId"));
        } else {
          dmSmsResult.setSuccess(false);
          dmSmsResult.setErrorMsg(jsonObject.getStr("respDesc"));
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      dmSmsResult.setSuccess(false);
      dmSmsResult.setErrorMsg("短信发送失败");
    }
    return dmSmsResult;
  }

  public DMSmsSendResult getSmsSendResult(Long count) {
    log.info("短信发送回执拉取(验证码通知，会员营销):count: {}", count);
    DMSmsSendResult sendResult = new DMSmsSendResult();
    try {
      sendResult.setSuccess(true);
      if (this.captchaSMS > 0) {
        StringBuilder sb = new StringBuilder();
        sb.append("accountSid").append("=").append(this.config.getAccount_sid());
        sb.append("&").append("accountId").append("=").append(this.config.getAccount_id());
        sb.append("&").append("count").append("=").append(count);
        Long timestamp = Long.valueOf(System.currentTimeMillis());
        String body = sb.toString() + HttpUtil.createParamWithTime(this.config.getAccount_sid(), this.config.getAuth_token(), timestamp);
        String baseUrl = this.config.getBase_url().replaceAll("/sendSMS", "");
        String result = HttpUtil.post(baseUrl + "/receipt/pull", body);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if ("0000".equals(jsonObject.getStr("respCode"))) {
          sendResult.setSuccess(true);
          sendResult.setData(JSON.parseArray(jsonObject.getStr("smsResult"), DMSmsSendResultDtl.class));
        } else {
          sendResult.setSuccess(false);
          sendResult.setErrorMsg(jsonObject.getStr("respDesc"));
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      log.info("短信发送回执拉取(验证码通知，会员营销):result:" + e.getMessage());
      sendResult.setSuccess(false);
      sendResult.setErrorMsg("短信发送失败");
    }
    return sendResult;
  }

  private SmsDto signJsonToDto(String sign) {
    String defaultSign = JSON.toJSONString(this.config.getDefalutCode());
    sign = StringUtils.isNotBlank(sign) ? sign : defaultSign;
    return (SmsDto)JSON.toJavaObject((JSON)JSON.parseObject(sign), SmsDto.class);
  }
}
