/*
 * @Author: wufan
 * @Date: 2021-05-11 10:21:37
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-07-21 14:25:37
 * @Description: 企业微信api
 * @@Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 * 
 */

import Platform from '@/common/js/platform';
import User from '@/common/js/user';
import Service from '@/common/js/service';

export default class WechatApi {
  static async initConfig(params = { isAgentConfig: false, url: '' }) {
    if (Platform.isWorkWx()) {

      return new Promise(async (resolve, reject) => {
        Service.Hades('anon/hades/getWxCorpJSAPISignature', {
          storeId: User.getStoreId(),
          url: params.url,
        }).then((result) => {
          const res = result.result;
          this.config({
            beta: true, // 必须这么写，否则wx.invoke调用形式的jsapi会有问题
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: res.appId, // 必填，企业微信的corpID
            timestamp: res.timestamp, // 必填，生成签名的时间戳
            nonceStr: res.nonceStr, // 必填，生成签名的随机串
            signature: res.signature, // 必填，签名，见 附录-JS-SDK使用权限签名算法
            jsApiList: ['chooseImage', 'shareToExternalContact', 'selectExternalContact', 'selectEnterpriseContact'],
          }).then(() => {
            Service.Hades('anon/hades/getWxWorkJSAPISignature', {
              storeId: User.getStoreId(),
              url: params.url,
            }).then((result2) => {
              const res2 = result2.result;
              setTimeout(() => {
                this.agentConfig({
                  corpid: res2.corpid, // 必填，企业微信的corpid，必须与当前登录的企业一致
                  agentid: res2.agentid, // 必填，企业微信的应用id （e.g. 1000247）
                  timestamp: res2.timestamp, // 必填，生成签名的时间戳
                  nonceStr: res2.nonceStr, // 必填，生成签名的随机串
                  signature: res2.signature, // 必填，签名，见附录-JS-SDK使用权限签名算法
                  jsApiList: ['selectExternalContact', 'getCurExternalContact', 'getContext', 'shareToExternalContact', 'sendChatMessage', 'shareToExternalChat', 'startLiving', 'replayLiving'],
                  success: (res) => {
                    console.log(res, 'res-agentconfig');
                    console.info('window.WWOpenData', window.WWOpenData);
                    resolve(res);
                  },
                  fail: (err) => {
                    console.log(1213545344545)
                    console.log(err, 'err-agentconfig');
                    reject(err);
                  },
                });
              }, 500)

            });

          })


        });
      })

    } else {
      if (params.isAgentConfig) {
        console.log(32132132, 'cesgu')
        return new Promise(async (resolve, reject) => {
          Service.Hades('anon/hades/getWxWorkJSAPISignature', {
            storeId: User.getStoreId(),
            url: params.url,
          }).then((result2) => {
            const res2 = result2.result;
            this.agentConfig({
              corpid: res2.corpid, // 必填，企业微信的corpid，必须与当前登录的企业一致
              agentid: res2.agentid, // 必填，企业微信的应用id （e.g. 1000247）
              timestamp: res2.timestamp, // 必填，生成签名的时间戳
              nonceStr: res2.nonceStr, // 必填，生成签名的随机串
              signature: res2.signature, // 必填，签名，见附录-JS-SDK使用权限签名算法
              jsApiList: ['selectExternalContact', 'getCurExternalContact', 'getContext', 'shareToExternalContact', 'sendChatMessage', 'shareToExternalChat', 'startLiving', 'replayLiving'],
              success: (res) => {
                console.log(res, 'res-agentconfig');
                console.info('window.WWOpenData', window.WWOpenData);
                resolve(res);
              },
              fail: (err) => {
                console.log(1213545344545)
                console.log(err, 'err-agentconfig');
                reject(err);
              },
            });
          });
        });
      }
    }

  }

  static async config(config) {
    return new Promise((resolve, reject) => {
      console.info('wx.config', config);
      wx.config(config);
      wx.ready(resolve);
      wx.error(reject);
    }).then(
      () => {
        console.info('wx.ready');
      },
      (error) => {
        console.error('wx.error', error);
        throw error;
      }
    );
  }

  static async agentConfig(config) {
    wx.agentConfig({ ...config });
  }

  static getCurExternalContact() {
    return new Promise((resolve, reject) => {
      wx.ready(() => {
        wx.invoke('getCurExternalContact', {}, function (res) {
          if (res.err_msg == 'getCurExternalContact:ok') {
            resolve(res.userId); //返回当前外部联系人userId
          } else {
            reject(res.err_msg); //错误处理
          }
        });
      });
    });
  }

  static getContext() {
    return new Promise((resolve, reject) => {
      wx.ready(() => {
        wx.invoke('getContext', {}, function (res) {
          if (res.err_msg == 'getContext:ok') {
            resolve(res.entry); //返回进入H5页面的入口类型，目前有normal、contact_profile、single_chat_tools、group_chat_tools、chat_attachment
          } else {
            reject(res.err_msg); //错误处理
          }
        });
      });
    });
  }
  //进入直播间
  static enterLiveRoom(id) {
    return new Promise((resolve, reject) => {
      wx.ready(() => {
        wx.invoke('startLiving', {
          "livingId": id,
        }, function (res) {
          if (res.err_msg === "startLiving:ok") {
            resolve(true)
          } else {
            reject(res.err_msg); //错误处理
          }
        });
      });
    })
  }
  static replayLiving(id) {
    return new Promise((resolve, reject) => {
      wx.ready(() => {
        wx.invoke('replayLiving', {
          "livingId": id,
        }, function (res) {
          if (res.err_msg === "replayLiving:ok") {
            resolve(true)
          } else {
            let err = "进入回放失败"
            console.log(res.err_msg);
            if (res.err_msg === "replayLiving:fail_invalid living id") {
              err = "不合法的直播ID"
            } else if (res.err_msg === "replayLiving:fail_not allow to cross corp") {
              err = "不可跨企业使用直播ID"
            } else if (res.err_msg === "replayLiving:fail_not allow to cross app") {
              err = "不可跨应用使用直播ID"
            } else if (res.err_msg === "replayLiving:fail_living has no replay") {
              // err = "直播回放已失效或不存在"
              err = "该直播课未录制回放"
            } else if (res.err_msg === "replayLiving:fail_replay is beging creating") {
              err = "回放生成中，请耐心等待"
            } else if (res.err_msg === "replayLiving:fail_create replay failed") {
              err = "回放创建失败"
            } else if (res.err_msg === "replayLiving:fail_invalid parameter") {
              err = "参数不合法"
            }
            reject(err); //错误处理
          }
        });
      });
    })
  }
}
