<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 { CheckBoxListItem, CheckBoxListProps } from '@/components/dynamic/wrappers/CheckBoxList.vue';
import type { FormProps } from '@/components/form/Form.vue';
import type { CheckBoxTreeListProps } from '@/components/dynamic/wrappers/CheckBoxTreeList.vue';

const loading = ref(false);

const formRef = ref<IDynamicFormRef>();
const formModel = ref<VolunteerInfo>();
const formDefine : IDynamicFormOptions = {
  formItems: [
    { 
      label: '用户名', name: 'username', type: 'text',
      additionalProps: { 
        placeholder: '请输入用户名',
      },
      rules: [{ required: true, message: '请输入用户名' }],
      show: { callback: () => isNew.value },
    },
    {
      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: '请选择所属村社' }],
      show: { callback: () => isNew.value },
    },
    {
      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: 'catalogIds', type: 'check-box-tree', 
      additionalProps: { 
        placeholder: '请选择采集版块',
        vertical: true,
        multiple: true,
        loadData: async (pid) => (await VillageApi.getCatalogList(querys.value.villageId, pid)).map((p) => ({
          text: p.title,
          value: p.id,
          hasChildren: p.haschild,
        })),
      } as CheckBoxTreeListProps,
    },
    { 
      label: '村落认领说明', name: 'claimReason', type: 'text', 
      additionalProps: { placeholder: '请输入村落认领说明' } ,
      show: { callback: () => isNew.value },
    },
  ],
  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.getVolunteerInfoByIdAdmin(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>
