<script>
  import config from './config'
  import { getAccessToken } from '@/utils/auth'
  import { authLogin } from "@/api/login";
  import { setToken, setTenantId } from '@/utils/auth'
  import { openAuth } from "dingtalk-design-libs/biz/openAuth";
  import * as dd from "dingtalk-jsapi";
  function getQueryString() {
     let url = window.location.href; //获取url中"?"符后的字串
	 console.log(url)
      if (url.indexOf("?") != -1) { 
         let str = url.substr(1); 
         let strs = str.split("=");
		 let index = strs[1].indexOf("#")
		 let corpId = strs[1].substring(0, index);
		 console.log(corpId)
         return corpId;          
      }
  };
  
  export default {
    onLaunch: function() {
      this.initApp()
    },
    methods: {
      // 初始化应用
      initApp() {
        // 初始化应用配置
        this.initConfig()
        // 检查用户登录状态
        //#ifdef H5
        this.checkLogin()
        //#endif
      },
      initConfig() {
        this.globalData.config = config
      },
      checkLogin() {
		  let that = this;
		  debugger
		let corpId = getQueryString();
		console.log(corpId);
        if (!getAccessToken()) {
			if (dd.env.platform !== "notInDingTalk") {
				debugger
			  return new Promise((resolve, reject) => {
			    dd.ready(function () {
			      // 唤起授权--统一授权套件SDK
			      openAuth({
			        clientId: "suite7tssbigaaqsejgth", // 应用ID(唯一标识)
			        corpId: corpId, // 当前组织的corpId
			        rpcScope: "Contact.User.Read", //通讯录
			        fieldScope: "Contact.User.mobile", //手机号
			        type: 0, // 0 标识授权个人信息；1 标识授权组织信息
			      }).then((res) => {
			        // 处理返回数据
			        console.log("统一授权套件SDK==res=", res);
					console.log("corpId", corpId);
			        authLogin({ code: res.result.authCode, corpId: corpId })
			          .then((res) => {
			            console.log("===登录授权=", res);
			            setToken(res.data);
			            setTenantId(res.msg)
						// 设置用户信息
						that.$store.dispatch('GetInfo').then(res => {
							that.$tab.reLaunch('/pages/index')
						})
			            resolve();
			          })
			          .catch((err) => {
			            reject();
			          });
			      });
			    });
			  });
			}else{
				this.$tab.reLaunch('/pages/login')
			}
        }
      }
    }
  }
</script>

<style lang="scss">
  @import '@/static/scss/index.scss'
</style>
