<template>
  <CommonRoot>
    <FlexCol :gap="20" :padding="30">
      <!--完成-->
      <Result 
        v-if="step === 'already'" 
        status="success"
        title="您已经是志愿者"
        description="赶快去采编村社文化资源信息吧"
      >
        <Height :size="20" />
        <Button type="primary" @click="redirectTo('/pages/index')">返回首页</Button>
      </Result>
      <!--注册-->
      <FlexCol v-else-if="step === 'register'">
        <DynamicForm
          ref="registerFormRef"
          :model="registerFormModel"
          :options="registerFormDefine"
        />
        <Height :height="20" />
        <Button block type="primary" @click="registerSubmit" :loading="registerFormLoading">提交</Button>
      </FlexCol>
      <!--注册完成-->
      <Result 
        v-else-if="step === 'finished'" 
        status="success"
        title="注册志愿者成功"
        description="请等待管理员审核，在此期间，可以在社区中先逛逛，学习如何采编村社文化资源信息吧"
      >
        <Height :size="20" />
        <Button type="primary" @click="redirectTo('/pages/index')">进入首页</Button>
      </Result>
      <!--错误-->
      <Result 
        v-else-if="step === 'error'" 
        status="error"
        title="分享链接参数有误"
        description="请联系管理员，或稍后重试"
      />
      <!--登录-->
      <FlexCol v-else center :height="400">
        
        <Icon icon="smile-filling" color="primary" :size="156" />
        <Height :height="20" />
        <Text :fontSize="26" color="primary" text="欢迎注册，加入志愿者队伍" />
        <Height :size="40" />

        <!-- #ifdef MP-WEIXIN -->
        <Button type="primary" block text="微信登录" @click="loginWechat" />
        <Height :size="20" />
        <!-- #endif -->
        <!-- #ifndef MP-WEIXIN -->
        <Result status="warning" title="提示" desc="当前环境不支持微信登录" />
        <!-- #endif -->

      </FlexCol>
    </FlexCol>
  </CommonRoot>
</template>

<script setup lang="ts">
import Button from '@/components/basic/Button.vue';
import Result from '@/components/feedback/Result.vue';
import FlexCol from '@/components/layout/FlexCol.vue';
import Height from '@/components/layout/space/Height.vue';
import Icon from '@/components/basic/Icon.vue';
import Text from '@/components/basic/Text.vue';
import CommonRoot from '@/components/dialog/CommonRoot.vue';
import DynamicForm from '@/components/dynamic/DynamicForm.vue';
import { useAppInit } from '@/common/composeabe/AppInit';
import { UserApi } from '@/api/auth/UserApi';
import { useAuthStore } from '@/store/auth';
import { redirectTo } from '@/components/utils/PageAction';
import { closeToast, toast } from '@/components/dialog/CommonRoot';
import { showError } from '@/common/composeabe/ErrorDisplay';
import { useLoadQuerys } from '@/common/composeabe/LoadQuerys';
import { onMounted, ref } from 'vue';
import { getVolunteerForm } from '../admin/data/volunteer';
import VillageApi, { VolunteerInfo } from '@/api/inhert/VillageApi';
import type { IDynamicFormOptions, IDynamicFormRef } from '@/components/dynamic';

/**
 * 分享注册页面
 * 
 * 用户从管理员分享链接进入，需要注册为志愿者
 * 0. 如果已经登录，且有志愿者信息，直接跳转已经注册页, 否则进入注册流程
 * 1. 登录微信, 登录成功后, 如果有志愿者信息, 直接跳转成功页, 否则进入注册流程
 * 2. 注册流程中, 提交成功后, 跳转成功页
 */

const authStore = useAuthStore();
const { init } = useAppInit();

const { querys } = useLoadQuerys({ 
  villageId: 0,  
});
const step = ref<''|'register'|'finished'|'already'|'error'>('');

onMounted(async () => {
  if (!querys.value.villageId) {
    step.value = 'error';
    return;
  }
  registerFormDefine.value = getVolunteerForm({
    canSetCatalog: false,
    villageId: querys.value.villageId,
    onlyPassword: false,
    isNew: ref(true),
    formRef: registerFormRef,
  });
  if (authStore.isLogged) {
    try {
      await VillageApi.getVolunteerInfo();
      step.value = 'already';
    } catch {
      step.value = 'register';
    }
  }
});

async function loginWechat() {
  toast({
    type: 'loading',  
    content: '登录中...',
  })

  try {
    const res = await Promise.all([
      uni.login({ provider: 'weixin' }),
      uni.getUserProfile({ desc: '用于完善会员资料' }),
    ]);
    await authStore.loginWechart(res[0].code, res[1]);
    toast({
      type: 'success',  
      content: '登录成功',
    });

    try {
      await VillageApi.getVolunteerInfo();
      //有志愿者信息，表示是志愿者，直接跳转
      step.value = 'already';
      return;
    } catch {
      step.value = 'register';
    }
  } catch(e) {
    showError(e);
  } finally {
    closeToast();
  }
}

const registerFormLoading = ref(false);
const registerFormRef = ref<IDynamicFormRef>();
const registerFormModel = ref<VolunteerInfo>(new VolunteerInfo());
const registerFormDefine = ref<IDynamicFormOptions>();

async function registerSubmit() {
  if (!registerFormRef.value || !registerFormModel.value)
    return;
  try {
    await registerFormRef.value.validate();
  } catch (e) {
    toast({ content: '有必填项未填写，请检查' });
    return;
  }
  try {
    registerFormLoading.value = true;
    registerFormModel.value!.villageId = querys.value.villageId;
    const loginRes = await VillageApi.shareAddVolunteer(registerFormModel.value as VolunteerInfo);
    await authStore.loginResultHandle(loginRes, UserApi.LOGIN_TYPE_USER);
    await init();
    toast({ content: '注册成功' });
    step.value = 'finished';
  } catch (e) {
    showError(e);
  } finally {
    registerFormLoading.value = false;
  }
}
</script>
