<script lang="ts" setup>
import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Form, FormItem, InputNumber, message } from 'ant-design-vue';

import { updateStoreExternalFieldApi } from '../api';

const storeId = ref(0);
const field = ref<'erp_id' | 'mes_id'>('erp_id');
const fieldLabel = ref('');
const inputValue = ref<null | number>(null);
const gridApiRef = ref<any>(null);

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    modalApi.setState({ confirmLoading: true });
    try {
      await updateStoreExternalFieldApi({
        id: storeId.value,
        field: field.value,
        value:
          inputValue.value === null || inputValue.value === undefined
            ? ''
            : inputValue.value,
      });
      message.success('保存成功');
      gridApiRef.value?.query?.();
      gridApiRef.value?.reload?.();
      modalApi.close();
    } catch {
      message.error('保存失败');
    } finally {
      modalApi.setState({ confirmLoading: false });
    }
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const data = modalApi.getData<{
        field: 'erp_id' | 'mes_id';
        gridApi: any;
        label: string;
        values: Record<string, any>;
      }>();
      gridApiRef.value = data?.gridApi;
      storeId.value = data?.values?.id ?? 0;
      field.value = data?.field ?? 'erp_id';
      fieldLabel.value = data?.label ?? '';
      const f = data?.field ?? 'erp_id';
      const raw = data?.values?.[f];
      inputValue.value =
        raw !== null && raw !== undefined && raw !== '' ? Number(raw) : null;
    } else {
      storeId.value = 0;
      inputValue.value = null;
      gridApiRef.value = null;
    }
  },
});
</script>

<template>
  <Modal :title="`编辑${fieldLabel}`" class="w-[400px]">
    <Form layout="vertical">
      <FormItem :label="fieldLabel">
        <InputNumber
          v-model:value="inputValue"
          allow-clear
          class="w-full"
          :precision="0"
          placeholder="留空表示清空"
        />
      </FormItem>
    </Form>
  </Modal>
</template>
