<template>
  <CommonDialog v-model:show="show" title="加入村社" :showDivider="false" :showCloseButton="false">
    <FlexCol gap="gap.lg" padding="padding.md" width="600rpx">
      
      <template v-if="step === 'chooseType'">
        <FlexCol gap="gap.md">
          <Text text="加入村社后，您即可为村社做贡献。请完善身份信息，解锁更多村社专属功能" fontConfig="contentSpeicalText" />
          <Height :height="10" />

          <BackgroundBox 
            v-for="(item, k) in typeChoices"
            :key="k"
            backgroundImage="https://xy.wenlvti.net/app_static/images/village/BoxMid.png"
            :backgroundCutBorder="32"
            :backgroundCutBorderSize="36"
            :padding="24"
            direction="row"
          >
            <Touchable direction="row" gap="gap.md"center @click="handleChooseType(item.value)">
              <Image :src="item.image" :radius="20" width="100" height="100" mode="aspectFill" />
              <Width :width="20" />
              <Text text="我是" fontConfig="lightImportantTitle" />
              <Text :text="item.label" fontConfig="lightGoldTitle" />
            </Touchable>
          </BackgroundBox>
        </FlexCol>
      </template>
      <template v-else-if="step === 'chooseIdentity'">
        <FlexCol gap="gap.md">
          <Text textAlign="center" text="请选择你的村民身份" fontConfig="contentSpeicalText" />
          <Height :height="10" />

          <BackgroundBox 
            v-for="(item, k) in identityChoices"
            :key="k"
            backgroundImage="https://xy.wenlvti.net/app_static/images/village/BoxMid.png"
            :backgroundCutBorder="32"
            :backgroundCutBorderSize="36"
            :padding="24"
            direction="row"
          >
            <Touchable direction="row" gap="gap.md"center @click="handleChooseIdentity(item.value)">
              <Image :src="item.image" :radius="20" width="100" height="100" mode="aspectFill" />
              <Width :width="20" />
              <Text :text="item.label" fontConfig="lightGoldTitle" />
            </Touchable>
          </BackgroundBox>
        </FlexCol>
      </template>
      <template v-else-if="step === 'form'">
        <Text textAlign="center" text="请完善身份信息，解锁更多村社专属功能" fontConfig="contentSpeicalText" />
        <Height :height="10" />
        
        <ProvideVar :vars="{
          FieldBackgroundColor: 'transparent',
        }">
          <BackgroundBox
            backgroundImage="https://xy.wenlvti.net/app_static/images/village/BoxMid.png"
            :backgroundCutBorder="32"
            :backgroundCutBorderSize="36"
            :padding="24"
          >
            <DynamicForm
              ref="addFormRef"
              :model="addFormModel"
              :options="addFormDefine"
            />
          </BackgroundBox>
        </ProvideVar>
        <Height :height="20" />
        <FlexRow justify="space-around" gap="gap.md">
          <FrameButton text="返回" @click="step = 'chooseType'" width="220rpx" />
          <FrameButton primary text="提交" @click="addSubmit" :loading="addFormLoading" width="220rpx" />
        </FlexRow>
      </template>
      <template v-else-if="step === 'finished'">
        <Result
          status="success"
          title="提交成功"
          description="等待管理员审核，通过后即可为村社做贡献，您可以先逛逛学习吧"
        />
        <FlexRow justify="space-around" gap="gap.md">
          <FrameButton primary text="完成" @click="show = false" width="220rpx" />
        </FlexRow>
      </template>
    </FlexCol>
  </CommonDialog>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { toast } from '@/components/dialog/CommonRoot';
import { showError } from '@/common/composeabe/ErrorDisplay';
import VillageApi, { VillageClaimInfo } from '@/api/inhert/VillageApi';
import CommonDialog from '@/common/components/CommonDialog.vue';
import FrameButton from '@/common/components/FrameButton.vue';
import Image from '@/components/basic/Image.vue';
import Text from '@/components/basic/Text.vue';
import DynamicForm from '@/components/dynamic/DynamicForm.vue';
import FlexCol from '@/components/layout/FlexCol.vue';
import FlexRow from '@/components/layout/FlexRow.vue';
import Height from '@/components/layout/space/Height.vue';
import BackgroundBox from '@/components/display/block/BackgroundBox.vue';
import Touchable from '@/components/feedback/Touchable.vue';
import type { RadioValueProps } from '@/components/dynamic/wrappers/RadioValue';
import type { RuleItem } from 'async-validator';
import type { FieldProps } from '@/components/form/Field.vue';
import type { IDynamicFormOptions, IDynamicFormRef } from '@/components/dynamic';
import Result from '@/components/feedback/Result.vue';
import Width from '@/components/layout/space/Width.vue';
import ProvideVar from '@/components/theme/ProvideVar.vue';

