import BaseStore from '@src/stores/base';
import { generateUUID } from '@src/services/Tools';
import { WechatH5AppId } from '../../Constant';

export default class CommonStore extends BaseStore {
  /**
   * 发送短信验证码
   * @param {*} area 区域码
   * @param {*} mobile 手机号
   */
  sendSms(area, mobile) {
    return this.apiPost('/common/sms/valid', { area, mobile });
  }

  /**
   * 上传至本地服务器
   * @param {*} file 图片文件
   */
  upload(file) {
    return this.apiForm('/common/upload/image', { file });
  }

  readyWechatBridge(callback) {
    if (typeof WeixinJSBridge === 'object' && typeof WeixinJSBridge.invoke === 'function') {
      callback();
    } else if (document.addEventListener) {
      document.addEventListener('WeixinJSBridgeReady', callback, false);
    } else if (document.attachEvent) {
      document.attachEvent('WeixinJSBridgeReady', callback);
      document.attachEvent('onWeixinJSBridgeReady', callback);
    }
  }

  readyWechat(url, list) {
    return this.apiGet('/common/wechat/ticket').then(ticket => {
      const time = new Date().getTime() / 1000;
      const nonce = generateUUID(6, 10);
      const p = `jsapi_ticket=${ticket}&noncestr=${nonce}&timestamp=${time}&url=${url.split('#')[0]}`;
      const a = list.map(row => row);
      a.push('checkJsApi');
      wx.config({
        debug: false, // 是否打开调试模式,调用的api会被alert出来,在pc端也能看到log信息
        appid: WechatH5AppId, // 必填,微信公众号的唯一标识
        timestamp: time, // 必填,生成签名的时间戳
        nonceStr: nonce, // 必填,生成签名的随机串
        signature: sha1(p), // 必填,用于验证的签名
        jsApiList: a, // 必填,需要使用到的JS接口列表
      });
      return new Promise((resolve, reject) => {
        wx.ready(() => {
          resolve(wx);
        });
        wx.error((err) => {
          reject(err);
        });
      });
    });
  }
}

export const Common = new CommonStore({ key: 'common' });