<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <BasicTable @register="registerTable">
    <template #action="{ record }">
      <button @click="handleGoToPage(record, `/sealed/${record.areaId}`)" class="action-btn">
        <SvgIcon name="data" />
      </button>
      <button @click="handleGoToPage(record, '/basicInfo/accessStatistics')" class="action-btn">
        <SvgIcon name="info" />
      </button>
      <button @click="handleGoToPageQuery(record, '/warningAnalysis/connectAnalysis')" class="action-btn">
        <SvgIcon name="chart" />
      </button>
    </template>
  </BasicTable>
</template>

<script setup lang="ts">
  import { ref, nextTick, computed, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import { BasicTable, useTable } from '/@/components/Table';
  import { SvgIcon } from '/@/components/Icon';
  import { message } from 'ant-design-vue';
  // 引入动态列/表单配置函数 + 类型
  import { getColumns, getSearchFormSchema, type ProductionStatusMap } from './minesInfo.data';
  import { getMineData } from '../basicInfo.api';
  // 引入字典获取方法
  import { getDictItemsByCode } from '/@/utils/dict';

  // 路由实例
  const router = useRouter();

  // ========== 动态生产状态配置 ==========
  // 1. 响应式存储动态状态映射（key: 状态值，value: 配置）
  const dynamicProductionStatusMap = ref<ProductionStatusMap>({});
  // 2. 响应式存储动态下拉选项（供搜索表单使用）
  const dynamicProductionStatusOptions = ref<{ label: string; value: string | number }[]>([]);

  // 3. 生产状态颜色分配规则（和dataQuality保持一致）
  const getStatusColor = (statusText: string) => {
    if (statusText.includes('正常生产')) return 'green';
    if (statusText.includes('拟建矿井')) return 'blue';
    return 'red'; // 其他状态统一红色
  };

  // 4. 从接口获取生产状态字典，生成动态映射/选项
  const fetchProductionStatus = async () => {
    try {
      const statusList = await getDictItemsByCode('mineProStatus');
      if (!Array.isArray(statusList)) return;

      const statusMap: ProductionStatusMap = {};
      const statusOptions: { label: string; value: string | number }[] = [];
      
      statusList.forEach((item) => {
        const value = item.value;
        const label = item.text || item.label;
        const color = getStatusColor(label);
        
        statusMap[value] = { label, value, color };
        statusOptions.push({ label, value });
      });

      // 赋值到响应式变量
      dynamicProductionStatusMap.value = statusMap;
      dynamicProductionStatusOptions.value = statusOptions;

      // 刷新表格（使用最新的状态映射）
      await safeReloadTable();
    } catch (error) {
      console.error('获取生产状态字典失败:', error);
      message.error('生产状态数据加载失败');
    }
  };

  // 5. 生成动态列和搜索表单（computed响应式更新）
  const columns = computed(() => getColumns(dynamicProductionStatusMap));
  const searchFormSchema = computed(() => getSearchFormSchema(dynamicProductionStatusOptions));

  // ========== 表格注册 ==========
  const [registerTable, { reload: reloadTable }] = useTable({
    title: '矿山信息表格',
    api: getMineData, // 数据统计接口
    columns: columns, // 绑定动态列
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema.value, // 绑定动态搜索表单
      showAdvancedButton: false,
      schemaGroupNames: ['常规查询'],
    },
    pagination: true,
    useSearchForm: true,
    bordered: true,
    showIndexColumn: false,
    scroll: { x: 'max-content' },
    actionColumn: {
      width: 180,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    immediate: false, // 先不加载，等字典获取后再加载
  });

  // ========== 辅助方法 ==========
  // 安全刷新表格（避免表格未初始化导致的报错）
  async function safeReloadTable() {
    await nextTick();
    try {
      await reloadTable();
    } catch (e) {
      console.warn('矿山信息表格重载失败:', e);
    }
  }

  /**
   * 通用页面跳转方法
   * @param record 当前行数据
   * @param path 目标路径
   */
  function handleGoToPage(record: any, path: string) {
    router.push({
      path,
    });
  }

  function handleGoToPageQuery(record: any, path: string) {
    const mineCode = record.mineCode
    router.push({
      path,
      query: { mineCode : mineCode},
    });
  }

  // ========== 初始化 ==========
  onMounted(async () => {
    // 先获取生产状态字典，再加载表格
    await fetchProductionStatus();
  });
</script>

<style lang="less" scoped>
  .action-btn {
    height: 30px;
    cursor: pointer;
    margin-right: 10px;

    &:last-child {
      margin-right: 0;
    }
  }
</style>