const show = ref(false);
const props = defineProps<{
  villageId: number;
}>();
const emit = defineEmits(['apply']);

const step = ref('chooseType');

const typeChoices = ref([
  {
    label: '志愿者',
    value: 'volunteer',
    image: 'https://xy.wenlvti.net/app_static/images/home/volunteer/IconTypeExternal.png',
  },
  {
    label: '管理人员',
    value: 'staff',
    image: 'https://xy.wenlvti.net/app_static/images/home/volunteer/IconTypeLocal.png',
  },
  {
    label: '村民',
    value: 'villager',
    image: 'https://xy.wenlvti.net/app_static/images/home/volunteer/IconTypeWork.png',
  },
]);

function handleChooseType(type: string) {
  step.value = 'chooseIdentity';
  addFormModel.value.type = type;
}

const identityChoices = ref([
  {
    label: '在村劳作',
    value: 1,
    image: 'https://xy.wenlvti.net/app_static/images/home/volunteer/IconTypeWork.png',
  },
  {
    label: '社区居民',
    value: 2,
    image: 'https://xy.wenlvti.net/app_static/images/home/volunteer/IconTypeLocal.png',
  },
  {
    label: '在外游子',
    value: 3,
    image: 'https://xy.wenlvti.net/app_static/images/home/volunteer/IconTypeOut.png',
  },
  {
    label: '退休人员',
    value: 4,
    image: 'https://xy.wenlvti.net/app_static/images/home/volunteer/IconTypeOld.png',
  },
]);

function handleChooseIdentity(identity: number) {
  step.value = 'form';
  addFormModel.value.identity = identity;
}

const addFormLoading = ref(false);
const addFormRef = ref<IDynamicFormRef>();
const addFormModel = ref<VillageClaimInfo>(new VillageClaimInfo());
const addFormDefine : IDynamicFormOptions = {
  formAdditionaProps: {},
  formItems: [
    {
      label: '真实姓名',
      name: 'name',
      type: 'text',
      additionalProps: { placeholder: '请输入真实姓名' },
      rules: [{ required: true, message: '请输入真实姓名' }],
    },
    {
      label: '联系方式',
      name: 'mobile',
      type: 'text',
      additionalProps: { placeholder: '请输入手机号' },
      rules: [{ required: true, message: '请输入联系方式' }],
    },
    {
      label: '性别',
      name: 'sex',
      type: 'radio-value',
      defaultValue: 3,
      additionalProps: {
        options: [
          { text: '男', value: 1 },
          { text: '女', value: 2 },
          { text: '未知', value: 3 },
        ],
      } as RadioValueProps,
    },
    {
      label: '居住地址',
      name: 'address',
      type: 'text',
      additionalProps: { placeholder: '请输入居住地址（选填）' },
    },
    {
      label: '工作单位',
      name: 'unit',
      type: 'text',
      additionalProps: { placeholder: '请输入工作单位（选填）' },
      show: { callback: () => addFormModel.value.type === 'staff' },
      rules: [{
        required: true,
        message: '请输入工作单位',
      }] as RuleItem[],
    },
    {
      label: '职位',
      name: 'job',
      type: 'text',
      additionalProps: { placeholder: '请输入职位' },
      show: { callback: () => addFormModel.value.type === 'staff' },
      rules: [{
        required: true,
        message: '请输入职位',
      }] as RuleItem[],
    },
    {
      label: '申请理由',
      name: 'claimReason',
      type: 'textarea',
      additionalProps: {
        placeholder: '请说明认领该村社的原因（选填），可以加快管理员审核速度',
        showWordLimit: true,
        maxLength: 200,
      } as FieldProps,
    },
  ]
}

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 = props.villageId;
    await VillageApi.claimVallage(addFormModel.value as VillageClaimInfo);
    toast({ content: '提交成功' });
    show.value = false;
  } catch (e) {
    showError(e);
  } finally {
    addFormLoading.value = false;
  }
}

defineExpose({
  show: () => {
    show.value = true;
    step.value = 'chooseType';
    addFormModel.value = new VillageClaimInfo();
    addFormModel.value.type = 'villager';
    addFormModel.value.villageId = props.villageId;
  },
});
</script>