<script setup lang="ts">
/* eslint-disable no-underscore-dangle */
import { computed, defineProps, h, nextTick, onActivated, onMounted, provide, ref, watch, withDefaults } from 'vue';
import SearchForm from './codet/components/SearchForm.vue';
import DataTable from './codet/components/DataTable.vue';
import TableSettingsDrawer from './codet/components/TableSettingsDrawer.vue';
import ColumnEditDrawer from './codet/components/ColumnEditDrawer.vue';
import SearchFieldEditDrawer from './codet/components/SearchFieldEditDrawer.vue';
import AddFieldDrawer from './codet/components/AddFieldDrawer.vue';
import DataTransform from './codet/components/DataTransform.vue';
import CreateDialog from './codet/components/CreateDialog.vue';
// 使用封装的axios实例 - 已在main.ts中全局注册，支持代理
const axios = (window as any).$axios;

// 定义组件名称，避免与HTML元素冲突
defineOptions({
  name: 'TableView'
});

const tableData = ref([]);
const loading = ref(false);

// 在 script setup 中添加响应式变量
const tableSize = ref('medium'); // 表格大小
const showBorder = ref(true); // 表格纵向边框
const showStripe = ref(true); // 表格隔行换色
const enableSingleSelect = ref(false); // 是否开启序号
const activeTab = ref('table'); // 当前激活的标签页
// 定义props
interface Props {
  uiConfig?: Record<string, any>;
}

const props = withDefaults(defineProps<Props>(), {
  uiConfig: () => ({})
});
// 分页配置
const pagination = ref({
  page: 1,
  pageSize: 20,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [20, 30, 40, 50],
  prefix: ({ itemCount }: { itemCount: number }) => `共 ${itemCount} 条`
});

// 定义列的类型
interface TableColumn {
  title: string;
  key: string;
  width: number;
  minWidth?: number;
  render?: (row: any, index?: number) => any; // 修改render函数类型定义
  ellipsis?: {
    tooltip: boolean;
  };
  resizable?: boolean;
  align?: 'left' | 'center' | 'right';
  titleAlign?: 'left' | 'center' | 'right';
  sortable?: boolean;
  sorter?: (row1: any, row2: any) => number;
  filter?: boolean;
  filterOptions?: { label: string; value: string }[];
  filterOptionValues?: string[] | null; // 用于存储当前选中的筛选值
  __originalRender?: (row: any, index?: number) => any; // 备份原始渲染函数
}
// 接口类型定义
interface SearchFieldOption {
  label: string;
  value: string;
}

interface SearchField {
  label: string;
  key: string;
  type: string;
  visible: boolean;
  defaultValue: string;
  placeholder: string;
  options: SearchFieldOption[];
  order: number;
}

interface TagMapping {
  value: string;
  label: string;
  color: string;
}

interface TransformRule {
  field: string;
  fieldLabel: string;
  type: string;
  typeLabel: string;
  params: {
    mappings: TagMapping[];
  };
}
// 添加日期格式化函数
const formatDate = (dateStr: string) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  if (Number.isNaN(date.getTime())) return dateStr;

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 原始列配置
const rawColumns = ref<TableColumn[]>([]);

// 添加列配置相关的响应式变量
const visibleColumns = ref<string[]>([]);

// 当前筛选状态
const currentFilters = ref<Record<string, any>>({});

// 获取当前所有列的筛选状态
const getFiltersState = () => {
  const filters: Record<string, string[]> = {};

  rawColumns.value.forEach(col => {
    if (col.filter && col.filterOptionValues && col.filterOptionValues.length) {
      filters[col.key] = col.filterOptionValues;
    }
  });

  return filters;
};

// 筛选改变
const handleFiltersChange = (filters: any) => {
  // 保存当前筛选状态到currentFilters
  // 格式化筛选参数，确保数组标识在冒号后面，值在数组里
  const formattedFilters: Record<string, any> = {};

  for (const key in filters) {
    if (filters[key] && filters[key].length) {
      // 移除可能存在的数组标记
      const cleanKey = key.replace('[]', '');
      // 将值作为数组存储
      formattedFilters[cleanKey] = filters[key];
    }
  }

  currentFilters.value = formattedFilters;
  pagination.value.page = 1;
  fetchData();
};

