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

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

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';

import { insertTableDataApi, updateTableDataApi } from '../api';

defineOptions({
  name: 'EditDataModal',
});

const tableName = ref('');
const columns = ref<any[]>([]);
const isUpdate = ref(false);
const primaryKey = ref('');
const reloadCallback = ref<(() => void) | null>(null);

const formSchema = computed(() => {
  return columns.value.map((col) => {
    const isTextType = col.type === 'text' || col.type === 'longtext';
    return {
      component: isTextType ? 'Textarea' : 'Input',
      fieldName: col.name,
      label: col.comment || col.name,
      formItemClass: 'col-span-12',
      componentProps: {
        placeholder: `请输入${col.comment || col.name}`,
        ...(isTextType ? { rows: 3 } : {}),
        ...(col.name === primaryKey.value && isUpdate.value ? { disabled: true } : {}),
      },
    };
  });
});

const [Form, formApi] = useVbenForm({
  wrapperClass: 'grid-cols-12',
  commonConfig: {
    formItemClass: 'col-span-12',
    componentProps: {
      class: 'w-full',
    },
  },
  layout: 'horizontal',
  schema: formSchema,
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    const valid = await formApi.validate();
    if (valid.valid) {
      const values = await formApi.getValues();
      modalApi.setState({ loading: true, confirmLoading: true });
      try {
        if (isUpdate.value) {
          // 构建WHERE条件
          const where = [
            {
              field: primaryKey.value,
              operator: '=',
              value: values[primaryKey.value],
            },
          ];
          const data = { ...values };
          delete data[primaryKey.value];

          await updateTableDataApi({
            table_name: tableName.value,
            data,
            where,
          });
          message.success('更新成功');
        } else {
          await insertTableDataApi({
            table_name: tableName.value,
            data: values,
          });
          message.success('添加成功');
        }
        reloadCallback.value?.();
        modalApi.close();
      } catch (error: any) {
        message.error(error.message || '操作失败');
      } finally {
        modalApi.setState({ loading: false, confirmLoading: false });
      }
    }
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const data = modalApi.getData<{
        tableName: string;
        columns: any[];
        values?: any;
        update?: boolean;
        reload: () => void;
      }>();
      if (data) {
        tableName.value = data.tableName;
        columns.value = data.columns;
        isUpdate.value = data.update || false;
        reloadCallback.value = data.reload;

        // 查找主键
        const pkColumn = data.columns.find((col) => col.key_type === 'PRI');
        primaryKey.value = pkColumn ? pkColumn.name : data.columns[0]?.name || 'id';

        // 设置表单值
        if (data.values) {
          formApi.setValues(data.values);
        } else {
          formApi.resetFields();
        }
      }
    }
  },
});
</script>

<template>
  <Modal :title="`${isUpdate ? '编辑' : '添加'}数据`" class="w-[800px]">
    <Form />
  </Modal>
</template>
