<template>
  <CommonTopBanner title="点亮村社">
    <ProvideVar :vars="{
      FieldBackgroundColor: 'transparent',
    }">
      <FlexCol :gap="20" :padding="30">
        <!--注册-->
        <FlexCol v-if="step === 'register'" :gap="20">
          <BoxMid :padding="[45,35]">
            <FlexCol center :gap="20">
              <Icon name="smile-filling" :size="80" />
              <Text 
                text="感谢您为本村做出贡献，点亮村庄！不过在这之前您需要注册基本信息成为志愿者，这可以帮助您更好的为村做出贡献，领取奖励等。请完善以下信息" 
                textAlign="center" 
                fontConfig="contentSpeicalText" 
              />
            </FlexCol>
          </BoxMid>
          <BoxMid :padding="10">
            <DynamicForm
              ref="registerFormRef"
              :model="registerFormModel"
              :options="registerFormDefine"
            />
          </BoxMid>
          <Height :height="20" />
          <PrimaryButton text="提交" @click="registerSubmit" :loading="registerFormLoading" />
        </FlexCol>
        <!--认领-->
        <FlexCol v-else-if="step === 'add'" :gap="20">
          <BoxMid :padding="[45,35]">
            <FlexCol center :gap="20">
              <Icon name="smile-filling" :size="80" />
              <Text text="您已经是志愿者，请完善以下信息认领当前村社" textAlign="center" fontConfig="contentSpeicalText" />
            </FlexCol>
          </BoxMid>
          <BoxMid :padding="10">
            <DynamicForm
              ref="addFormRef"
              :model="addFormModel"
              :options="addFormDefine"
            />
          </BoxMid>
          <Height :height="20" />
          <PrimaryButton block text="提交" @click="addSubmit" :loading="addFormLoading" />
        </FlexCol>
        <!--注册完成-->
        <Result 
          v-else-if="step === 'finished'" 
          status="success"
          :title="finishedMode === 'claim' ? '认领申请已提交' : '注册志愿者成功'"
          :description="finishedMode === 'claim'
            ? '请等待管理员审核认领申请，审核通过后即可采编该村社文化资源'
            : '请等待管理员审核，在此期间，可以在社区中先逛逛，学习如何采编村社文化资源信息吧'"
        >
          <Height :size="20" />
          <PrimaryButton block text="进入首页" @click="back()" />
        </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 -->
          <PrimaryButton block text="微信登录" @click="loginWechat" />
          <Height :size="20" />
          <!-- #endif -->
          <!-- #ifndef MP-WEIXIN -->
          <Result status="warning" title="提示" desc="当前环境不支持微信登录" />
          <!-- #endif -->

        </FlexCol>
      </FlexCol>
    </ProvideVar>
  </CommonTopBanner>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useAppInit } from '@/common/composeabe/AppInit';
import { useAuthStore } from '@/store/auth';
import { useUserTools } from '@/common/composeabe/UserTools';
import { useLoadQuerys } from '@/components/composeabe/LoadQuerys';
import { UserApi } from '@/api/auth/UserApi';
import { waitTimeOut } from '@imengyu/imengyu-utils';
import { fillClaimFromVolunteer, getClaimVillageForm } from './form/claim';
import { getVolunteerForm } from './form/volunteer';
import { back } from '@/components/utils/PageAction';
import { closeToast, toast } from '@/components/dialog/CommonRoot';
import { showError } from '@/common/composeabe/ErrorDisplay';
import type { IDynamicFormOptions, IDynamicFormRef } from '@/components/dynamic';
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 Alert from '@/components/feedback/Alert.vue';
import VillageApi, { VillageClaimInfo, VolunteerInfo } from '@/api/inhert/VillageApi';
import CommonTopBanner from '@/common/components/CommonTopBanner.vue';
import BackgroundBox from '@/components/display/block/BackgroundBox.vue';
import PrimaryButton from '@/common/components/PrimaryButton.vue';
import ProvideVar from '@/components/theme/ProvideVar.vue';
import BoxMid from '@/common/components/box/BoxMid.vue';

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

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.type = 'volunteer';
  registerFormModel.value.residentStatus = 1;
  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);
    await suscribePassMessage();
    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);
    await suscribePassMessage();
    toast({ content: '提交成功' });
    finishedMode.value = 'claim';
    step.value = 'finished';
  } catch (e) {
    showError(e);
  } finally {
    addFormLoading.value = false;
  }
}

async function suscribePassMessage() {
  const TEMPLATE_ID = '6CrLGzIl1yUxATluKrzhpG246pMrpwiPLZsF-5CKG1k';
  return new Promise<boolean>((resolve, reject) => {
    uni.requestSubscribeMessage({
      tmplIds: [TEMPLATE_ID],
      success(res) {
        if ((res as any)[TEMPLATE_ID] === 'accept')
          resolve(true);
        else
          resolve(false);
      },
      fail(err) {
        console.error('[suscribePassMessage] fail', err);
        reject(err);
      }
    });
  });
}
</script>