// 修改 generateColumns 函数
const generateColumns = (data: any): TableColumn[] => {
  if (!data) return [];
  const columns: TableColumn[] = [];

  // 添加序号列
  if (enableSingleSelect.value) {
    columns.push({
      title: '序号',
      key: 'index',
      width: 80,
      minWidth: 50,
      render: (_, index = 0) => index + 1 + (pagination.value.page - 1) * pagination.value.pageSize
    });
  }

  const processField = (obj: any, prefix = '') => {
    Object.entries(obj).forEach(([key, value]) => {
      // 处理数组类型字段
      if (Array.isArray(value)) {
        const columnKey = prefix + key;
        // 查找原有列的配置
        const existingColumn = rawColumns.value.find(col => col.key === columnKey);

        columns.push({
          title: key,
          key: columnKey,
          width: 200,
          minWidth: 150,
          ellipsis: existingColumn?.ellipsis ?? {
            tooltip: true
          },
          resizable: true,
          sortable: false, // 数组类型字段不支持排序
          render: (row: any) => {
            const arrayValue = row[key];
            if (Array.isArray(arrayValue)) {
              return arrayValue
                .map(item => {
                  if (typeof item === 'object') {
                    return Object.entries(item)
                      .map(([k, v]) => `${k}: ${v}`)
                      .join(', ');
                  }
                  return String(item);
                })
                .join('; ');
            }
            return '';
          }
        });
      }
      // 处理嵌套对象
      else if (value && typeof value === 'object' && !Array.isArray(value)) {
        Object.entries(value as object).forEach(([nestedKey, _]) => {
          const columnKey = `${key}.${nestedKey}`;
          // 查找原有列的配置
          const existingColumn = rawColumns.value.find(col => col.key === columnKey);

          columns.push({
            title: nestedKey,
            key: columnKey,
            width: key.includes('Time') ? 200 : 150,
            minWidth: 100,
            ellipsis: existingColumn?.ellipsis ?? {
              tooltip: true
            },
            resizable: true,
            sortable: existingColumn?.sortable ?? false,
            ...(existingColumn?.filter
              ? {
                  filter: existingColumn.filter,
                  filterOptions: existingColumn.filterOptions,
                  filterOptionValues: existingColumn.filterOptionValues
                }
              : {}),
            render:
              key.includes('Time') || key.includes('Date')
                ? (row: any) => formatDate(row[key]?.[nestedKey])
                : undefined,
            sorter: (row1: any, row2: any) => {
              const val1 = row1[key]?.[nestedKey];
              const val2 = row2[key]?.[nestedKey];
              if (val1 > val2) return 1;
              if (val1 < val2) return -1;
              return 0;
            }
          });
        });
      }
      // 处理普通字段
      else {
        const columnKey = prefix + key;
        // 查找原有列的配置
        const existingColumn = rawColumns.value.find(col => col.key === columnKey);

        columns.push({
          title: key,
          key: columnKey,
          width: key.includes('Time') ? 200 : 150,
          minWidth: 100,
          ellipsis: existingColumn?.ellipsis ?? {
            tooltip: true
          },
          resizable: true,
          sortable: existingColumn?.sortable ?? false,
          ...(existingColumn?.filter
            ? {
                filter: existingColumn.filter,
                filterOptions: existingColumn.filterOptions,
                filterOptionValues: existingColumn.filterOptionValues
              }
            : {}),
          render: key.includes('Time') || key.includes('Date') ? (row: any) => formatDate(row[key]) : undefined,
          sorter: (row1: any, row2: any) => {
            const val1 = row1[key];
            const val2 = row2[key];
            if (val1 > val2) return 1;
            if (val1 < val2) return -1;
            return 0;
          }
        });
      }
    });
  };

  processField(data);

  // 更新 rawColumns，但保留原有的排序设置
  rawColumns.value = columns;

  // 初始化 visibleColumns
  if (visibleColumns.value.length === 0) {
    visibleColumns.value = columns.map(col => col.key);
  }

  return columns;
};

// 修改计算属性，根据 visibleColumns 过滤显示的列
const columns = computed(() => {
  return rawColumns.value
    .filter(col => visibleColumns.value.includes(col.key))
    .map(col => ({
      ...col,
      title: col.title,
      width: col.width,
      sortable: col.sortable,
      sorter: col.sortable
        ? (row1: any, row2: any) => {
            const val1 = col.key.includes('.') ? row1[col.key.split('.')[0]]?.[col.key.split('.')[1]] : row1[col.key];
            const val2 = col.key.includes('.') ? row2[col.key.split('.')[0]]?.[col.key.split('.')[1]] : row2[col.key];

            // 处理数字类型
            if (!Number.isNaN(Number(val1)) && !Number.isNaN(Number(val2))) {
              return Number(val1) - Number(val2);
            }
            // 处理日期类型
            if (col.key.includes('Time') || col.key.includes('Date')) {
              // 使用formatDate函数格式化日期，然后进行比较
              const formattedDate1 = formatDate(val1);
              const formattedDate2 = formatDate(val2);
              // 如果格式化后的日期相同，则使用原始时间戳比较
              if (formattedDate1 === formattedDate2) {
                return new Date(val1).getTime() - new Date(val2).getTime();
              }
              // 否则比较格式化后的日期字符串
              return formattedDate1.localeCompare(formattedDate2);
            }
            // 处理字符串类型
            return String(val1).localeCompare(String(val2));
          }
        : undefined,
      // 处理筛选相关属性
      ...(col.filter
        ? {
            filter: true,
            filterOptions: col.filterOptions,
            filterOptionValues: col.filterOptionValues,
            // 添加筛选变化处理函数
            onFilterChange: (values: string[]) => {
              const columnIndex = rawColumns.value.findIndex(c => c.key === col.key);
              if (columnIndex !== -1) {
                // 保存筛选值到列配置
                rawColumns.value[columnIndex].filterOptionValues = values.length ? values : null;

                // 生成筛选状态并触发表格刷新
                handleFiltersChange(getFiltersState());
              }
            }
          }
        : {})
    }));
});

// 添加 watch 以在 enableSingleSelect 变化时重新生成列
watch(enableSingleSelect, () => {
  if (tableData.value.length > 0) {
    rawColumns.value = generateColumns(tableData.value[0]);
  }
});

// 当前排序状态
const currentSorter = ref();

// 添加搜索表单的展开状态
const isExpanded = ref(true);
// 在 script setup 部分添加以下代码
const searchFields = ref<SearchField[]>([]);

// 在 script setup 部分添加以下代码
const searchForm = ref<Record<string, any>>({});

