<script setup lang="ts">
import { defineExpose, inject, ref } from 'vue';
import TableBasicSettings from './TableBasicSettings.vue';
import ColumnSettings from './ColumnSettings.vue';
import SearchFieldSettings from './SearchFieldSettings.vue';
import DataTransform from './DataTransform.vue';
defineOptions({
  name: 'TableSettingsDrawer'
});

// 通过window对象使用axios
const axios = (window as any).$axios; // 使用全局注入的axios实例

// 从主组件注入状态和方法
const tableState: any = inject('tableState');
const tableMethods: any = inject('tableMethods');

const {
  showSettingDrawer,
  activeTab,
  tableSize,
  showBorder,
  showStripe,
  enableSingleSelect,
  tableHeight,
  tableScrollWidth,
  visibleColumns,
  searchFields,
  formItems,
  uiConfig
} = tableState;

// 获取所有设置信息
const getAllSettings = () => {
  // 获取列编辑配置
  const columnConfigs = tableState.rawColumns.value.map((column: any, index: number) => ({
    key: column.key,
    title: column.title,
    titleAlign: column.titleAlign,
    align: column.align,
    sortable: column.sortable,
    filter: column.filter,
    filterOptions: column.filterOptions,
    ellipsis: column.ellipsis,
    width: column.width,
    minWidth: column.minWidth,
    maxWidth: column.maxWidth,
    fixed: column.fixed,
    resizable: column.resizable,
    order: index // 保存列的排序顺序
  }));

  // 获取搜索字段配置
  const searchFieldConfigs = tableState.searchFields.value.map((field: any) => ({
    key: field.key,
    label: field.label,
    type: field.type,
    visible: field.visible,
    defaultValue: field.defaultValue,
    placeholder: field.placeholder,
    options: field.options,
    order: field.order
  }));

  // 获取数据转换配置
  const transformConfigs = {
    // 保存转换规则
    transformRules: tableState.transformRules.value,
    // 保存标签映射
    tagMappings: tableState.tagMappings.value,
    // 保存字段转换配置
    transformConfigurations: tableState.transformConfigurations.value,
    // 保存列的自定义渲染函数配置
    columnRenderConfigs: tableState.rawColumns.value
      // eslint-disable-next-line no-underscore-dangle
      .filter((column: any) => column.__originalRender)
      .map((column: any) => ({
        key: column.key,
        hasCustomRender: true
      }))
  };

  return {
    // 表格基本设置
    tableSettings: {
      tableSize: tableSize.value,
      showBorder: showBorder.value,
      showStripe: showStripe.value,
      enableSingleSelect: enableSingleSelect.value,
      tableHeight: tableHeight.value,
      tableScrollWidth: tableScrollWidth.value
    },
    // 列设置
    columnSettings: {
      visibleColumns: visibleColumns.value,
      columnConfigs,
      columnOrder: tableState.rawColumns.value.map((col: any) => col.key) // 保存列的顺序
    },
    // 搜索设置
    searchSettings: {
      searchFields: searchFields.value,
      formItems: formItems.value,
      searchFieldConfigs
    },
    // 数据转换设置
    transformSettings: transformConfigs
  };
};

