<template>
  <MessageBox
    ref="messageRef"
    title="授权登录"
    content="您的操作需要授权登录后才能继续，是否继续？"
    text-ok="继续"
    :hide-ok="true"
    :show-get-phone-number="true"
    :on-get-phone-number="handleGetPhoneNumber"
    :on-cancel="handleCancel"
  />
</template>
<script lang="ts" setup>
import { useAuthStore } from '@/store/modules/useAuthStore';
import { ref, watch } from 'vue';
import { useApi } from '@/hooks/useApi';
import { useGlobal } from '@/hooks/useGlobal';
import MessageBox from './MessageBox.vue';

const { toast } = useGlobal();
const authStore = useAuthStore();
const messageRef = ref<InstanceType<typeof MessageBox>>();

const result = ref<boolean | undefined>();

const handleCancel = () => {
  messageRef.value?.hideDialog();
  result.value = false;
};


const handleGetPhoneNumber = async(e: any) => {

  try {
    toast.value?.loading('授权中...');
    if (!e?.code) {
      throw new Error();
    }

    const loginRes = await uni.login();
    if (!loginRes?.code) {
      throw new Error();
    }

    console.log(loginRes);

    await useApi().userweappApi.registeruserweapp({
      loginCode: loginRes.code,
      phoneCode: e.code,
    });


    await login();
    result.value = true;
  } catch (error) {
    console.log(error);
    result.value = false;
  } finally {
    toast.value?.close();
  }
};


const login = async() => {
  try {
    toast.value?.loading('登录中...');
    const loginRes = await uni.login();
    if (!loginRes?.code) {
      throw new Error();
    }

    const res = await useApi().userweappApi.loginuserweapp({
      loginCode: loginRes.code,
    });

    console.log(res?.data?.data);
    if (!res?.data?.data) {
      throw new Error();
    }
    // 登录成功
    authStore.setUsername(res?.data?.data?.username || '');
    authStore.setToken(res?.data?.data?.token || '');
    authStore.setOpenid(res?.data?.data?.openid || '');
    authStore.setAvatar(res?.data?.data?.meta?.avatar || '');
    authStore.setName(res?.data?.data?.meta?.name || '');
    authStore.setId(res?.data?.data?.id || 0);
    authStore.setPhone(res?.data?.data?.meta?.phone || '');
    
  } catch (error) {
    authStore.$reset();
    throw error;
  } finally {
    toast.value?.close();
  }
};


const auth = () => new Promise((resolve, reject) => {
  console.log(authStore.token);
  console.log(authStore.username);
  result.value = undefined;
  console.log('auth');
  if (!authStore.token || !authStore.username) {
    watch(result, (newV) => {
      if (newV === true) {
        console.log('登录成功');
        resolve(null);
      } else if (newV === false) {
        toast.value?.error('登录失败');
        reject(new Error('登录失败'));
      }
    });
    // 先进行直接登录，如果报错再拉起手机号
    login()
      .then(() => {
        result.value = true;
      })
      .catch(() => {
        messageRef.value?.showDialog();
      });
  } else {
    // 存在token，则验证一下token，验证不通过再弹出授权
    useApi().userweappApi.veryfyTokenuserweapp().then((res: any) => {
      if (res?.data?.data?.name) {
        authStore.setName(res?.data?.data?.name);
      }
      if (res?.data?.data?.avatar) {
        authStore.setAvatar(res?.data?.data?.avatar);
      }
      if (res?.data?.data?.phone) {
        authStore.setPhone(res?.data?.data?.phone);
      }
      resolve(null);
    })
      .catch(() => {
        authStore.$reset();
        auth().then(() => resolve(null))
          .catch((error) => reject(error));
      });
  }
});


defineExpose({
  auth,
});

</script>
<style lang="scss" scoped>
</style>