// 修改 watch searchFields 的处理
watch(
  searchFields,
  newFields => {
    // 更新 searchForm 结构
    const newSearchForm: Record<string, any> = {};
    newFields.forEach(field => {
      // 根据不同类型设置不同的初始值,优先使用默认值
      if (field.type === 'date') {
        newSearchForm[field.key] = field.defaultValue || null;
      } else if (field.type === 'select') {
        newSearchForm[field.key] = field.defaultValue || undefined;
      } else {
        newSearchForm[field.key] = field.defaultValue || '';
      }
    });
    searchForm.value = newSearchForm;
  },
  { deep: true }
);

// 处理搜索
const handleSearch = () => {
  pagination.value.page = 1;
  fetchData();
};

// 重置搜索表单
const resetSearch = () => {
  // 只保留分页参数，清除其他所有搜索条件
  const newSearchForm = {
    Skip: (pagination.value.page - 1) * pagination.value.pageSize,
    Take: pagination.value.pageSize
  };
  searchForm.value = newSearchForm;
  handleSearch();
};

// 添加 CreateDialog 的引用
const createDialogRef = ref();

// 添加一个标志来追踪配置是否已加载
const isConfigLoaded = ref(false);

// 添加 TableSettingsDrawer 的引用
const tableSettingsDrawerRef = ref();

// 添加筛选功能相关配置
const newFilterLabel = ref('');
const newFilterValue = ref('');

// 添加获取所有设置的方法
const getAllTableSettings = async () => {
  if (tableSettingsDrawerRef.value) {
    await tableSettingsDrawerRef.value.handleGetSettings();
  }
};

// 处理新建
const handleCreate = (row?: any) => {
  if (row) {
    // 编辑模式
    // console.log('进入编辑模式', row);
    // 打开编辑弹窗并传递当前行数据
    createDialogRef.value?.open(row);
  } else {
    // 新建模式
    // console.log('进入新建模式');
    // 打开新建弹窗
    createDialogRef.value?.open();
  }
};

// 处理搜索参数
const buildSearchParams = () => {
  const searchParams: any = {
    ...searchForm.value,
    Skip: (pagination.value.page - 1) * pagination.value.pageSize,
    Take: pagination.value.pageSize,
    OrderBy: currentSorter.value
      ? (currentSorter.value.order === 'descend' ? '-' : '') + currentSorter.value.columnKey
      : undefined
  };

  // 处理筛选参数
  if (Object.keys(currentFilters.value).length) {
    for (const key in currentFilters.value) {
      if (
        currentFilters.value[key] &&
        Array.isArray(currentFilters.value[key]) &&
        currentFilters.value[key].length > 0
      ) {
        searchParams[key] = currentFilters.value[key];
      }
    }
  }

  // 处理表单中的值为空或undefined的情况，创建新对象而不是删除属性
  const cleanedParams: any = {};
  for (const key in searchParams) {
    if (searchParams[key] !== '' && searchParams[key] !== null && searchParams[key] !== undefined) {
      cleanedParams[key] = searchParams[key];
    }
  }
  Object.assign(searchParams, cleanedParams);
  // 清空原对象的其他属性
  for (const key in searchParams) {
    if (!(key in cleanedParams)) {
      searchParams[key] = undefined;
    }
  }

  // 处理日期范围
  if (searchForm.value.下单时间) {
    searchParams.下单时间开始 = searchForm.value.下单时间[0];
    searchParams.下单时间结束 = searchForm.value.下单时间[1];
    delete searchParams.下单时间;
  }

  return searchParams;
};

