<template>
  <CommonRoot>
    <FlexCol :gap="20" :padding="30">
      <!--注册-->
      <FlexCol v-if="step === 'register'">
        <DynamicForm
          ref="registerFormRef"
          :model="registerFormModel"
          :options="registerFormDefine"
        />
        <Height :height="20" />
        <Button block type="primary" @click="registerSubmit" :loading="registerFormLoading">提交</Button>
      </FlexCol>
      <!--认领-->
      <FlexCol v-else-if="step === 'add'">
        <Alert 
          type="info"
          message="您已经是志愿者，请填写以下信息，认领当前村社"
        />
        <DynamicForm
          ref="addFormRef"
          :model="addFormModel"
          :options="addFormDefine"
        />
        <Height :height="20" />
        <Button block type="primary" @click="addSubmit" :loading="addFormLoading">提交</Button>
      </FlexCol>
      <!--注册完成-->
      <Result 
        v-else-if="step === 'finished'" 
        status="success"
        :title="finishedMode === 'claim' ? '认领申请已提交' : '注册志愿者成功'"
        :description="finishedMode === 'claim'
          ? '请等待管理员审核认领申请，审核通过后即可采编该村社文化资源'
          : '请等待管理员审核，在此期间，可以在社区中先逛逛，学习如何采编村社文化资源信息吧'"
      >
        <Height :size="20" />
        <Button type="primary" @click="back()">进入首页</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 { back } from '@/components/utils/PageAction';
import { closeToast, toast } from '@/components/dialog/CommonRoot';
import { showError } from '@/common/composeabe/ErrorDisplay';
import { useLoadQuerys } from '@/components/composeabe/LoadQuerys';
import { onMounted, ref } from 'vue';
import VillageApi, { VillageClaimInfo, VolunteerInfo } from '@/api/inhert/VillageApi';
import type { IDynamicFormOptions, IDynamicFormRef } from '@/components/dynamic';
import { waitTimeOut } from '@imengyu/imengyu-utils';
import { fillClaimFromVolunteer, getClaimVillageForm } from './form/claim';
import { getVolunteerForm } from './form/volunteer';
import Alert from '@/components/feedback/Alert.vue';
import { useUserTools } from '@/common/composeabe/UserTools';

/**
 * 点亮村社页面
 */

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

const { querys } = useLoadQuerys({ 
  villageId: 0,  
  regionId: 0,
  unit: '',
});
const step = ref<'register' |'add'|'finished'|'error'>('register');
const finishedMode = ref<'register' | 'claim'>('register');

onMounted(async () => {
  if (!querys.value.villageId) {
    step.value = 'error';
    return;
  }

  //如果已登录，则尝试获取志愿者信息，有注册志愿者，则显示认领当前村社表单
  if (authStore.isLogged) {
    try {
      const volunteerInfo = await VillageApi.getVolunteerInfo();
      if (volunteerInfo) {
        step.value = 'add';
        addFormDefine.value = getClaimVillageForm({ formRef: addFormRef });
        const model = new VillageClaimInfo();
        model.villageId = querys.value.villageId;
        fillClaimFromVolunteer(model, volunteerInfo);
        addFormModel.value = model;
        return;
      }
    } catch {
    }
  }


  await waitTimeOut(1000);
  registerFormDefine.value = getVolunteerForm({
    canSetCatalog: false,
    villageId: querys.value.villageId,
    onlyPassword: false,
    isNew: ref(true),
    formRef: registerFormRef,
  });
  registerFormModel.value.regionId = querys.value.regionId;
  registerFormModel.value.unit = querys.value.unit;
});

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: '登录成功',
    });
    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);
    toast({ content: '注册成功' });
    finishedMode.value = 'register';
    step.value = 'finished';
  } catch (e) {
    showError(e);
  } finally {
    registerFormLoading.value = false;
  }
  await init();
}

const addFormLoading = ref(false);
const addFormRef = ref<IDynamicFormRef>();
const addFormModel = ref<VillageClaimInfo>(new VillageClaimInfo());
const addFormDefine = ref<IDynamicFormOptions>();

async function addSubmit() {
  if (!addFormRef.value || !addFormModel.value)
    return;
  try {
    await addFormRef.value.validate();
  } catch (e) {
    toast({ content: '有必填项未填写，请检查' });
    return;
  }

  try {
    addFormLoading.value = true;
    addFormModel.value.villageId = querys.value.villageId;
    await VillageApi.claimVallage(addFormModel.value as VillageClaimInfo);
    toast({ content: '提交成功' });
    finishedMode.value = 'claim';
    step.value = 'finished';
  } catch (e) {
    showError(e);
  } finally {
    addFormLoading.value = false;
  }
}
</script>
