<script>
import cache from '@/utils/cache';
import config from '@/config/index';
import { mapState } from 'vuex';
// #ifdef MP-DINGTALK
import { onAuthAppBack, openAuthMiniApp } from 'dingtalk-design-libs/biz/openAuthMiniApp';
// #endif

export default {
  computed: {
    ...mapState(['authed','userInfo']),
  },
  onLaunch(options) {
    const systemInfo = uni.getSystemInfoSync();
    let origin = systemInfo?.environment === 'wxwork' ? 'QY_FREGHT_MA' : 'FREGHT_MA';
    // #ifdef MP-DINGTALK
    origin = 'DINGTALK_FREGHT_MA';
    // #endif
    // 设置小程序来源，企业微信小程序或微信小程序
    this.$store.commit('SET_ORIGIN', origin);
    this.$store.commit('SET_SCENE', options.scene);
    this.$u.api.dict.all().then(response => {
      cache.put('DICT', response.result);
      this.$store.commit('SET_DICT', response.result);
    });
    this.$u.api.district.all().then(response => {
      cache.put('DISTRICT', response.result);
      this.$store.commit('SET_DISTRICT', response.result);
    });
    if (!this.authed) {
      if (origin === 'QY_FREGHT_MA') {
        wx.qy.login({
          suiteId: config.suiteId,
          success: (res) => {
            if (res.code) {
              uni.$u.api.login.loginByCode({ code: res.code }).then((response) => {
                if (!response.result) return this.handleLogin();
                const result = response.result || {};
                this.$store.commit('SET_AUTHED', result.hasBind);
                this.$store.commit('SET_USER_INFO', result);
                this.getPermission();
                if (result.hasBind) {
                  uni.$u.api.user.detail().then(res => {
                    this.$store.commit('SET_FREGHT_INFO', res.result);
                  });
                }
              })
            }
          },
          fail: () => {
            this.handleLogin();
          }
        });
      } else {
        this.handleLogin();
      }
    }
    // 监听刷新权限
    uni.$on('refresh-permission', () =>{
      this.getPermission();
    });
    // 监听检测更新
    uni.$on('refresh-version', (params) =>{
      const { notifyType = 'toast' } = params || {};
      this.handleRefreshVersion(notifyType);
    });
    // 初始化检测更新
    uni.$emit('refresh-version', { notifyType: 'silent' });
  },
  onShow(options) {
    // #ifdef MP-DINGTALK
    // 监听钉钉统一授权小程序返回结果的方法
    onAuthAppBack(options, (data) => {
      const { status, result } = data || {};
      if (status === 'ok' && result && result.authCode) {
        uni.$u.api.login.dingtalk({ authCode: result.authCode, corpId: dd.corpId }).then(response => {
          const result = response.result || {};
          this.$store.commit('SET_AUTHED', result.hasBind);
          this.$store.commit('SET_USER_INFO', result);
          this.getPermission();
          if (result.hasBind) {
            uni.$u.api.user.detail().then(res => {
              this.$store.commit('SET_FREGHT_INFO', res.result);
            });
          }
        });
      }
      return data;
    });
    // #endif
  },
  methods: {
    // 检测更新
    handleRefreshVersion(notifyType) {
      const showToast = (options) => {
        if (notifyType === 'silent') return; // 静默
        wx.showToast(options);
      };
      if (wx.canIUse('getUpdateManager')) {
        const updateManager = wx.getUpdateManager();
        showToast({ title: '检测中，请稍后', icon: 'none', duration: 2000 });
        updateManager.onCheckForUpdate(ret => {
          // 请求完新版本信息的回调
          if (ret.hasUpdate) {
            updateManager.onUpdateReady(() => {
              wx.hideToast();
              wx.showModal({
                title: '更新提示',
                content: '新版本已经准备好，是否重启应用？',
                success(res) {
                  if (res.confirm) {
                    updateManager.applyUpdate();
                  }
                }
              });
            });
            updateManager.onUpdateFailed(() => {
              // 新版本下载失败
              showToast({ title: '网络状况不佳，稍后再试', icon: 'none', duration: 2000 });
            })
          } else {
            showToast({ title: '当前已是最新版本', icon: 'none', duration: 2000 });
          } 
        })
      } else {
        showToast({ title: `当前${wx.getSystemInfoSync()?.environment === 'wxwork' ? '企业' : ''}微信版本过低，请升级到最新版本后重试`, icon: 'none', duration: 3000 });
      }
    },
    // 查询权限
    getPermission() {
      return new Promise((resolve) => {
        uni.$u.api.user.getPermission({ systemCode: 'dispatch-helper-ma', userId: this.userInfo.userId }).then((response = {}) => {
          const { result = [] } = response;
          this.$store.commit('SET_PERMISSION', result);
          resolve(result);
        }).catch(() => {
          resolve([]);
        });
      });
    },
    handleLogin() {
      // #ifdef MP-WEIXIN
      uni.login({
        provider: 'weixin',
        success: response => {
          const { code } = response;
          if (code) {
            uni.$u.api.login.wechat({ code }).then(response => {
              const result = response.result || {};
              this.$store.commit('SET_AUTHED', result.hasBind);
              this.$store.commit('SET_USER_INFO', result);
              this.getPermission();
              if (result.hasBind) {
                uni.$u.api.user.detail().then(res => {
                  this.$store.commit('SET_FREGHT_INFO', res.result);
                });
              }
            });
          }
        }
      });
      // #endif
      // #ifdef MP-DINGTALK
      // 打开钉钉统一授权小程序
      openAuthMiniApp({
        path: 'pages/home/home',  //不要改,这里是小程序dingwlanwvdmrtjjwdmd下的一个页面地址
        panelHeight: 'percent50',
        extraData:{
          clientId: config.clientId, // 应用ID(唯一标识)
          rpcScope: 'Contact.User.Read',
          fieldScope: 'Contact.User.mobile',
          type:0,
          ext: JSON.stringify({}),
          from:''
        }
      });
      // #endif
    }
  }
}
</script>

<style lang="scss">
@import "@/uni_modules/uview-ui/index.scss";
@import '~styles/common.scss';
@import './iconfont/iconfont.css';
@import '~styles/common.scss';
</style>