// 获取数据
async function fetchData() {
  console.log('🚀 fetchData 被调用，axios 可用:', Boolean(axios));
  loading.value = true;
  try {
    const searchParams = buildSearchParams();

    // 自定义axios请求配置，使用自定义参数序列化函数
    console.log('📡 发送请求到 /table.json');
    const response = await axios.get('/codet/test.json', {
      params: searchParams,
      paramsSerializer: (params: any) => {
        // 自定义参数序列化，避免数组被转换为key[]=value格式
        const queryParams: string[] = [];

        for (const key in params) {
          if (params[key] !== undefined && params[key] !== null) {
            if (Array.isArray(params[key])) {
              // 只在数组不为空时添加参数
              if (params[key].length > 0) {
                // 数组类型使用JSON.stringify处理，并将参数名变为复数形式
                queryParams.push(`${encodeURIComponent(`${key}s`)}=${encodeURIComponent(JSON.stringify(params[key]))}`);
              }
            } else {
              // 非数组类型参数保持原样
              queryParams.push(`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`);
            }
          }
        }

        return queryParams.join('&');
      }
    });
    console.log('✅ 请求成功，响应:', response.status, response.data?.Results?.length || 0, '条数据');
    if (response.data?.Results?.length) {
      // 保存当前的filter状态
      const currentFilterState: Record<
        string,
        {
          filter: boolean;
          filterOptions?: { label: string; value: string }[];
          filterOptionValues?: string[] | null;
        }
      > = rawColumns.value.reduce((acc: Record<string, any>, col) => {
        if (col.filter && col.filterOptionValues) {
          acc[col.key] = {
            filter: col.filter,
            filterOptions: col.filterOptions,
            filterOptionValues: col.filterOptionValues
          };
        }
        return acc;
      }, {});

      // 先获取字段配置
      let fieldConfigs = [];
      try {
        const entityResponse = await axios.get(`/Server/Entity/${props.uiConfig.Type}`);
        if (entityResponse.data?.Results) {
          fieldConfigs = entityResponse.data.Results;
        }
      } catch (error) {
        // console.error('获取字段配置失败:', error);
      }

      // 生成列配置时传入字段配置
      const generateColumnsWithConfig = (data: any, configs: any[]): TableColumn[] => {
        if (!data) return [];
        const newColumns: TableColumn[] = [];

        // 添加序号列
        if (enableSingleSelect.value) {
          newColumns.push({
            title: '序号',
            key: 'index',
            width: 60,
            minWidth: 30,
            render: (_, index = 0) => index + 1 + (pagination.value.page - 1) * pagination.value.pageSize
          });
        }

        const processField = (obj: any, prefix = '') => {
          Object.entries(obj).forEach(([key, value]) => {
            // 查找字段配置
            const fieldConfig = configs.find(field => field.Name === key);
            const displayName = fieldConfig?.DisplayName || key;

            // 处理数组类型字段
            if (Array.isArray(value)) {
              const columnKey = prefix + key;
              const existingColumn = rawColumns.value.find(col => col.key === columnKey);

              newColumns.push({
                title: displayName,
                key: columnKey,
                width: 200,
                minWidth: 150,
                ellipsis: existingColumn?.ellipsis ?? {
                  tooltip: true
                },
                resizable: true,
                sortable: false,
                render: (row: any) => {
                  const arrayValue = row[key];
                  if (Array.isArray(arrayValue)) {
                    return arrayValue
                      .map(item => {
                        if (typeof item === 'object') {
                          return Object.entries(item)
                            .map(([k, v]) => `${k}: ${v}`)
                            .join(', ');
                        }
                        return String(item);
                      })
                      .join('; ');
                  }
                  return '';
                }
              });
            }
            // 处理嵌套对象
            else if (value && typeof value === 'object' && !Array.isArray(value)) {
              Object.entries(value as object).forEach(([nestedKey, _]) => {
                const columnKey = `${key}.${nestedKey}`;
                const existingColumn = rawColumns.value.find(col => col.key === columnKey);
                const nestedFieldConfig = configs.find(field => field.Name === nestedKey);
                const nestedDisplayName = nestedFieldConfig?.DisplayName || nestedKey;

                newColumns.push({
                  title: nestedDisplayName,
                  key: columnKey,
                  width: key.includes('Time') ? 200 : 150,
                  minWidth: 100,
                  ellipsis: existingColumn?.ellipsis ?? {
                    tooltip: true
                  },
                  resizable: true,
                  sortable: existingColumn?.sortable ?? false,
                  ...(existingColumn?.filter
                    ? {
                        filter: existingColumn.filter,
                        filterOptions: existingColumn.filterOptions,
                        filterOptionValues: existingColumn.filterOptionValues
                      }
                    : {}),
                  render:
                    key.includes('Time') || key.includes('Date')
                      ? (row: any) => formatDate(row[key]?.[nestedKey])
                      : undefined,
                  sorter: (row1: any, row2: any) => {
                    const val1 = row1[key]?.[nestedKey];
                    const val2 = row2[key]?.[nestedKey];
                    if (val1 > val2) return 1;
                    if (val1 < val2) return -1;
                    return 0;
                  }
                });
              });
            }
            // 处理普通字段
            else {
              const columnKey = prefix + key;
              const existingColumn = rawColumns.value.find(col => col.key === columnKey);

              newColumns.push({
                title: displayName,
                key: columnKey,
                width: key.includes('Time') ? 200 : 150,
                minWidth: 100,
                ellipsis: existingColumn?.ellipsis ?? {
                  tooltip: true
                },
                resizable: true,
                sortable: existingColumn?.sortable ?? false,
                ...(existingColumn?.filter
                  ? {
                      filter: existingColumn.filter,
                      filterOptions: existingColumn.filterOptions,
                      filterOptionValues: existingColumn.filterOptionValues
                    }
                  : {}),
                render: key.includes('Time') || key.includes('Date') ? (row: any) => formatDate(row[key]) : undefined,
                sorter: (row1: any, row2: any) => {
                  const val1 = row1[key];
                  const val2 = row2[key];
                  if (val1 > val2) return 1;
                  if (val1 < val2) return -1;
                  return 0;
                }
              });
            }
          });
        };

        processField(data);
        return newColumns;
      };

      // 使用新的生成函数生成列配置
      rawColumns.value = generateColumnsWithConfig(response.data.Results[0], fieldConfigs);

      // 确保所有列在rawColumns更新后默认可见
      visibleColumns.value = rawColumns.value.map(col => col.key);

      // 恢复之前的筛选状态
      if (Object.keys(currentFilterState).length > 0) {
        rawColumns.value.forEach(col => {
          const savedState = currentFilterState[col.key];
          if (savedState) {
            col.filter = savedState.filter;
            col.filterOptions = savedState.filterOptions;
            col.filterOptionValues = savedState.filterOptionValues;
          }
        });
      }

      tableData.value = response.data.Results;
      pagination.value.itemCount = response.data.Total || 0;

      // 移除多余的判断，简化配置加载逻辑
      if (!isConfigLoaded.value) {
        // console.log('首次加载配置');
        isConfigLoaded.value = true;
        nextTick(() => {
          getAllTableSettings();
        });
      }
    } else {
      // 如果没有数据，清空表格数据并设置总数为0
      tableData.value = [];
      pagination.value.itemCount = response.data?.Total || 0;
    }
  } catch (error) {
    console.error('❌ 请求失败:', error);
    tableData.value = [];
    pagination.value.itemCount = 0;
  } finally {
    loading.value = false;
  }
}

