<template>
  <div style="padding: 10px 0; overflow: hidden">
    <div class="board-table-container">
      <!-- Table 区域 -->
      <div class="table-section" v-if="tableConfig && tableData.length > 0">
        <div class="table__content">
          <!-- 表头 -->
          <div class="table__content_label" :class="`table__content_label_${tableConfig.type}`">
            <!-- 单选框列占位（固定宽度） -->
            <div v-if="showRadio" :style="{ width: radioColumnWidth }" class="label-t table__content__list_item_radio">
              <!-- 表头单选框位置留空 -->
            </div>
            <!-- 数据列头 -->
            <div class="label-t" v-for="(item, index) in tableColumns" :key="`header-${index}`" :style="{ flexBasis: dataColumnFlexBasis }">
              {{ item.name }}
            </div>
          </div>
          <!-- 表格内容 -->
          <div class="table__content_list" :class="`table__content_list_${tableConfig.type}`">
            <div
              class="table__content_list_row"
              v-for="(row, rowIndex) in tableData"
              :key="`row-${rowIndex}`"
              :class="{ 'active-row': selectedRowIndex === rowIndex }"
              @click="handleRowClick(rowIndex)"
            >
              <!-- 第一列：单选框（固定宽度） -->
              <div v-if="showRadio" :style="{ width: radioColumnWidth }" class="table__content__list_item_radio">
                <input type="radio" :name="radioGroupName" :checked="selectedRowIndex === rowIndex" @click.stop="handleRowClick(rowIndex)" />
              </div>
              <!-- 其他列（平分剩余空间） -->
              <div
                v-for="(col, colIndex) in tableColumns"
                :key="`cell-${rowIndex}-${colIndex}`"
                :style="{ flexBasis: dataColumnFlexBasis }"
                :class="`table__content__list_item_${tableConfig.type}`"
              >
                <!-- <slot :name="col.prop" :scope="row">
                  <span>{{ getter(row, col.prop) }}</span>
                </slot> -->
                <slot :name="col.prop" :scope="row">
                  <component :is="renderCellComponent(row, col)" />
                </slot>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Board 区域 - 修改为单选切换模式 -->
      <div class="board-section">
        <!-- 1. Board 标题单选框组 -->
        <div class="board-tab-container" v-if="boardConfigList.length > 1">
          <div
            class="board-tab-item"
            v-for="(cfg, index) in boardConfigList"
            :key="`tab-${index}`"
            :class="{ active: selectedBoardIndex === index }"
            @click="selectedBoardIndex = index"
          >
            {{ cfg.title || `Board ${index + 1}` }}
          </div>
        </div>

        <!-- 如果只有一个 board，直接显示标题（可选，或者隐藏标题） -->
        <div class="board-title" v-else-if="boardConfigList.length === 1 && boardConfigList[0].title">
          <div class="board-title-text">{{ boardConfigList[0].title }}</div>
        </div>

        <!-- 2. 单个 Board 内容展示区 -->
        <div class="board-list" :class="{ 'overflow-y-auto': boardOverflow }" v-if="currentBoardConfig">
          <template v-for="(item, itemIndex) in getCurrentBoardItems()" :key="`board-item-${itemIndex}`">
            <Tooltip v-if="item.tooltip">
              <template #title>{{ item!.tooltip }}</template>
              <MiniBoard
                :label="item.label"
                :value="item.value as string"
                :layout="currentBoardConfig.layout || 'val-top'"
                :type="currentBoardConfig.type || 'D'"
              />
            </Tooltip>
            <MiniBoard
              v-else
              :label="item.label"
              :value="item.value as string"
              :layout="currentBoardConfig.layout || 'val-top'"
              :type="currentBoardConfig.type || 'D'"
            />
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, watch, onMounted, h } from 'vue';
  import { get, isNil } from 'lodash-es';
  import MiniBoard from '../detail/MiniBoard.vue';
  import { StatusColorEnum } from '/@/enums/jeecgEnum';
  import { Tooltip } from 'ant-design-vue';
  import { getFormattedText } from '../hooks/helper.js';

  interface BoardItem {
    label: string;
    value: string | number;
    tooltip?: string;
  }

  interface TableColumn {
    name: string;
    prop: string;
  }

  interface BoardConfig {
    type?: string;
    layout?: string;
    title?: string;
    readFrom?: string;
    items?: BoardItem[];
  }

  interface TableConfig {
    type?: string;
    columns?: TableColumn[];
    readFrom?: string;
  }

  const props = withDefaults(
    defineProps<{
      boardConfig?: BoardConfig;
      boardConfigs?: BoardConfig[];
      tableConfig?: TableConfig;
      tableData?: any[];
      showRadio?: boolean;
      defaultValue?: string;
      radioWidth?: number; // 单选框列宽度
      boardOverflow?: boolean;
    }>(),
    {
      showRadio: false,
      defaultValue: '-',
      radioWidth: 40, // 默认 40px
      tableData: () => [],
      boardConfig: () => ({}),
      boardConfigs: () => [],
      tableConfig: () => ({}),
    }
  );

  // 当前选中的行索引
  const selectedRowIndex = ref<number>(0);
  // 当前选中的 Board 索引
  const selectedBoardIndex = ref<number>(0);

  const uniqueId = ref(`bt-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`);
  const radioGroupName = computed(() => `board-table-radio-${uniqueId.value}`);

  // 处理后的 board 数据
  const boardItemsList = ref<BoardItem[][]>([]);

  // board 配置列表（兼容单个 boardConfig 和多个 boardConfigs）
  const boardConfigList = computed(() => {
    if (props.boardConfigs && props.boardConfigs.length > 0) {
      return props.boardConfigs;
    }
    if (props.boardConfig && Object.keys(props.boardConfig).length > 0) {
      return [props.boardConfig];
    }
    return [];
  });

  // 当前激活的 Board 配置
  const currentBoardConfig = computed(() => {
    return boardConfigList.value[selectedBoardIndex.value] || null;
  });

  // 单选框列固定宽度
  const radioColumnWidth = computed(() => {
    return `${props.radioWidth}px`;
  });

  // 数据列平分剩余空间
  const dataColumnFlexBasis = computed(() => {
    const columnCount = props.tableConfig?.columns?.length || 1;
    return Math.fround(100 / columnCount) + '%';
  });

  // 表格列
  const tableColumns = computed(() => {
    return props.tableConfig?.columns || [];
  });

  // 获取表格数据值
  function getter(o: any, p: string) {
    const d = get(o, p);
    return isNil(d) ? props.defaultValue : d === '' ? props.defaultValue : d;
  }

  // 获取当前选中 Board 的 items
  function getCurrentBoardItems() {
    if (!currentBoardConfig.value) return [];
    return boardItemsList.value[selectedBoardIndex.value] || [];
  }

  function updateBoardData(rowData: any) {
    if (!rowData) return;

    // 重新计算所有 board 的数据，确保切换时数据是最新的
    boardItemsList.value = boardConfigList.value.map((boardCfg) => {
      if (!boardCfg?.items) return [];

      return boardCfg.items.map((item) => {
        return {
          label: item.label,
          value: getFormattedText(rowData, String(item.value)),
          tooltip: getFormattedText(rowData, item.tooltip, {}, ''),
        };
      });
    });
  }

  // 处理行点击
  function handleRowClick(index: number) {
    if (selectedRowIndex.value === index) return;

    selectedRowIndex.value = index;
    const rowData = props.tableData[index];

    // 自动更新 board 数据
    updateBoardData(rowData);
  }

  // 监听选中行变化，自动更新 board
  watch(selectedRowIndex, (newIndex) => {
    if (props.tableData[newIndex]) {
      updateBoardData(props.tableData[newIndex]);
    }
  });

  // 在 script setup 中添加
  const riskMap = {
    '1': '低风险',
    '2': '一般风险',
    '3': '较高风险',
    '4': '高风险',
  };
  const riskColorMap = {
    '1': StatusColorEnum.blue, // 蓝
    '2': StatusColorEnum.yellow, // 黄
    '3': StatusColorEnum.gold, // 金
    '4': StatusColorEnum.red, // 红
  };

  // 修改 getter 或创建一个专门的渲染函数
  const renderCellComponent = (row: any, col: TableColumn) => {
    return {
      render() {
        const value = getter(row, col.prop);
        if (col.prop === 'alarmLevel') {
          const level = String(value);
          const text = riskMap[level] || value;
          const color = riskColorMap[level] || StatusColorEnum.blue;
          return h('span', { style: { color } }, text);
        }
        return h('span', {}, value);
      },
    };
  };

  // 监听 tableData 变化，重置选中状态
  watch(
    () => props.tableData,
    (newData) => {
      if (newData && newData.length > 0) {
        selectedRowIndex.value = 0;
        updateBoardData(newData[0]);
      }
    },
    { immediate: true }
  );

  // 初始化时加载第一行数据
  onMounted(() => {
    if (props.tableData && props.tableData.length > 0) {
      updateBoardData(props.tableData[0]);
    }
  });
