<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="title" @ok="handleSubmit" @cancel="handleCancel" width="40%">
    <BasicForm @register="registerForm">
      <template #wrdkid="{ model, field }">
        <a-select
          v-model:value="model[field]"
          show-search
          placeholder="模糊搜索污染地块"
          :filter-option="false"
          :not-found-content="state.fetching ? undefined : null"
          :options="state.data"
          @search="fetchUser"
          :disabled="isUpdate"
        >
          <template v-if="state.fetching" #notFoundContent>
            <a-spin size="small" />
          </template>
        </a-select>
      </template>
      <template #zjcyId="{ model, field }">
        <a-select
          v-model:value="model[field]"
          show-search
          placeholder="模糊搜索专家"
          :filter-option="false"
          :not-found-content="state.fetching1 ? undefined : null"
          :options="state.data1"
          @search="fetchUser1"
          :disabled="isUpdate"
        >
          <template v-if="state.fetching" #notFoundContent>
            <a-spin size="small" />
          </template>
        </a-select>
      </template>
    </BasicForm>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed, unref, reactive } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from '../zjsh.data';
  import { saveOrUpdate, dkList, zjkList } from '../zjsh.api';
  import { debounce } from 'lodash-es';
  // Emits声明
  const emit = defineEmits(['register', 'success']);
  const isUpdate = ref(true);
  //表单配置
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 80,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { span: 12 },
  });
  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //重置表单
    await resetFields();
    setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      fetchUser(data.record.wrdkmc);
      fetchUser1(data.record.zjxm);
      //表单赋值
      await setFieldsValue({
        ...data.record,
      });
    }
  });
  //设置标题
  const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
  //表单提交事件
  async function handleSubmit(v) {
    try {
      let values = await validate();
      setModalProps({ confirmLoading: true });
      //提交表单
      await saveOrUpdate(values, isUpdate.value);
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success', { isUpdate: isUpdate.value, values });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
  //关闭弹窗
  function handleCancel() {
    state.data = [];
    state.fetching = false;
    state.data1 = [];
    state.fetching1 = false;
  }
  let lastFetchId = 0;
  let lastFetchId1 = 0;
  const state = reactive({
    data: [],
    data1: [],
    value: [],
    value1: [],
    fetching: false,
    fetching1: false,
  });
  const fetchUser = debounce((value) => {
    console.log('fetching user', value);
    lastFetchId += 1;
    const fetchId = lastFetchId;
    state.data = [];
    state.fetching = true;
    dkList({ wrdkbm: value, pageNo: 1, pageSize: 99999999 }).then((res) => {
      if (fetchId !== lastFetchId) {
        return;
      }
      const data = res.records.map((item) => ({
        value: item.wrdkid,
        label: item.wrdkmc,
      }));
      state.data = data;
      state.fetching = false;
    });
  }, 300);
  const fetchUser1 = debounce((value) => {
    console.log('fetching user1', value);
    lastFetchId1 += 1;
    const fetchId = lastFetchId1;
    state.data1 = [];
    state.fetching1 = true;
    zjkList({ zjxm: value, pageNo: 1, pageSize: 99999999 }).then((res) => {
      if (fetchId !== lastFetchId1) {
        return;
      }
      const data = res.records.map((item) => ({
        value: item.id,
        label: item.zjxm,
      }));
      state.data1 = data;
      state.fetching1 = false;
    });
  }, 300);
</script>

<style lang="less" scoped>
  :deep(.ant-input-number) {
    width: 100%;
  }
</style>
