<!-- 搜索表单 -->
<template>
  <simple-form-modal
    :title="title"
    :items="formItems"
    ref="editRef"
    :baseUrl="baseUrl"
    @success="(data) => emit('success', data)"
  ></simple-form-modal>
</template>

<script setup>
  import { reactive, ref, defineEmits, getCurrentInstance } from 'vue';
  import { useFormData } from '@/utils/use-form-data';
  import SimpleFormModal from '@/components/CommonPage/SimpleFormModal.vue';
  const { proxy } = getCurrentInstance();

  //获取省市
  const provinceList = ref([]);
  const cityList = ref([]);
  const title = ref('新增高校');
  const emit = defineEmits(['success']);

  const formItems = computed(() => {
    return [
      { type: 'input', label: '学校名称', prop: 'schoolName', required: true },
      {
        type: 'select',
        label: '省份',
        prop: 'provinceId',
        required: true,
        options: provinceList.value.map((d) => {
          return { label: d.district, value: d.id };
        }),
        props: {
          filterable: true,
          onChange: (val) => {
            getProviceList(val).then((res) => {
              cityList.value = res.data.data;
            });
          }
        }
      },
      {
        type: 'select',
        label: '所在市',
        prop: 'cityId',
        required: true,
        options: cityList.value.map((d) => {
          return { label: d.district, value: d.id };
        }),
        props: {
          filterable: true
        }
      },
      {
        type: 'dictSelect',
        label: '办学层次',
        prop: 'schoolLevel',
        props: { code: 'school_level' },
        required: true
      },
      {
        type: 'input',
        label: '主管部门',
        prop: 'departmentName',
        required: true
      },
      {
        type: 'dictSelect',
        label: '标记',
        prop: 'schoolTag',
        props: { code: 'school_tag' },
        required: true
      }
    ];
  });
  //默认值
  const baseUrl = reactive({
    add: '/baseinfo/schoolInfo/save',
    update: '/baseinfo/schoolInfo/edit'
  });
  const formData = ref({ schoolTag: '1' });

  const editRef = ref(null);

  function handleOpen(data = {}) {
    title.value = data && data.id ? '编辑高校' : '新增高校';
    formData.value = Object.assign(formData.value, data || {});
    getProviceList().then((res) => {
      provinceList.value = res.data.data;
    });
    if (data && data.provinceId) {
      getProviceList(data.provinceId).then((res) => {
        cityList.value = res.data.data;
      });
    }
    editRef.value?.handleOpen(formData.value);
  }

  function getProviceList(id = 1) {
    return proxy.$http.get(`/baseinfo/districtInfo/findInfo/${id}`);
  }

  defineExpose({ handleOpen });
</script>
