<template>
  <BasicModal v-bind="$attrs"
              :title="getTitle"
              @register="registerModal"
              @ok="handleSubmit"
  >
    <BasicForm @register="registerForm"/>
  </BasicModal>
</template>

<script lang="ts" setup>
import {ref, computed, unref, toRaw} from 'vue';
import {BasicModal, useModalInner} from '/@/components/Modal';
import {hospitalFormSchema} from './hospital.data';
import {BasicForm, useForm} from '/@/components/Form';
import {set} from '/@/api/platform/system/controller/hospital';
import {HospitalItem} from '/@/api/platform/system/entity/hospitalModel';
const isUpdate = ref(true);
// 定义emit
const emit = defineEmits(['success', 'register']);
/**
 * 表单
 */
const [registerForm, {resetFields, setFieldsValue, validate}] = useForm({
  labelWidth: 120,
  schemas: hospitalFormSchema,
  showActionButtonGroup: false,
  actionColOptions: {
    span: 23,
  },
});
/**
 * 表单参数
 */
const [registerModal, {setModalProps, closeModal}] = useModalInner( (data) => {
  resetFields();
  setModalProps({confirmLoading: false});
  isUpdate.value = !!data?.isUpdate;
  if (unref(isUpdate)) {
    if(typeof data.record.addressIds == 'string'){
      let addressIdsStr: string = data.record.addressIds;
      const addressIds:String[] = addressIdsStr.split(',');
      data.record.addressIds = addressIds;
    }
    setFieldsValue({
      ...data.record,
    });
  }
});
//表单标题
const getTitle = computed(() => (!unref(isUpdate) ? '新增医院' : '编辑医院'));
async function handleSubmit() {
  try {
    const values = await validate();
    setModalProps({confirmLoading: true});
    let val = toRaw<HospitalItem>(values);
    values.addressIds = toRaw(val.addressIds);
    await set(values);
    closeModal();
    emit('success');
  } finally {
    setModalProps({confirmLoading: false});
  }
}
</script>