</script>

<style lang="less" scoped>
  @import '/@/design/theme.less';

  @font-face {
    font-family: 'douyuFont';
    src: url('/@/assets/font/douyuFont.otf');
  }

  .board-table-container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    overflow: hidden;
    border: 2px dashed #0070ff;
    border-radius: 10px;
    padding: 10px 5px;
  }

  .board-section {
    height: 70%;
    flex: none;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .board-tab-container {
      display: flex;
      background-color: #c1dbfd;
      overflow: hidden;
    }

    .board-tab-item {
      padding: 8px 12px;
      font-size: 14px;
      color: #333;
      cursor: pointer;
      border: none;
      background-color: transparent;
      transition: all 0.2s ease;

      &:hover {
        background-color: #d0edff;
      }
    }

    .board-tab-item.active {
      background-color: #a2c2fa;
      color: black;
    }
    .board-title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      height: 25px;
      // background: var(--image-module-title) no-repeat;
      // background-size: cover;
      padding-left: 10px;
      .board-title-text {
        color: #103d82;
        font-size: 16px;
        font-style: normal;
        font-family: 'Microsoft YaHei';
        font-weight: 700;
        margin-top: -10px;
      }
    }

    .board-list {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-around;
      flex: 1;
      // overflow-y: hidden;
    }
    :deep(.mini-board) {
      margin-bottom: 10px;
    }
  }

  .table-section {
    height: 30%;
    flex: none;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }

  .table__content {
    --image-content-label-A: url('/@/assets/images/sealedGoaf/configurable/table/table-label-A.png');
    --image-content-list-active-A: url('/@/assets/images/sealedGoaf/configurable/table/table-list-active-A.png');

    height: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 5px 0;

    .table__content_label {
      width: 400px;
      height: 32px;
      display: flex;
      justify-content: space-around;
      align-items: center;
      .label-t {
        text-align: center;
        font-size: 14px;
      }
    }

    .table__content_list {
      height: calc(100% - 32px);
      width: 400px;
      display: flex;
      flex-direction: column;
      padding: 5px 0;
      box-sizing: border-box;
      overflow-y: auto;
      .table__content_list_row {
        width: 100%;
        height: 40px;
        min-height: 40px;
        flex-shrink: 0;
        display: flex;
        justify-content: space-around;
        align-items: center;
        color: #fff;
        cursor: pointer;
        span {
          display: inline-block;
          text-align: center;
        }
      }
      .active-row {
        background-image: var(--image-content-list-active-A);
        background-size: 100% 100%;
        background-repeat: no-repeat;
      }
    }

    .table__content_label_A {
      background-image: var(--image-content-label-A);
      background-size: 100% 100%;
      background-repeat: no-repeat;
      color: #000000;
      width: 100%;
      padding-left: 10px;
    }

    .table__content_list_A {
      width: 100%;
      padding-left: 10px;
      font-weight: bold;
      font-size: 28px;
    }
    /* 第一个子元素：黑色 */
    .table__content_list_row .table__content__list_item_A:nth-child(1) {
      font-size: 14px;
      text-align: left;
      color: #000000;
    }

    /* 第二个子元素：蓝色 */
    .table__content_list_row .table__content__list_item_A:nth-child(2) {
      color: #0052cc;
    }

    /* 第三个子元素：黄色 */
    .table__content_list_row .table__content__list_item_A:nth-child(3) {
      color: #b39f01;
    }

    /* 第四个子元素：橙色 */
    .table__content_list_row .table__content__list_item_A:nth-child(4) {
      color: #e6a23d;
    }

    /* 第五个子元素：红色 */
    .table__content_list_row .table__content__list_item_A:nth-child(5) {
      color: #c45656;
    }

    .table__content_label_B {
      background-image: var(--image-content-label-A);
      background-size: 100% 100%;
      background-repeat: no-repeat;
      color: #000000;
      width: 100%;
      padding-left: 10px;
    }

    .table__content_list_B {
      width: 100%;
      padding-left: 10px;
      font-weight: bold;
      font-size: 28px;
    }
    /* 第一个子元素：黑色 */
    .table__content_list_row .table__content__list_item_B:nth-child(1) {
      font-size: 14px;
      text-align: left;
      color: #000000;
    }

    /* 第二个子元素：蓝色 */
    .table__content_list_row .table__content__list_item_B:nth-child(2) {
      color: #0052cc;
    }

    /* 第三个子元素：绿色 */
    .table__content_list_row .table__content__list_item_B:nth-child(3) {
      color: #4caf50;
    }

    /* 第四个子元素：橙色 */
    .table__content_list_row .table__content__list_item_B:nth-child(4) {
      color: #c97800;
    }

    /* 第五个子元素：红色 */
    .table__content_list_row .table__content__list_item_B:nth-child(5) {
      color: #c45656;
    }
  }

  .table__content_label_C {
    background-image: var(--image-content-label-A);
    background-size: 100% 100%;
    background-repeat: no-repeat;
    color: #000000;
    width: 100% !important;
  }

  .table__content_list_C {
    width: 100% !important;
    font-weight: bold;
    font-size: 15px;
    color: #000000;
  }
  .table__content_list_row {
    color: #000000 !important;
  }
  .table__content_list_row .table__content__list_item_C:nth-child(1) {
    color: #ff0000;
  }

  .table__content_label_D {
    background-color: #c1dbfd;
    // background-image: var(--image-content-label-A);
    background-size: 100% 100%;
    background-repeat: no-repeat;
    color: #000000;
    width: 100% !important;
  }

  .table__content_list_D {
    width: 100% !important;
    font-weight: bold;
    font-size: 15px;
    color: #000000;
    text-align: center;
  }
  .table__content_list_row {
    color: #000000 !important;
  }

  .table__content_list_row .table__content__list_item_D:nth-child(1) {
    width: 50px;
  }
  .table__content_list_row .table__content__list_item_D:nth-child(4) {
    color: #107f30;
  }

  // 单选框列样式（固定宽度）
  .table__content__list_item_radio {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-shrink: 0; // 防止被压缩

    input[type='radio'] {
      cursor: pointer;
      width: 14px;
      height: 14px;
    }
  }
</style>