// 添加应用配置的方法
const applySettings = (settings: any) => {
  // 应用表格基本设置
  if (settings.tableSettings) {
    tableSize.value = settings.tableSettings.tableSize;
    showBorder.value = settings.tableSettings.showBorder;
    showStripe.value = settings.tableSettings.showStripe;
    enableSingleSelect.value = settings.tableSettings.enableSingleSelect;
    tableHeight.value = settings.tableSettings.tableHeight;
    tableScrollWidth.value = settings.tableSettings.tableScrollWidth;
  }

  // 应用列设置
  if (settings.columnSettings) {
    visibleColumns.value = settings.columnSettings.visibleColumns;

    // 应用列排序
    if (settings.columnSettings.columnOrder) {
      // 根据保存的顺序重新排列列
      const orderedColumns: any[] = [];
      settings.columnSettings.columnOrder.forEach((key: any) => {
        const column = tableState.rawColumns.value.find((col: any) => col.key === key);
        if (column) {
          orderedColumns.push(column);
        }
      });

      // 添加可能新增的列（不在保存的顺序中的列）
      tableState.rawColumns.value.forEach((column: any) => {
        if (!settings.columnSettings.columnOrder.includes(column.key)) {
          orderedColumns.push(column);
        }
      });

      // 更新列配置
      tableState.rawColumns.value = orderedColumns;
    }

    // 应用列配置
    if (settings.columnSettings.columnConfigs) {
      tableState.rawColumns.value = tableState.rawColumns.value.map((column: any) => {
        const config = settings.columnSettings.columnConfigs.find((c: any) => c.key === column.key);
        if (config) {
          return {
            ...column,
            ...config
          };
        }
        return column;
      });
    }
  }

  // 应用搜索设置
  if (settings.searchSettings) {
    searchFields.value = settings.searchSettings.searchFields;
    formItems.value = settings.searchSettings.formItems;
    // 应用搜索字段配置
    if (settings.searchSettings.searchFieldConfigs) {
      tableState.searchFields.value = settings.searchSettings.searchFieldConfigs;
    }
  }

  // 应用数据转换设置
  if (settings.transformSettings) {
    // 恢复转换规则
    if (settings.transformSettings.transformRules) {
      tableState.transformRules.value = settings.transformSettings.transformRules;
    }
    // 恢复标签映射
    if (settings.transformSettings.tagMappings) {
      tableState.tagMappings.value = settings.transformSettings.tagMappings;
    }
    // 恢复字段转换配置
    if (settings.transformSettings.transformConfigurations) {
      tableState.transformConfigurations.value = settings.transformSettings.transformConfigurations;
    }

    // 恢复列的自定义渲染配置
    if (settings.transformSettings.columnRenderConfigs) {
      settings.transformSettings.columnRenderConfigs.forEach((config: any) => {
        const column = tableState.rawColumns.value.find((col: any) => col.key === config.key);
        if (column && config.hasCustomRender) {
          // 使用 tableMethods 中的方法更新列渲染函数
          tableMethods.updateTransformedColumnRenders();
        }
      });
    }

    // 如果有转换规则，自动应用转换
    if (settings.transformSettings.transformRules?.length > 0) {
      tableMethods.applyTransformations();
    }
  }
};
const settings = ref({});
// 获取配置信息的方法
const handleGetSettings = async () => {
  try {
    // 在请求前检查必要的配置参数
    if (!uiConfig.GetUrl || !uiConfig.Type) {
      // console.warn('缺少必要的配置参数，无法获取配置');
      return;
    }

    const response = await axios.post(uiConfig.GetUrl, {
      Type: uiConfig.Type,
      InternalCode: uiConfig.InternalCode,
      IsDefault: uiConfig.IsDefault
    });

    if (response.data?.Parameters) {
      settings.value = JSON.parse(response.data.Parameters);
      // console.log('获取到的配置信息:', settings.value);
      applySettings(settings.value);
      // window.$message?.success('配置信息获取成功');
    } else {
      // console.log('没有获取到配置参数，使用默认配置');
    }
  } catch (error) {
    // console.error('获取配置失败:', error);
    window.$message?.error('获取配置失败');
  }
};

// 保存配置信息的方法
const handleSetSettings = async () => {
  try {
    const response = await axios.post(uiConfig.SetUrl, {
      Type: uiConfig.Type,
      InternalCode: uiConfig.InternalCode,
      IsDefault: uiConfig.IsDefault,
      Parameters: JSON.stringify(getAllSettings())
    });

    if (response.data) {
      // 应用配置
      applySettings(settings.value);
      window.$message?.success('配置信息保存成功');
      handleGetSettings();
    }
  } catch (error) {
    // console.error('保存配置失败:', error);
    window.$message?.error('保存配置失败');
  }
};

// 导出方法供外部使用
defineExpose({
  getAllSettings,
  applySettings,
  handleGetSettings
});
</script>

<template>
  <NDrawer v-model:show="showSettingDrawer" :width="550" placement="right">
    <NDrawerContent title="表格设置">
      <div class="settings-container">
        <NTabs v-model:value="activeTab" placement="left" type="line" class="settings-tabs">
          <NTabPane name="table" tab="表格设置">
            <div class="tab-content">
              <TableBasicSettings />
            </div>
          </NTabPane>

          <NTabPane name="columns" tab="列设置">
            <div class="tab-content">
              <ColumnSettings />
            </div>
          </NTabPane>

          <NTabPane name="buttons" tab="搜索配置">
            <div class="tab-content">
              <SearchFieldSettings />
            </div>
          </NTabPane>

          <NTabPane name="transform" tab="数据转换">
            <div class="tab-content">
              <DataTransform />
            </div>
          </NTabPane>
        </NTabs>
      </div>
      <div style="position: fixed; top: 5px; right: 5px">
        <NButton type="primary" style="margin-right: 5px" @click="handleGetSettings">获取配置信息</NButton>
        <NButton type="primary" @click="handleSetSettings">应用配置信息</NButton>
      </div>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped>
.settings-container {
  height: 80%;
  display: flex;
}

.settings-tabs {
  flex: 1;
  height: 100%;
}

.tab-content {
  padding: 16px 0;
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.n-tabs) {
  height: 100%;
}

:deep(.n-tabs-nav) {
  width: 100px;
  border-right: 1px solid var(--n-border-color);
}

:deep(.n-tabs-nav__scroll-container) {
  padding: 8px 0;
}

:deep(.n-tabs-tab) {
  justify-content: flex-start;
  padding: 12px 16px;
}

:deep(.n-tabs-tab-wrapper) {
  padding: 0;
}

:deep(.n-tabs-wrapper) {
  flex: 1;
  height: 100%;
}

:deep(.n-tab-pane) {
  padding: 0;
  height: 100%;
}

:deep(.n-drawer-content) {
  padding: 0;
}

:deep(.n-drawer-header) {
  padding: 16px;
  border-bottom: 1px solid var(--n-border-color);
}

:deep(.n-drawer-header__main) {
  font-size: 16px;
  font-weight: 500;
}
</style>
