<template>
  <CommonRoot>
    <FlexCol :gap="20" :padding="30">
      <!--完成-->
      <Result 
        v-if="step === 'already'" 
        status="success"
        title="您已经是志愿者"
        desc="赶快去采编村社文化资源信息吧"
      >
        <Height :size="20" />
        <Button type="primary" @click="navTo('/pages/index')">返回首页</Button>
      </Result>
      <!--注册-->
      <FlexCol v-else-if="step === 'register'" center>
        <FlexCol :padding="30">
          <DynamicForm
            ref="registerFormRef"
            :model="registerFormModel"
            :options="registerFormDefine"
            :formGlobalParams="querys"
          />
          <Height :height="20" />
          <Button type="primary" @click="registerSubmit" :loading="registerFormLoading">提交</Button>
        </FlexCol>
      </FlexCol>
      <!--注册完成-->
      <Result 
        v-if="step === 'finished'" 
        status="success"
        title="注册志愿者成功"
        desc="请等待管理员审核，在此期间，可以在社区中先逛逛，学习如何采编村社文化资源信息吧"
      >
        <Height :size="20" />
        <Button type="primary" @click="navTo('/pages/index')">进入首页</Button>
      </Result>
      <!--登录-->
      <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 { navTo } from '@/components/utils/PageAction';
import { useAuthStore } from '@/store/auth';
import { useAliOssUploadCo } from '@/common/components/upload/AliOssUploadCo';
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 VillageApi, { type VolunteerInfo } from '@/api/inhert/VillageApi';
import CommonContent from '@/api/CommonContent';
import type { IDynamicFormItemCallbackAdditionalProps, IDynamicFormOptions, IDynamicFormRef } from '@/components/dynamic';
import type { FieldProps } from '@/components/form/Field.vue';
import type { RuleItem } from 'async-validator';
import type { PickerIdFieldProps } from '@/components/dynamic/wrappers/PickerIdField';
import type { RadioValueProps } from '@/components/dynamic/wrappers/RadioValue';
import type { UploaderFieldProps } from '@/components/form/UploaderField.vue';
import type { FormProps } from '@/components/form/Form.vue';
import { useAppInit } from '@/common/composeabe/AppInit';
import { UserApi } from '@/api/auth/UserApi';

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

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

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

onMounted(() => {
  if (authStore.isLogged) {
    if (authStore.userInfo?.villageVolunteer)
      step.value = 'already';
    else 
      step.value = 'register';
  }
});

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

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

        if (res.villageVolunteer) {
          //有志愿者信息，表示是志愿者，直接跳转
          step.value = 'already';
          return;
        }
        
        step.value = 'register';
      }).catch(showError);
    })
    .catch(showError)
    .finally(() => closeToast());
}

const registerFormLoading = ref(false);
const registerFormRef = ref<IDynamicFormRef>();
const registerFormModel = ref<VolunteerInfo>();
const registerFormDefine : IDynamicFormOptions = {
  formItems: [
    {
      name: 'groupBase',
      type: 'flat-simple',
      children: [
        { 
          label: '登录账号', name: 'username', type: 'text',
          additionalProps: { 
            placeholder: '请输入用户名',
          },
          rules: [{ required: true, message: '请输入用户名' }],
        },
        {
          label: '密码',
          name: 'password',
          type: 'text',
          additionalProps: { 
            placeholder: '请输入密码',
            type: 'password',
          } as FieldProps,
          rules: [{ required: true, message: '请输入密码' }],
        },
        {
          label: '确认密码',
          name: 'passwordRepeat',
          type: 'text',
          additionalProps: { 
            placeholder: '请再输入一次密码',
            type: 'password',
          } as FieldProps,
          rules: [
            { required: true, message: '请再输入一次密码' },
            {
              async validator(rule, value) {
                if (value != registerFormRef.value?.getValueByPath('password'))
                  throw '两次输入密码不一致，请检查';
              },
            }
          ] as RuleItem[],
        },
      ]
    },
    {
      name: 'groupExtra',
      type: 'flat-simple',
      childrenColProps: {
        span: 24,
      },
      children: [
        {
          label: '真实名称', name: 'name', type: 'text',
          additionalProps: { placeholder: '请输入真实名称' },
          rules: [{ required: true, message: '请输入真实名称' }],
        },
        {
          label: '手机号', name: 'mobile', type: 'text',
          additionalProps: { placeholder: '请输入手机号' },
          rules: [{ required: true, message: '请输入手机号' }],
        },
        { 
          label: '区域', name: 'regionId', type: 'select-id',
          additionalProps: {
            placeholder: '请选择区域',
            loadData: async () => (await CommonContent.getCategoryList(1)).map(p => ({ text: p.title, value: p.id, raw: p }))
          } as IDynamicFormItemCallbackAdditionalProps<PickerIdFieldProps>,
          rules: [{ required: true, message: '请选择区域' }],
        },
        {
          label: '性别', name: 'sex', type: 'radio-value',
          additionalProps: {
            options: [
              { text: '男', value: 1 },
              { text: '女', value: 2 }
            ]
          } as RadioValueProps,
        },
        { 
          label: '头像', name: 'image', type: 'uploader',
          additionalProps: {
            single: true,
            maxFileSize: 1024 * 1024 * 10,
            upload: useAliOssUploadCo('xiangyuan/volunteer/images')
          } as UploaderFieldProps,
        },
        { label: '地址', name: 'address', type: 'text', additionalProps: { placeholder: '请输入地址' } },
        { 
          label: '介绍', 
          name: 'intro', 
          type: 'textarea', 
          additionalProps: { 
            placeholder: '请输入介绍',
            showWordLimit: true,
            maxLength: 200,
          } as FieldProps,
        },
        { 
          label: '村落认领说明', name: 'claimReason', type: 'text', 
          additionalProps: { placeholder: '请输入村落认领说明' } ,
        },
      ]
    },
  ],
  formAdditionaProps: {
    labelWidth: '160rpx',
    labelAlign: 'right',
    innerStyle: {
      radius: '10rpx',
    },
  } as Omit<FormProps, 'model'>,
}

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!);
    await authStore.loginResultHandle(loginRes, UserApi.LOGIN_TYPE_USER);
    await init();
    toast({ content: '注册成功' });
    step.value = 'finished';
  } catch (e) {
    showError(e);
  } finally {
    registerFormLoading.value = false;
  }
}
</script>
