<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 { updateTableStructureApi } from '../api';

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

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

// 字段类型选项
const fieldTypeOptions = [
  { label: 'VARCHAR', value: 'VARCHAR' },
  { label: 'CHAR', value: 'CHAR' },
  { label: 'TEXT', value: 'TEXT' },
  { label: 'LONGTEXT', value: 'LONGTEXT' },
  { label: 'INT', value: 'INT' },
  { label: 'BIGINT', value: 'BIGINT' },
  { label: 'TINYINT', value: 'TINYINT' },
  { label: 'SMALLINT', value: 'SMALLINT' },
  { label: 'DECIMAL', value: 'DECIMAL' },
  { label: 'FLOAT', value: 'FLOAT' },
  { label: 'DOUBLE', value: 'DOUBLE' },
  { label: 'DATETIME', value: 'DATETIME' },
  { label: 'DATE', value: 'DATE' },
  { label: 'TIMESTAMP', value: 'TIMESTAMP' },
  { label: 'TIME', value: 'TIME' },
  { label: 'YEAR', value: 'YEAR' },
  { label: 'BOOLEAN', value: 'TINYINT' },
];

// 需要长度的类型
const typesNeedLength = ['VARCHAR', 'CHAR', 'INT', 'BIGINT', 'TINYINT', 'SMALLINT', 'DECIMAL', 'FLOAT', 'DOUBLE'];

// 位置选项（AFTER字段）
const positionOptions = computed(() => {
  if (!columns.value) return [];
  return columns.value.map((col) => ({
    label: `${col.name}${col.comment ? ` (${col.comment})` : ''}`,
    value: col.name,
  }));
});

// 表单schema
const formSchema = computed(() => {
  const baseSchema = [
    {
      component: 'Input',
      fieldName: 'name',
      label: '字段名',
      formItemClass: 'col-span-12',
      componentProps: {
        placeholder: '请输入字段名（小写字母、数字、下划线）',
      },
      rules: 'required',
    },
    {
      component: 'Select',
      fieldName: 'type',
      label: '字段类型',
      formItemClass: 'col-span-12',
      componentProps: {
        options: fieldTypeOptions,
        placeholder: '请选择字段类型',
      },
      rules: 'required',
    },
  ];

  // 根据类型动态添加长度字段
  const lengthField = {
    component: 'Input',
    fieldName: 'length',
    label: '长度/精度',
    formItemClass: 'col-span-12',
    componentProps: {
      placeholder: '例如: 255 或 10,2 (DECIMAL类型)',
    },
    dependencies: {
      show: {
        triggerFields: ['type'],
        condition: (values: any) => {
          const type = values.type || '';
          return typesNeedLength.includes(type.toUpperCase());
        },
      },
    },
  };

  const afterField = {
    component: 'Select',
    fieldName: 'after',
    label: '位置（AFTER字段）',
    formItemClass: 'col-span-12',
    componentProps: {
      options: positionOptions.value,
      placeholder: '选择字段位置，留空则添加到表末尾',
      allowClear: true,
    },
  };

  return [
    ...baseSchema,
    lengthField,
    {
      component: 'Input',
      fieldName: 'default_value',
      label: '默认值',
      formItemClass: 'col-span-12',
      componentProps: {
        placeholder: '请输入默认值，留空表示无默认值',
      },
    },
    {
      component: 'Switch',
      fieldName: 'nullable',
      label: '允许NULL',
      formItemClass: 'col-span-12',
    },
    {
      component: 'Textarea',
      fieldName: 'comment',
      label: '字段注释',
      formItemClass: 'col-span-12',
      componentProps: {
        rows: 3,
        placeholder: '请输入字段注释',
      },
    },
    afterField,
  ];
});

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 {
        // 构建column_info
        const columnInfo: any = {
          name: values.name,
          type: values.type,
        };

        // 处理长度
        if (values.length && typesNeedLength.includes(values.type.toUpperCase())) {
          columnInfo.length = values.length;
        }

        // 处理默认值
        if (values.default_value !== null && values.default_value !== undefined && values.default_value !== '') {
          columnInfo.default_value = values.default_value;
        }

        // 处理NULL
        columnInfo.nullable = values.nullable || false;

        // 处理注释
        if (values.comment) {
          columnInfo.comment = values.comment;
        }

        // 处理位置
        if (values.after) {
          columnInfo.after = values.after;
        }

        await updateTableStructureApi({
          table_name: tableName.value,
          action: 'add',
          column_info: columnInfo,
        });
        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[];
        reload: () => void;
      }>();
      if (data) {
        tableName.value = data.tableName;
        columns.value = data.columns;
        reloadCallback.value = data.reload;
        formApi.resetFields();
      }
    }
  },
});
</script>

<template>
  <Modal title="添加字段" class="w-[600px]">
    <Form />
  </Modal>
</template>
