const system = require("../../../system");
const settings = require("../../../../config/settings")
const Core = require('@alicloud/pop-core');
const ServiceBase = require("../../sve.base");
class SmsinfoService extends ServiceBase {
  constructor() {
    super("common", ServiceBase.getDaoName(SmsinfoService));
    let aliSmsConfig = settings.aliSmsConfig();
    this.aliSmsConfigration = aliSmsConfig;
    this.client = new Core({
      accessKeyId: aliSmsConfig.accessKeyId,
      accessKeySecret: aliSmsConfig.accessKeySecret,
      endpoint: aliSmsConfig.endpoint,
      apiVersion: aliSmsConfig.apiVersion
    });
  }


  /**
   * 发送短信
   * @param {*} params 
   */
  async sendSms(params) {
    let key = this.trim(params.templateName);
    let loginTemplateConfig = this.aliSmsConfigration.template[key];
    if (!loginTemplateConfig) {
      return system.getResult(-1, `参数错误 模板不存在`);
    }
    if (!params.phoneNumbers) {
      return system.getResult(null, `参数错误 手机号不能为空`);
    }

    let data = {
      "RegionId": "cn-hangzhou",
      "PhoneNumbers": params.phoneNumbers,
      "TemplateCode": loginTemplateConfig.code,

      "SignName": this.aliSmsConfigration.signName
    }
    if (params.hasOwnProperty("code")) {
      data.TemplateParam = `{\"code\":\"${params.code}\"}`;
    }else if(params.hasOwnProperty("name")){
      data.TemplateParam = `{\"name\":\"${params.name}\"}`;
    }
    try {
      //创建记录
      let _smsInfo = await this.dao.create({
        regionId: data.RegionId,
        phoneNumbers: data.PhoneNumbers,
        templateCode: data.TemplateCode,
        templateParam: data.TemplateParam,
        signName: data.SignName
      });
      let res = await this.client.request('SendSms', data, {
        method: 'POST'
      });
      _smsInfo.result = JSON.stringify(res);
      if (res.Code == "OK") {
        _smsInfo.success = 1;
      } else {
        _smsInfo.success = 0;
      }
      await _smsInfo.save();
      return system.getResult(res);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 查询发送记录
   * @param {*} params 
   */
  async querySendDetails(params) {
    if (!params.phoneNumbers) {
      return system.getResult(null, `参数错误 手机号不能为空`);
    }
    if (!params.sendDate) {
      return system.getResult(null, `参数错误 日期不能为空`);
    }
    let data = {
      "RegionId": "cn-hangzhou",
      "PhoneNumbers": params.phoneNumbers,
      "SendDate": this.trim(params.sendDate),
      "PageSize": Number(this.trim(params.pageSize) || 10),
      "CurrentPage": Number(this.trim(params.currentPage) || 1),
    }
    try {
      let res = await this.client.request('QuerySendDetails', data, {
        method: 'POST'
      });
      return system.getResult(res);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 条件查询所有的记录
   * @param {*} params 
   */
  async querySmsInfos(params) {
    let where = {};
    if (params.regionId) {
      where.regionId = this.trim(params.regionId);
    }
    if (params.phoneNumbers) {
      where.phoneNumbers = this.trim(params.phoneNumbers);
    }
    if (params.templateCode) {
      where.templateCode = this.trim(params.templateCode);
    }
    if (params.templateParam) {
      where.templateParam = this.trim(params.templateParam);
    }
    if (params.signName) {
      where.signName = this.trim(params.signName);
    }
    if (params.hasOwnProperty("success")) {
      where.success = this.trim(params.success);
    }
    var currentPage = Number(params.currentPage || 1);
    var pageSize = Number(params.pageSize || 10);
    var orderby = [
      ["id", 'desc']
    ];

    var attributes = ["id", "regionId", "phoneNumbers", "templateCode", "templateParam", "signName", "result", "success", "created_at"];

    try {
      var page = await this.getPageList(currentPage, pageSize, where, orderby, attributes);
      return system.getResult(page);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  trim(o) {
    if (!o) {
      return "";
    }
    return o.toString().trim();
  }
}
module.exports = SmsinfoService;