// 添加删除后的数据刷新处理方法
const handleDeleteRefresh = async () => {
  // 记录删除前的数据条数
  const beforeDeleteCount = tableData.value.length;
  const currentPage = pagination.value.page;

  // 先刷新数据获取最新的总数
  await fetchData();

  // 如果当前页没有数据了，且不是第一页，则跳转到前一页
  if (tableData.value.length === 0 && currentPage > 1) {
    // console.log('当前页无数据，跳转到前一页');
    pagination.value.page = currentPage - 1;
    await fetchData();
  }
  // 如果删除后当前页还有数据，但数据条数减少了，说明删除成功
  else if (beforeDeleteCount > tableData.value.length || tableData.value.length === 0) {
    // console.log('删除成功，数据已更新');
  }
};

// 页码改变
const handlePageChange = (page: number) => {
  pagination.value.page = page;
  fetchData();
};

// 每页条数改变
const handlePageSizeChange = (pageSize: number) => {
  pagination.value.pageSize = pageSize;
  pagination.value.page = 1;
  fetchData();
};

// 排序改变
const handleSorterChange = (sorter: { columnKey: string; order: 'ascend' | 'descend' | false }) => {
  currentSorter.value = sorter;
  fetchData();
};

const showSettingDrawer = ref(false);
const tableHeight = ref(600);
const tableScrollWidth = ref(0); // 设置一个默认值

// 添加列配置相关的响应式变量
const showEditDrawer = ref(false);
const currentEditColumn = ref<TableColumn | null>(null);

// 修改拖拽排序相关的方法
const handleDragStart = (e: DragEvent, index: number) => {
  e.dataTransfer?.setData('text/plain', index.toString());
};

const handleDragOver = (e: DragEvent) => {
  e.preventDefault();
};

const handleDrop = (e: DragEvent, toIndex: number) => {
  e.preventDefault();
  const fromIndex = Number(e.dataTransfer?.getData('text/plain'));
  if (!Number.isNaN(fromIndex)) {
    const reorderedColumns = [...rawColumns.value];
    const [movedColumn] = reorderedColumns.splice(fromIndex, 1);
    reorderedColumns.splice(toIndex, 0, movedColumn);
    rawColumns.value = reorderedColumns;
  }
};

// 添加计算属性判断是否为 index 字段
const isIndexColumn = computed(() => {
  if (!currentEditColumn.value) return false;
  return currentEditColumn.value.key === 'index' || currentEditColumn.value.key.toLowerCase().includes('index');
});

// 修改编辑列的方法
const handleEditColumn = (column: TableColumn) => {
  currentEditColumn.value = {
    ...column,
    align: (column as any).align || 'left',
    titleAlign: (column as any).titleAlign || 'left',
    sortable: isIndexColumn.value ? false : column.sortable || false,
    // 保持原有的 ellipsis 配置，如果没有则不设置
    ...(column.ellipsis ? { ellipsis: { ...column.ellipsis } } : {}),
    // 保持原有的筛选配置
    ...(column.filter
      ? {
          filter: true,
          filterOptions: [...(column.filterOptions || [])]
        }
      : {})
  };
  showEditDrawer.value = true;

  // 重置添加筛选选项输入框
  newFilterLabel.value = '';
  newFilterValue.value = '';
};

// 修改 saveColumnEdit 方法
const saveColumnEdit = () => {
  if (!currentEditColumn.value) return;

  const index = rawColumns.value.findIndex(col => col.key === currentEditColumn.value?.key);
  if (index > -1) {
    const updatedColumn = {
      ...rawColumns.value[index],
      title: currentEditColumn.value.title,
      align: currentEditColumn.value.align,
      titleAlign: currentEditColumn.value.titleAlign,
      sortable: currentEditColumn.value.sortable
    };

    // 只在存在 ellipsis 时添加该属性
    if (currentEditColumn.value.ellipsis) {
      updatedColumn.ellipsis = {
        tooltip: currentEditColumn.value.ellipsis.tooltip
      };
    } else {
      // 确保删除 ellipsis 属性
      delete updatedColumn.ellipsis;
    }

    // 保存筛选相关设置
    if (currentEditColumn.value.filter) {
      updatedColumn.filter = true;
      updatedColumn.filterOptions = currentEditColumn.value.filterOptions || [];

      // 添加筛选处理函数
      updatedColumn.filterOptionValues = null; // 初始时没有选中的筛选值
    } else {
      // 删除筛选相关属性
      delete updatedColumn.filter;
      delete updatedColumn.filterOptions;
      delete updatedColumn.filterOptionValues;
    }

    rawColumns.value[index] = updatedColumn;
  }

  showEditDrawer.value = false;
  currentEditColumn.value = null;
};

// 添加列显示状态变化的处理方法
const handleColumnVisibleChange = (checked: boolean, column: TableColumn) => {
  if (checked) {
    if (!visibleColumns.value.includes(column.key)) {
      visibleColumns.value = [...visibleColumns.value, column.key];
    }
  } else {
    visibleColumns.value = visibleColumns.value.filter(key => key !== column.key);
  }
};

// 添加列搜索相关的响应式变量
const columnSearchText = ref('');

