<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="680" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #warehousePicker="{ model, field }">
        <JSearchSelect
          v-model:value="model[field]"
          dict="mes_xsl_warehouse,warehouse_name,id"
          :async="true"
          placeholder="请搜索并选择仓库"
          :disabled="isDetail"
          @change="(v) => onWarehouseChange(model, v)"
        />
      </template>
    </BasicForm>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm, JSearchSelect } from '/@/components/Form';
  import { formSchema } from '../MesXslWarehouseArea.data';
  import { saveOrUpdate } from '../MesXslWarehouseArea.api';
  import { defHttp } from '/@/utils/http/axios';

  const emit = defineEmits(['register', 'success']);

  const isUpdate = ref(true);
  const isDetail = ref(false);

  const [registerForm, { setProps, resetFields, setFieldsValue, validate, scrollToField }] = useForm({
    labelWidth: 120,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { span: 24 },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    await resetFields();
    setModalProps({ confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter });
    isUpdate.value = !!data?.isUpdate;
    isDetail.value = !data?.showFooter;

    if (unref(isUpdate)) {
      await setFieldsValue({ ...data.record });
    } else {
      await setFieldsValue({ status: '0' });
    }

    setProps({ disabled: !data?.showFooter });
  });

  const title = computed(() => (!unref(isUpdate) ? '新增库区' : unref(isDetail) ? '库区详情' : '编辑库区'));

  async function onWarehouseChange(model: any, val: unknown) {
    const id = val != null && val !== '' ? String(val) : '';
    if (!id) {
      model.warehouseName = '';
      await setFieldsValue({ warehouseName: '', warehouseCategory: undefined });
      return;
    }
    try {
      const wh = await defHttp.get({ url: '/xslmes/mesXslWarehouse/queryById', params: { id } });
      if (wh) {
        await setFieldsValue({
          warehouseName: wh.warehouseName || '',
          warehouseCategory: wh.warehouseCategory || undefined,
        });
      }
    } catch {
      // ignore
    }
  }

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      await saveOrUpdate(values, unref(isUpdate));
      closeModal();
      emit('success');
    } catch (e: any) {
      if (e?.errorFields) {
        const firstField = e.errorFields[0];
        if (firstField) {
          scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(e);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
