<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="800" @ok="handleSubmit">
    <BasicForm @register="registerForm" name="MesXslCustomerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from '../MesXslCustomer.data';
  import { saveOrUpdate, queryById } from '../MesXslCustomer.api';

  /** 字典下拉 value 与接口一致为字符串，避免 number/string 与选项不一致导致回显成第一项「启用」 */
  function normalizeCustomerFormValues(record: Recordable) {
    const o = { ...record };
    if (o.status !== undefined && o.status !== null && o.status !== '') {
      o.status = String(o.status);
    }
    if (o.customerRegion !== undefined && o.customerRegion !== null && o.customerRegion !== '') {
      o.customerRegion = String(o.customerRegion);
    }
    return o;
  }

  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)) {
      let row = data?.record;
      // 以详情接口为准，避免列表行字段缺失或与字典组件 value 类型不一致（列表仍显示 status_dictText）
      if (row?.id) {
        try {
          const res = await queryById({ id: String(row.id) });
          const full = (res as any)?.id != null ? res : (res as any)?.result ?? res;
          if (full && (full as any).id) {
            row = full as Recordable;
          }
        } catch {
          // 仍使用列表行
        }
      }
      await setFieldsValue(normalizeCustomerFormValues(row || {}));
    } else {
      // 新增默认启用（与后端 MesXslCustomerBizStatus.ENABLED 一致，0=启用）
      await setFieldsValue({ status: '0' });
    }
    setProps({ disabled: !data?.showFooter });
  });

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

  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>

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