// 添加列搜索的计算属性
const filteredColumns = computed(() => {
  const searchText = columnSearchText.value.toLowerCase().trim();
  if (!searchText) return rawColumns.value;

  return rawColumns.value.filter(column => {
    const title = column.title.toLowerCase();
    const key = column.key.toLowerCase();
    return title.includes(searchText) || key.includes(searchText);
  });
});

// 添加搜索框清空方法
const clearColumnSearch = () => {
  columnSearchText.value = '';
};

// 在 script setup 部分添加以下代码
const formItems = computed(() => {
  const items = searchFields.value
    .filter(field => field.visible)
    .sort((a, b) => a.order - b.order)
    .map(field => ({
      label: field.label,
      key: field.key,
      type: field.type,
      // 使用字段自身的 placeholder,如果没有则使用默认值
      placeholder: field.placeholder || (field.type === 'select' ? `请选择${field.label}` : `请输入${field.label}`),
      defaultValue: field.defaultValue, // 添加默认值
      options: field.options
    }));

  return items;
});

// 修改添加搜索字段的方法
const showAddFieldDrawer = ref(false);
const selectedColumns = ref<string[]>([]);

const confirmAddFields = () => {
  const newFields = selectedColumns.value.map(key => {
    const column = rawColumns.value.find(col => col.key === key);
    const isDateField = column?.key.toLowerCase().includes('time') || column?.key.toLowerCase().includes('date');

    return {
      label: column?.title || '',
      key: column?.key || '',
      type: isDateField ? 'date' : 'input',
      visible: true,
      defaultValue: '',
      placeholder: isDateField ? `请选择${column?.title || ''}` : `请输入${column?.title || ''}`,
      order: searchFields.value.length + 1,
      options: []
    };
  });

  searchFields.value = [...searchFields.value, ...newFields];
  showAddFieldDrawer.value = false;
};

// 添加搜索字段编辑抽屉
const showSearchFieldDrawer = ref(false);

const currentSearchField = ref<SearchField>({
  label: '',
  key: '',
  type: 'input',
  visible: true,
  defaultValue: '',
  placeholder: '请输入占位提示',
  options: [],
  order: 0
});

// 修改 saveSearchField 方法
const saveSearchField = () => {
  const index = searchFields.value.findIndex(field => field.key === currentSearchField.value.key);
  if (index > -1) {
    const oldType = searchFields.value[index].type;
    const newType = currentSearchField.value.type;

    searchFields.value[index] = {
      ...searchFields.value[index],
      ...currentSearchField.value,
      placeholder: currentSearchField.value.placeholder,
      options: currentSearchField.value.type === 'select' ? currentSearchField.value.options : []
    };

    // 如果类型改变为 select，重置对应的表单值为 undefined
    if (oldType !== 'select' && newType === 'select') {
      searchForm.value[currentSearchField.value.key] = undefined;
    }
  }
  showSearchFieldDrawer.value = false;
};

// 添加搜索字段编辑方法
const addSearchField = () => {
  selectedColumns.value = [];
  showAddFieldDrawer.value = true;
};

// 编辑搜索字段
const editSearchField = (field: any) => {
  currentSearchField.value = {
    ...field,
    options: field.options || [] // 确保 options 属性存在
  };
  showSearchFieldDrawer.value = true;
};

// 移除搜索字段
const removeSearchField = (field: any) => {
  searchFields.value = searchFields.value.filter(f => f.key !== field.key);
};

// 更新字段可见性
const updateFieldVisibility = (field: any, visible: boolean) => {
  field.visible = visible;
};

// 获取可选择的列
const availableColumns = computed(() => {
  const existingKeys = searchFields.value.map(f => f.key);
  return rawColumns.value.filter(col => !existingKeys.includes(col.key));
});

// 在 script setup 部分添加以下响应式变量
const newOptionKey = ref('');
const newOptionValue = ref('');

// 添加一个方法来处理添加新选项
const addOption = () => {
  if (!currentSearchField.value.options) {
    currentSearchField.value.options = [];
  }

  if (newOptionKey.value && newOptionValue.value) {
    currentSearchField.value.options.push({
      label: newOptionKey.value,
      value: newOptionValue.value
    });
    // 清空输入
    newOptionKey.value = '';
    newOptionValue.value = '';
  }
};

// 添加删除选项的方法
const removeOption = (index: number) => {
  if (currentSearchField.value.options) {
    currentSearchField.value.options.splice(index, 1);
  }
};

// 添加拖拽排序相关方法
const handleSearchFieldDragStart = (e: DragEvent, field: any) => {
  e.dataTransfer?.setData('text/plain', field.key);
};

const handleSearchFieldDragOver = (e: DragEvent) => {
  e.preventDefault();
};

const handleSearchFieldDrop = (e: DragEvent, targetField: any) => {
  e.preventDefault();
  const sourceKey = e.dataTransfer?.getData('text/plain');
  if (!sourceKey) return;

  const sourceField = searchFields.value.find(f => f.key === sourceKey);
  const targetOrder = targetField.order;

  if (sourceField) {
    // 交换order值
    const sourceOrder = sourceField.order;
    sourceField.order = targetOrder;
    targetField.order = sourceOrder;

    // 重新排序数组
    searchFields.value.sort((a, b) => a.order - b.order);
  }
};

