<template>
  <view>
    <!-- 使用Uniapp的loading组件 -->
    <view v-if="loading" class="hc-body-loading">
      <text>授权登录中...</text>
    </view>

    <!-- 错误页面 -->
    <view v-if="isErrorShow" class="error-page">
      <view :style="`background-image: url(${svg403});`" class="img"></view>
      <view class="content">
        <text class="title">403</text>
        <text class="desc">抱歉，token授权登录异常，请重新进入</text>
        <view class="actions">
          <!-- 使用Uniapp的button组件 -->
          <button class="uni-btn" type="primary" size="large" @click="toLoginTap">手动登录</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>

import { onMounted, ref } from 'vue'
import {useAppStore} from "@/store";
import  userApi from '@/httpApi/modules/user'
import { errorToast, getTopUrl } from '@/utils/tools'
import { useRoute, useRouter } from 'vue-router'
// import svg403 from '~src/assets/view/403.svg'
import { getObjVal, getObjValue, isNullES } from 'js-fast-way'
import { setUserAppInfo, setUserTenantInfo } from '@/store/user'
import { onLaunch, onShow } from '@dcloudio/uni-app';
import {setToken, setRefreshToken} from '@/httpApi/util/auth';
import {successToast} from "@/utils/tools";

// 监听应用启动事件
onLaunch((options) => {
    console.log(options,'options');

});
//初始变量
const router = useRouter()
const useRoutes = useRoute()
const store = useAppStore()

//先清理下缓存
store.clearStoreData()



const toUrl=ref("/pages/index/index")
//渲染完成
onMounted(() => {
      loading.value = true
    // http://质检的域名/#/auth-token?token=xxx&tid=xxx&pid=xxx&cid=xxx&layout=no&url=xxx
   console.log(useRoutes.query,'useRoutes.query');
    const { token, tid, pid, cid, layout, url } = getObjValue(useRoutes.query)
    if (!isNullES(token)) {
        isErrorShow.value = false
        toUrl.value = url ?? '/pages/index/index'
        //缓存数据
        setToken(token)
        store.setProjectId(pid)
        store.setContractId(cid)

        //处理授权登录
        setLoginByTokenData(token, tid)
    } else {
        loading.value = false
        isErrorShow.value = true
    }
})

//获取租户id
const getTenantIdApi = async () => {
    const { data } = await userApi.getTenantID(getTopUrl())
    const { id } = await setUserTenantInfo(getObjVal(data))
    return id
}

//设置租户信息
const setLoginByTokenData = async (token, tenant_id) => {
    const tenantIds = await getTenantIdApi()
    const tenantId = tenant_id ? tenant_id : tenantIds
    await loginByTokenApi({ token, tenantId })
}

//请求授权登录
const loginByTokenApi = async (form) => {
    console.log(form,'form');

    const { error, code, data } = await userApi.loginByToken(form)
    const res = getObjVal(data)
    if (!error && code === 200 && res) {
        await setUserAppInfo(res)
        successToast('授权成功');
        setTimeout(() => {
            loading.value = false
            isErrorShow.value = false
            uni.navigateTo({url:toUrl.value });

        }, 1500)
    } else {
        errorToast('授权登录失败')
        isErrorShow.value = true
        loading.value = false
    }
}

//跳转登陆
// const toLoginTap = () => {
//     router.push({ path: '/login-main' })
// }
// 定义响应式变量
const loading = ref(false); // 控制加载状态
const isErrorShow = ref(false); // 控制错误页面显示
const svg403 = ref('/static/403.svg'); // 403错误图片路径

// 跳转到登录页的方法
const toLoginTap = () => {
  uni.navigateTo({
    url: '/pages/login/login',
  });
};
</script>

<style scoped>
.hc-body-loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  font-size: 16px;
  color: #999;
}

.error-page {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  text-align: center;
}

.img {
  width: 200px;
  height: 200px;
  background-size: cover;
  background-position: center;
}

.content {
  margin-top: 20px;
}

.title {
  font-size: 32px;
  font-weight: bold;
  color: #333;
}

.desc {
  font-size: 16px;
  color: #666;
  margin-top: 10px;
}

.actions {
  margin-top: 20px;
}

.uni-btn {
  width: 100%;
}
</style>
