<template>
  <CommonRoot class="main">
    <LoadingPage v-if="loading" /> 
    <FlexCol :padding="30">
      <DynamicForm
        ref="formRef"
        :model="formModel"
        :options="formDefine"
        :formGlobalParams="querys"
      />
      <Height :height="20" />
      <Button type="primary" @click="submit">提交</Button>
    </FlexCol>
  </CommonRoot>
</template>

<script setup lang="ts">
import { computed, nextTick, ref } from 'vue';
import { useLoadQuerys } from '@/common/composeabe/LoadQuerys';
import { useAliOssUploadCo } from '@/common/components/upload/AliOssUploadCo';
import { showError } from '@/common/composeabe/ErrorDisplay';
import { alert, toast } from '@/components/dialog/CommonRoot';
import { backAndCallOnPageBack } from '@/components/utils/PageAction';
import { RequestApiError } from '@imengyu/imengyu-utils';
import DynamicForm from '@/components/dynamic/DynamicForm.vue';
import LoadingPage from '@/components/display/loading/LoadingPage.vue';
import Button from '@/components/basic/Button.vue';
import CommonRoot from '@/components/dialog/CommonRoot.vue';
import FlexCol from '@/components/layout/FlexCol.vue';
import Height from '@/components/layout/space/Height.vue';
import VillageApi, { VolunteerInfo } from '@/api/inhert/VillageApi';
import CommonContent from '@/api/CommonContent';
import type { RuleItem } from 'async-validator';
import type { IDynamicFormOptions, IDynamicFormRef, IDynamicFormItemCallbackAdditionalProps } from '@/components/dynamic';
import type { UploaderFieldProps } from '@/components/form/UploaderField.vue';
import type { FieldProps } from '@/components/form/Field.vue';
import type { PickerIdFieldProps } from '@/components/dynamic/wrappers/PickerIdField';
import type { RadioValueProps } from '@/components/dynamic/wrappers/RadioValue';
import type { CheckBoxListProps } from '@/components/dynamic/wrappers/CheckBoxList.vue';
import type { FormProps } from '@/components/form/Form.vue';

const loading = ref(false);

const formRef = ref<IDynamicFormRef>();
const formModel = ref<VolunteerInfo>();
const formDefine : IDynamicFormOptions = {
  formItems: [
    { 
      label: '用户名', name: 'username', type: 'text',
      additionalProps: { 
        placeholder: '请输入用户名',
        disabled: { callback: () => !isNew.value },
      },
      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 != formRef.value?.getValueByPath('password'))
              throw '两次输入密码不一致，请检查';
          },
        }
      ] as RuleItem[],
    },
    {
      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: '请选择区域',
        disabled: { callback: () => !isNew.value },
        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: 'villageId', type: 'select-id',
      additionalProps: {
        placeholder: '请选择所属村庄',
        disabled: { callback: () => !isNew.value },
        loadData: async () => (await VillageApi.getClaimedVallageList()).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: 'collectModule', type: 'check-box-list', 
      additionalProps: { 
        placeholder: '请选择采集版块',
        vertical: true,
        multiple: true,
        loadData: async () => 
          (await VillageApi.getCollectModuleList())
            .map((p) => ({
              text: p.label,
              value: p.value,
              raw: p
            }))
          ,
      } as CheckBoxListProps,
    },
    { label: '村落认领说明', name: 'claimReason', type: 'text', additionalProps: { placeholder: '请输入村落认领说明' } },
  ],
  formAdditionaProps: {
    labelWidth: '160rpx',
    labelAlign: 'right',
    innerStyle: {
      radius: '10rpx',
    },
  } as Omit<FormProps, 'model'>,
}

async function submit() {
  if (!formRef.value)
    return;
  try {
    await formRef.value.validate();
  } catch (e) {
    toast({ content: '有必填项未填写，请检查' });
    return;
  }
  try {
    loading.value = true;
    if (querys.value.id >= 0) {
      await VillageApi.updateVolunteer(formModel.value!);
    } else {
      await VillageApi.addVolunteer(formModel.value!);
    };
    alert({
      title: '操作成功',
      icon: 'success-filling',
      iconColor: 'success',
      content: isNew.value ? '新增志愿者信息成功' : '更新志愿者信息成功',
      onConfirm() {
        backPrev(true);
      },
    });
  } catch (e) {
    showError(e);
  } finally {
    loading.value = false;
  }
}
function backPrev(needRefresh: boolean) {
  backAndCallOnPageBack('list', {
    needRefresh,
  });
}

const { querys } = useLoadQuerys({ 
  villageId: 0,  
  villageVolunteerId: 0,
  id: 0,
}, async (querys) => {
  loading.value = true;
  if (!formRef.value)
    return;

  let formData = undefined;

  try {
    formModel.value = new VolunteerInfo();
    if (querys.id >= 0)
      formData = await VillageApi.getVolunteerInfoById(querys.id);
  } catch (e) {
    if (!(e instanceof RequestApiError && e.errorMessage.startsWith('请完成')))
      showError(e, undefined, () => backPrev(false));
  } finally {
    loading.value = false;
  }

  if (formData) {
    formModel.value = formData;
  }
   
  await nextTick();

  formRef.value.initDefaultValuesToModel();
});
const isNew = computed(() => querys.value.id < 0);

</script>
