<script setup lang="ts">
import { computed, h, inject, onMounted, watch } from 'vue';

// 从主组件注入状态和方法
const tableState: any = inject('tableState');
const tableMethods: any = inject('tableMethods');
// 通过window对象使用axios和dialog
const axios = (window as any).$axios;
const dialog = (window as any).$dialog;
const message = (window as any).$message;

// 获取主题状态
const themeStore = (window as any).$themeStore;
const isDarkMode = computed(() => themeStore?.darkMode || false);
const borderColor = computed(() => (isDarkMode.value ? '#303030' : '#ffffff'));

const {
  tableData,
  columns,
  loading,
  pagination,
  tableSize,
  showBorder,
  showStripe,
  tableHeight,
  tableScrollWidth,
  uiConfig
} = tableState;

const { handlePageChange, handlePageSizeChange, handleSorterChange, handleFiltersChange, fetchData, handleCreate } =
  tableMethods;

// const handleDeleteRefresh = tableMethods.handleDeleteRefresh;

// 监听数据变化
watch(
  () => tableData.value,
  () => {
    // console.log('表格数据已更新');
  },
  { deep: true }
);

// 组件挂载后检查数据
onMounted(() => {
  // 初始化完成
});

// 处理列配置，为表格列添加标签渲染支持
const processedColumns = computed(() => {
  // 处理原始列配置
  const baseColumns = columns.value.map((col: any) => {
    // 如果已经有自定义render函数则保留
    if (col.render) return col;

    // 添加通用的render函数检查是否是标签类型
    const newCol = { ...col };

    // 为列添加渲染函数
    newCol.render = (row: any) => {
      const value = row[col.key];
      // 检查是否是标签类型
      // eslint-disable-next-line no-underscore-dangle
      if (value && typeof value === 'object' && (value as any).__isTag) {
        // console.log(`渲染标签：列=${col.key}, 值=${value.value}, 标签=${value.label}, 颜色=${value.color}`);

        return h('div', { class: 'tag-container' }, [
          h(
            'div',
            {
              class: `table-tag ${value.color}`,
              style: {
                display: 'inline-block',
                padding: '0 7px',
                fontSize: '12px',
                lineHeight: '20px',
                borderRadius: '3px',
                margin: 0,
                backgroundColor: getTagColor(value.color),
                color: '#fff'
              }
            },
            value.label
          )
        ]);
      }
      // 普通值直接返回
      return value;
    };

    return newCol;
  });

  // 添加操作列
  const actionColumn = {
    title: '操作',
    key: 'actions',
    fixed: 'right',
    width: 120,
    render: (row: any) => {
      return h(
        'div',
        {
          style: `display: flex; align-items: center; justify-content: center; gap: 4px; background-color: ${
            borderColor.value
          }; padding: 4px; flex-direction: row; flex-wrap: nowrap; width: 70px;`
        },
        [
          // 编辑按钮 - 使用用户提供的 SVG 图标
          h(
            'div',
            {
              style:
                'display: inline-flex; align-items: center; justify-content: center; cursor: pointer; margin-right: 8px; transition: transform 0.2s ease; flex-shrink: 0;',
              onClick: () => {
                console.log('编辑', row);
                // 使用handleCreate方法处理编辑操作
                if (handleCreate) {
                  handleCreate(row);
                } else {
                  console.warn('handleCreate方法未定义');
                }
              }
            },
            h(
              'svg',
              {
                xmlns: 'http://www.w3.org/2000/svg',
                width: '16',
                height: '16',
                viewBox: '0 0 32 32',
                fill: 'none',
                stroke: 'currentColor'
              },
              [
                h('path', { d: 'M2 26h28v2H2z', fill: 'currentColor' }),
                h('path', {
                  d: 'M25.4 9c.8-.8.8-2 0-2.8l-3.6-3.6c-.8-.8-2-.8-2.8 0l-15 15V24h6.4l15-15zm-5-5L24 7.6l-3 3L17.4 7l3-3zM6 22v-3.6l10-10l3.6 3.6l-10 10H6z',
                  fill: 'currentColor'
                })
              ]
            )
          ),

          // 删除按钮 - 使用 SVG 图标
          h(
            'div',
            {
              style:
                'display: inline-flex; align-items: center; justify-content: center; cursor: pointer; transition: transform 0.2s ease; flex-shrink: 0;',
              onClick: () => {
                // 创建确认对话框
                dialog?.warning({
                  title: '确认删除',
                  content: '确定要删除这条数据吗？',
                  positiveText: '确定',
                  negativeText: '取消',
                  onPositiveClick: async () => {
                    try {
                      // 准备删除请求的参数
                      const Kvids = [row.Kvid];

                      // 发送删除请求
                      const response = await axios.post(uiConfig.InitDelete, { Kvids });

                      if (response.data) {
                        message?.success('删除成功');
                        // 重新加载数据
                        fetchData();
                      } else {
                        message?.error('删除失败');
                      }
                    } catch (error: any) {
                      // console.error('删除失败:', error);
                      message?.error(`删除失败: ${error.message || '未知错误'}`);
                    }
                  }
                });
              }
            },
            h(
              'svg',
              {
                xmlns: 'http://www.w3.org/2000/svg',
                width: '16',
                height: '16',
                viewBox: '0 0 20 20',
                fill: 'none',
                stroke: 'currentColor'
              },
              [
                h('path', {
                  d: 'M11.5 4a1.5 1.5 0 0 0-3 0h-1a2.5 2.5 0 0 1 5 0H17a.5.5 0 0 1 0 1h-.554L15.15 16.23A2 2 0 0 1 13.163 18H6.837a2 2 0 0 1-1.987-1.77L3.553 5H3a.5.5 0 0 1-.492-.41L2.5 4.5A.5.5 0 0 1 3 4h8.5zm3.938 1H4.561l1.282 11.115a1 1 0 0 0 .994.885h6.326a1 1 0 0 0 .993-.885L15.438 5zM8.5 7.5c.245 0 .45.155.492.359L9 7.938v6.125c0 .241-.224.437-.5.437c-.245 0-.45-.155-.492-.359L8 14.062V7.939c0-.242.224-.438.5-.438zm3 0c.245 0 .45.155.492.359l.008.079v6.125c0 .241-.224.437-.5.437c-.245 0-.45-.155-.492-.359L11 14.062V7.939c0-.242.224-.438.5-.438z',
                  fill: 'currentColor'
                })
              ]
            )
          )
        ]
      );
    }
  };

  return [...baseColumns, actionColumn];
});

