<template>
  <BasicModal @register="registerModal" title="新增数据" width="700px" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #id='{ model, field }'>
        <div>
          <a-input v-model:value="model[field]" :disabled="isEdit" placeholder="请选择"/>
        </div>
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { defineComponent,ref,unref } from 'vue';
  import { BasicModal,useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { FormSchema } from '/@/components/Table';
  import { addXzbm,editXzbm,delXzbm  } from '../address.api';
  let isEdit = ref<Boolean>(false)
  const formSchema: FormSchema[] = [
    {
      field: 'id',
      label: '编码',
      component:'Input',
      required: true,
      slot:'id',
      // componentProps:{
      //   disabled:()=>{ 
      //     return !isEdit.value
      //   },
      // },
      dynamicRules: () => {
      return [
        { pattern:/^[1-9][0-9]*$/, message: '只能输入数字', required: true, },
      ];
    },
    },
    {
      field: 'name',
      label: '机构名称',
      component: 'Input',
      required: true,
    },
    {
    label: '行政区划',
    field: 'pid',
    component: 'JTreeSelect',
    componentProps: {
      url: '/sys/api/tree/xzbm',
    },
    required: true,
    // cityTree
  },
  ] 
  const emit = defineEmits(['register', 'success']);
  const [registerForm, { setProps, resetFields, setFieldsValue, updateSchema, validate, clearValidate }] = useForm({
    labelCol: {
      md: { span: 4 },
      sm: { span: 6 },
    },
    wrapperCol: {
      md: { span: 20 },
      sm: { span: 18 },
    },
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //重置表单
    await resetFields();
    if(!(data.isUpdate)){
        isEdit.value = false
    }
    if(data.isUpdate){
        isEdit.value = true
    }
  //表单赋值
    await setFieldsValue({
      ...data.record
    })

});
  async function handleSubmit() {
    try{
      const values = await validate();
      if(isEdit.value){
        await editXzbm(values);
      }else{
        await addXzbm(values);
      }
      closeModal()
      emit('success', { values });
    }catch{

    }
  }
</script>
