import * as dd from "dingtalk-jsapi";

const ding = {}; // 钉钉jsapi对象
let $loading = false; // 避免多个请求闪屏

import progress from "@/service/progress";

// loading 显示
ding.showLoading = function (message = "拼命加载中...") {
  if ($loading) return;
  $loading = true;
  dd.device.notification.showPreloader({
    showIcon: true,
    text: message,
  });
};

// loading 关闭
ding.hideLoading = function () {
  if (!$loading) return;
  dd.device.notification.hidePreloader();
  $loading = false;
};

// toast 提示: info 详见 https://ding-doc.dingtalk.com/doc#/dev/oo98ye/6pwsuy
ding.showMessageToast = function (info = {}) {
  if (!info.message) return;
  dd.device.notification.toast(info);
};

// 获取定位
ding.getLocation = function () {
  return new Promise((resolve, reject) => {
    dd.device.geolocation.get({
      targetAccuracy: 200,
      coordinate: 1,
      withReGeocode: true,
      useCache: true,
      onSuccess (result) {
        resolve(result);
      },
      onFail (err) {
        reject(err);
      },
    });
  });
};

// 根据chatId跳转到对应会话
ding.toConversation = function (chatId) {
  return new Promise((resolve, reject) => {
    dd.biz.chat.toConversation({
      corpId: conf.corpId,
      chatId,
      onSuccess: () => resolve(),
      onFail: (err) => reject(err),
    });
  });
};

// 图片预览: 支持缩放和左右切换
ding.previewImageScale = function (urls, index = 0) {
  if (!urls) return;
  dd.biz.previewImage({
    urls,
    current: urls[index],
  });
};

// 获取UUID
ding.getUUID = function () {
  return new Promise((resolve) => {
    dd.device.base.getUUID({
      onSuccess (data) {
        resolve(data);
      },
    });
  });
};

/** @exports 钉钉新开页面方法 */
ding.openNavigation = function (url, isReplace) {
  if (!url) return;
  // 区分环境, 兼容分享
  if (dd.env.platform === "notInDingTalk") {
    window.open(url, isReplace ? "_self" : "");
  } else {
    if (isReplace) {
      dd.biz.navigation.replace({ url });
    } else {
      dd.biz.util.openLink({ url });
    }
  }
};

/** @exports 设置右侧导航栏: [{ id: "1", text: "附 件", url: "http://alading-20210318.oss-cn-shanghai.aliyuncs.com/assets/nav-link.png",},] */
ding.settingNavigationMenu = function (menus = [], isClear, callback) {
  if (isClear) {
    menus = [
      {
        id: "999",
        text: " ",
      },
    ];
  }
  dd.biz.navigation.setMenu({
    items: menus,
    onSuccess (result) {
      callback && callback(result);
    },
  });
};

// 注册钉钉js接口鉴权 [H5无需配置, 但宜搭内需要配置鉴权, 才能获取到code]
ding.registerConfig = function () {

  if (dd.env.platform == "notInDingTalk") {
    progress.dialogConfirm("操作提示", "请在钉钉工作台打开!")
    return
  }

  /** // 页面环境：0提交(其它)，1查看，2编辑(审批)
    if (!mjs.env) {
  
      // 注册jsApi ticket
      const rsp = await mjs.request.xhr.doPost("https://mc.cloudpure.cn/api/hangshi/register", {}, {
        url: mjs.conf.ticketUrl,
        nonceStr: mjs.conf.nonceStr
      }, { noLoading: true });
      dd.config({
        ...rsp.data,
        type: 0,
        jsApiList: ["runtime.permission.requestAuthCode"]
      });
      // 钉钉免登逻辑
      const _this = this;
      mjs.ding.dd.ready(function () {
        mjs.ding.dd.runtime.permission.requestAuthCode({
          corpId: mjs.conf.corpId, // 企业id
          onSuccess: async function (info) {
            const res = await mjs.request.xhr.doPost("https://mc.cloudpure.cn/api/hangshi/user/code", {}, {
              code: info.code
            }, { noLoading: true });
            console.log("钉钉免登", res.data)
            _this.$('textField_ll3m8vz5').setValue(res.data.name)
            _this.$('textField_ll3m8vz6').setValue(res.data.userid)
          }
        });
      });
    } */

  dd.ready(function () {
    // dd.config({
    //   agentId,
    //   corpId,
    //   timeStamp,
    //   nonceStr,
    //   signature,
    //   type: 0,
    //   jsApiList: ["biz.chat.toConversation"], // 注意：不要带dd。
    // });
  })


};

// 注册配置异常抛出
dd.error(function (error) {
  window.alert(JSON.stringify(error));
});

ding.dd = dd;

export default ding;