// 添加筛选选项
const addFilterOption = () => {
  if (!currentEditColumn.value) return;

  if (!currentEditColumn.value.filterOptions) {
    currentEditColumn.value.filterOptions = [];
  }

  // 检查是否已存在相同的值，避免重复
  const isDuplicate = currentEditColumn.value.filterOptions.some(option => option.value === newFilterValue.value);

  if (!isDuplicate) {
    currentEditColumn.value.filterOptions.push({
      label: newFilterLabel.value,
      value: newFilterValue.value
    });

    // 清空输入
    newFilterLabel.value = '';
    newFilterValue.value = '';
  } else {
    // 可以在这里添加重复选项的提示
    // alert('该筛选值已存在，请勿重复添加');
  }
};

// 移除筛选选项
const removeFilterOption = (index: number) => {
  if (currentEditColumn.value?.filterOptions) {
    currentEditColumn.value.filterOptions.splice(index, 1);
  }
};

// 从当前数据生成选项
const generateFilterOptions = (column: TableColumn) => {
  if (!column || !tableData.value.length) return;

  // 获取当前列的所有唯一值
  const uniqueValues = new Set<string>();
  const key = column.key;

  tableData.value.forEach(row => {
    let value;

    // 处理嵌套属性 (如 'user.name')
    if (key.includes('.')) {
      const [parentKey, childKey] = key.split('.');
      value = row[parentKey]?.[childKey];
    } else {
      value = row[key];
    }

    // 值存在时添加到集合中
    if (value !== undefined && value !== null) {
      uniqueValues.add(String(value));
    }
  });

  // 将唯一值转换为筛选选项
  const options = Array.from(uniqueValues).map(value => ({
    label: value,
    value
  }));

  // 更新当前编辑列的筛选选项
  if (currentEditColumn.value) {
    currentEditColumn.value.filterOptions = options;
  }

  // 提供用户反馈
  if (options.length > 0) {
    // alert(`成功生成 ${options.length} 个筛选选项!`);
  } else {
    // alert('未能从当前数据中找到任何值，请检查数据是否已加载。');
  }
};
// 数据转换相关的状态

const selectedField = ref('');
const availableFields = computed(() => {
  return rawColumns.value.map((column: TableColumn) => ({
    label: column.title,
    value: column.key
  }));
});
const tagMappings = ref<TagMapping[]>([{ value: '', label: '', color: '' }]);
const transformRules = ref<TransformRule[]>([]);
const transformedData = ref<any[]>([]);

// 添加转换配置存储
const transformConfigurations = ref<Record<string, any>>({});

// 添加获取标签颜色的辅助函数
const getTagColor = (color: string) => {
  const colorMap: Record<string, string> = {
    default: '#909399',
    primary: '#409EFF',
    success: '#67C23A',
    warning: '#E6A23C',
    error: '#F56C6C',
    info: '#909399'
  };

  return colorMap[color] || colorMap.default;
};

// 添加更新列渲染函数的方法
const updateTransformedColumnRenders = () => {
  // 遍历所有列，为有转换配置的列添加自定义渲染函数
  rawColumns.value.forEach(column => {
    const config = transformConfigurations.value[column.key];

    if (config && config.type === 'tag') {
      // 备份原有的render函数(如果有)
      if (!column.__originalRender && column.render) {
        column.__originalRender = column.render;
      }

      // 添加新的render函数，应用标签转换
      column.render = (row, index) => {
        let value;

        // 处理嵌套字段
        if (column.key.includes('.')) {
          const [parentKey, childKey] = column.key.split('.');
          value = row[parentKey]?.[childKey];
        } else {
          value = row[column.key];
        }

        if (value !== undefined && value !== null) {
          const stringValue = String(value);
          const mapping = config.mappings.find((m: any) => String(m.value) === stringValue);

          if (mapping) {
            // 返回标签组件
            return h(
              'span',
              {
                class: `tag tag-${mapping.color || 'default'}`,
                style: {
                  padding: '2px 6px',
                  borderRadius: '4px',
                  backgroundColor: getTagColor(mapping.color),
                  color: '#fff',
                  fontSize: '12px'
                }
              },
              mapping.label
            );
          }
        }

        // 如果没有匹配的映射或值不存在，使用原始渲染或值
        if (column.__originalRender) {
          return column.__originalRender(row, index);
        }
        return value;
      };
    } else if (!config && column.__originalRender) {
      // 如果列没有转换配置但有原始渲染函数，恢复原始渲染
      column.render = column.__originalRender;
      column.__originalRender = undefined;
    }
  });
};

const applyTransformations = () => {
  if (!tableData.value || tableData.value.length === 0) {
    window.$message?.error('没有可转换的数据');
    return;
  }

  try {
    // 不修改原始数据，只提供渲染函数
    // console.log('应用数据转换配置');
    // console.log('转换配置:', transformConfigurations.value);

    // 刷新表格视图
    updateTransformedColumnRenders();

    // window.$message?.success('数据转换成功应用到显示');
  } catch (error: any) {
    // console.error('转换过程中出错:', error);
    window.$message?.error(`转换过程中出错: ${error.message}`);
  }
};

// 数据转换相关的方法
const addTagMapping = () => {
  tagMappings.value.push({ value: '', label: '', color: '' });
};

const removeTagMapping = (index: number) => {
  tagMappings.value.splice(index, 1);
};