// 根据标签类型获取颜色
function getTagColor(type: string) {
  switch (type) {
    case 'default':
      return '#f0f0f0';
    case 'primary':
      return '#2080f0';
    case 'info':
      return '#909399';
    case 'success':
      return '#18a058';
    case 'warning':
      return '#f0a020';
    case 'error':
      return '#d03050';
    default:
      return '#f0f0f0';
  }
}
</script>

<template>
  <NCard class="search-card" :bordered="false" content-style="padding: 0 12px 8px;margin-top:10px">
    <NDataTable
      ref="table"
      remote
      :columns="processedColumns"
      :data="tableData"
      :loading="loading"
      :pagination="{
        ...pagination,
        onChange: handlePageChange,
        onUpdatePageSize: handlePageSizeChange
      }"
      :row-key="row => row.Kvid"
      :max-height="tableHeight"
      :scroll-x="tableScrollWidth"
      :single-line="!showBorder"
      :striped="showStripe"
      :size="tableSize"
      @update:sorter="handleSorterChange"
      @update:filters="handleFiltersChange"
    >
      <template #loading>
        <NSpace vertical justify="center" class="py-4">
          <NSpin size="medium"></NSpin>
          <NText depth="3">正在加载数据...</NText>
        </NSpace>
      </template>

      <template #empty>
        <NEmpty description="暂无数据">
          <template #extra>
            <NButton size="small" @click="fetchData">重新加载</NButton>
          </template>
        </NEmpty>
      </template>
    </NDataTable>
  </NCard>
</template>

<style scoped>
.search-card {
  margin-bottom: 8px;
}

.tag-container {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

:deep(.n-data-table) {
  --n-merged-th-color: var(--n-table-color);
  --n-merged-td-color: var(--n-table-color);
}

:deep(.n-data-table-base-table-body) {
  overflow: auto !important;
}

:deep(.n-data-table-table) {
  min-width: 100%;
}

/*:deep(.n-data-table__pagination) {*/
/*  position: fixed;*/
/*  bottom: 12px;*/
/*  right: 12px;*/
/*}*/

/* 优化分页器页码选择器的样式 */
:deep(.n-pagination .n-pagination-size-picker) {
  width: 84px !important;
}

:deep(.n-pagination .n-pagination-size-picker .n-base-selection) {
  width: 84px !important;
}

/* 优化分页器整体布局 */
:deep(.n-pagination) {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 确保总条数显示正常 */
:deep(.n-pagination-prefix) {
  margin-right: auto;
  white-space: nowrap;
}

/* 优化表格滚动相关样式 */
:deep(.n-data-table-base-table) {
  width: 100%;
}

:deep(.n-data-table-base-table-body) {
  overflow-x: auto !important;
}

:deep(.n-scrollbar-container) {
  min-width: 100%;
}

/* 图标按钮样式 */
.icon-button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: transform 0.2s ease;
  flex-shrink: 0;
}

.icon-button:hover {
  transform: scale(1.2);
}

:deep(.n-data-table .action-buttons .n-button) {
  min-width: 60px;
  cursor: pointer !important;
}

/* 确保操作列固定在右侧 */
:deep(.n-data-table-td--fixed-right) {
  background-color: v-bind(borderColor) !important;
  right: 0px;
}

:deep(.n-data-table-th--fixed-right) {
  background-color: v-bind(borderColor) !important;
  right: 0px;
}

/* 直接针对最后一列的单元格设置样式 */
:deep(.n-data-table-td--last-col) {
  background-color: v-bind(borderColor) !important;
}
</style>