const addTransformRule = () => {
  if (!selectedField.value) return;

  // 过滤掉空值映射
  const validMappings = tagMappings.value.filter(mapping => mapping.value !== '' && mapping.label !== '');

  if (validMappings.length === 0) {
    window.$message?.error('请添加至少一个有效的标记映射');
    return;
  }

  // 将转换规则添加到规则列表
  transformRules.value.push({
    field: selectedField.value,
    fieldLabel: availableFields.value.find(f => f.value === selectedField.value)?.label || selectedField.value,
    type: 'tag',
    typeLabel: '转换标记',
    params: { mappings: validMappings }
  });

  // 同时更新转换配置存储
  transformConfigurations.value[selectedField.value] = {
    type: 'tag',
    mappings: validMappings
  };

  // 重置输入
  selectedField.value = '';
  tagMappings.value = [{ value: '', label: '', color: '' }];
};

const removeTransformRule = (index: number) => {
  // 获取要删除的规则
  const removedRule = transformRules.value[index];

  // 从规则列表中删除
  transformRules.value.splice(index, 1);

  // 从转换配置中删除
  if (removedRule && removedRule.field) {
    transformConfigurations.value[removedRule.field] = undefined;
  }

  // 刷新表格以移除转换效果
  applyTransformations();
};

// 添加恢复原始数据的方法
const restoreOriginalData = () => {
  // 恢复所有列的原始渲染函数
  rawColumns.value.forEach(column => {
    if ((column as any).__originalRender) {
      column.render = (column as any).__originalRender;
      (column as any).__originalRender = undefined;
    }
  });

  // 清空转换配置
  transformConfigurations.value = {};
  transformRules.value = [];

  window.$message?.success('已恢复原始数据显示');
};

// 添加一个标志来追踪数据是否已经准备好
const isDataReady = ref(false);

// 监听数据变化
watch([tableData, rawColumns], ([newTableData, newRawColumns]) => {
  if (newTableData.length > 0 && newRawColumns.length > 0) {
    // console.log('数据已准备好');
    isDataReady.value = true;
  }
});

// 监听数据准备状态 - 不再自动加载配置
watch(isDataReady, newValue => {
  if (newValue) {
    // console.log('数据已准备就绪');
    // 移除这里的配置加载，避免重复加载
    // loadTableSettings();
  }
});

onMounted(() => {
  // console.log(props.uiConfig);
  console.log('🔧 检查全局工具库:', {
    axios: Boolean((window as any).$axios),
    echarts: Boolean((window as any).$echarts),
    WangEditor: Boolean((window as any).$WangEditor)
  });

  // 在组件挂载时就确保配置加载完成
  fetchData();
  Promise.resolve()
    .then(() => fetchData())
    .then(() => {
      nextTick(() => {
        // console.log('组件挂载完成，初始化配置');
        // getAllTableSettings();
      });
    });
});

onActivated(() => {
  // console.log('组件被激活');
  fetchData();
});

// 提供共享状态和方法给子组件
provide('tableState', {
  tableData,
  loading,
  columns,
  pagination,
  rawColumns,
  visibleColumns,
  tableSize,
  showBorder,
  showStripe,
  tableHeight,
  tableScrollWidth,
  searchForm,
  searchFields,
  formItems,
  isExpanded,
  enableSingleSelect,
  filteredColumns,
  showSettingDrawer,
  showEditDrawer,
  showSearchFieldDrawer,
  showAddFieldDrawer,
  currentEditColumn,
  currentSearchField,
  activeTab,
  columnSearchText,
  selectedColumns,
  newFilterLabel,
  newFilterValue,
  newOptionKey,
  newOptionValue,
  isIndexColumn,
  availableColumns,
  uiConfig: props.uiConfig,
  tagMappings,
  transformRules,
  transformedData,
  selectedField,
  availableFields,
  transformConfigurations
});

// 提供方法
provide('tableMethods', {
  fetchData,
  handleSearch,
  resetSearch,
  handlePageChange,
  handlePageSizeChange,
  handleSorterChange,
  handleFiltersChange,
  handleEditColumn,
  saveColumnEdit,
  handleColumnVisibleChange,
  clearColumnSearch,
  handleDragStart,
  handleDragOver,
  handleDrop,
  addSearchField,
  editSearchField,
  removeSearchField,
  updateFieldVisibility,
  confirmAddFields,
  saveSearchField,
  addOption,
  removeOption,
  handleSearchFieldDragStart,
  handleSearchFieldDragOver,
  handleSearchFieldDrop,
  addFilterOption,
  removeFilterOption,
  generateFilterOptions,
  formatDate,
  addTagMapping,
  removeTagMapping,
  addTransformRule,
  removeTransformRule,
  applyTransformations,
  restoreOriginalData,
  updateTransformedColumnRenders,
  handleCreate,
  handleDeleteRefresh
});
</script>

<template>
  <div class="table-container">
    <!-- 搜索表单组件 -->
    <SearchForm></SearchForm>

    <!-- 数据表格组件 -->
    <DataTable></DataTable>

    <!-- 表格设置抽屉组件 -->
    <TableSettingsDrawer ref="tableSettingsDrawerRef"></TableSettingsDrawer>

    <!-- 列编辑抽屉 -->
    <ColumnEditDrawer></ColumnEditDrawer>

    <!-- 搜索字段编辑抽屉 -->
    <SearchFieldEditDrawer></SearchFieldEditDrawer>

    <!-- 添加字段抽屉 -->
    <AddFieldDrawer></AddFieldDrawer>

    <!-- 新建弹窗 -->
    <CreateDialog ref="createDialogRef"></CreateDialog>
  </div>
</template>

<style scoped>
.table-container {
  width: 100%;
  position: relative;
}
</style>
