<template>
  <!-- Tab标签页 -->
  <Tabs v-model:activeKey="activeKey" class="data-quality-page" type="line">
    <TabPane key="unresolved" tab="未解决">
      <div class="add-button">
        <a-button 
          type="default" 
          preIcon="mdi:download" 
          @click="handleExportExcel" 
          style="margin-right: 8px;"
        > 
          导出 
        </a-button>
        <a-button type="primary" preIcon="mdi:page-next-outline" @click="handleOpenModal({}, 'add')"> 新增问题 </a-button>
      </div>
      <BasicTable style="padding: 0" @register="registerUnresolvedTable">
        <template #queJson="{ record }">
          <div style="display: flex; align-items: center; gap: 8px; width: 100%;">
            <span style="flex: 1; text-align: center;">
              {{ record?.queJson ? formatQueJson(record.queJson) : '' }}
            </span>
            <!-- 按钮：无需额外样式，自然靠最右侧 -->
            <button @click="record && handleOpenModal(record, 'view')" class="action-btn">
              <SvgIcon name="view" />
            </button>
          </div>
        </template>
        <template #action="{ record }">
          <button @click="handleOpenModal(record, 'edit')" class="action-btn">
            <SvgIcon name="edit" />
          </button>
          <!-- 删除按钮 -->
          <Popconfirm
            title="删除确认"
            description="是否确认删除？"
            okText="确认"
            cancelText="取消"
            @confirm="handleDeleteRecord(record)"
            @cancel="handleCancel"
            placement="top"
          >
            <button class="action-btn">
              <SvgIcon name="delete" />
            </button>
          </Popconfirm>
          <Popconfirm
            title="标记已解决确认"
            :description="getResolveDesc(record)"
            okText="确认"
            cancelText="取消"
            @confirm="handleOKRecord(record)"
            @cancel="handleCancel"
            placement="top"
          >
            <button class="action-btn">
              <SvgIcon name="resolved" />
            </button>
          </Popconfirm>
          <button @click="handleGoToPage(record)" class="action-btn">
            <SvgIcon name="details" />
          </button>
        </template>
      </BasicTable>
    </TabPane>
    <TabPane key="resolved" tab="已解决">
      <div class="add-button">
        <a-button 
          type="default" 
          preIcon="mdi:download" 
          @click="handleExportExcel" 
          style="margin-right: 8px;"
        > 
          导出 
        </a-button>
      </div>
      <BasicTable style="padding: 0" @register="registerResolvedTable">
        <template #queJson="{ record }">
          <div style="display: flex; align-items: center; gap: 8px; width: 100%;">
            <span style="flex: 1; text-align: center;">
              {{ record?.queJson ? formatQueJson(record.queJson) : '' }}
            </span>
            <!-- 按钮：无需额外样式，自然靠最右侧 -->
            <button @click="record && handleOpenModal(record, 'view')" class="action-btn">
              <SvgIcon name="view" />
            </button>
          </div>
        </template>
        <template #action="{ record }">
          <button @click="handleOpenModal(record, 'view')" class="action-btn">
            <SvgIcon name="details" />
          </button>
        </template>
      </BasicTable>
    </TabPane>
  </Tabs>

  <!-- 处理弹框 -->
  <DataQualityModal @register="registerModal" @success="handleModalSuccess" />
</template>

<script setup lang="ts">
  import { ref, nextTick, computed } from 'vue';
  import { useRouter } from 'vue-router';
  import { BasicTable, useTable } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { Tabs, TabPane, Popconfirm, message } from 'ant-design-vue';
  import DataQualityModal from './components/DataQualityModal.vue';
  import { SvgIcon } from '/@/components/Icon';
  import { columns, searchFormSchema, productionStatusMap } from './dataQuality.data';
  import { getDataQuaQueList, addDataQuaQue, deleteDataQuaQue, editDataQuaQue } from '../basicInfo.api';
  import { findNode, findPath, listToTree } from '/@/utils/helper/treeHelper';
  import { useMineStore } from '/@/store/modules/mine';
  import dayjs from 'dayjs'; 
  import * as XLSX from 'xlsx';
  // 路由实例
  const router = useRouter();
  // 实例化矿井Store
  const mineStore = useMineStore();
  // 响应式数据
  const activeKey = ref('unresolved'); // 激活的Tab键
  const pageMode = ref('add');
  // 未解决表格注册
  const [registerUnresolvedTable, { reload: reloadUnresolved}] = useTable({
    api: getQuaQueListByTab(),
    columns,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
      showAdvancedButton: false,
      schemaGroupNames: ['常规查询'],
    },
    useSearchForm: true,
    pagination: true,
    striped: true,
    showIndexColumn: false,
    indexColumnProps: {
      title: '序号',
    },
    canResize: false,
    actionColumn: {
      width: 200,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    immediate: true,
  });

  // 已解决表格注册
  const [registerResolvedTable, { reload: reloadResolved }] = useTable({
    api: getQuaQueListByTab(),
    columns,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
      showAdvancedButton: false,
      schemaGroupNames: ['常规查询'],
    },
    useSearchForm: true,
    pagination: true,
    striped: true,
    // bordered: true,
    showIndexColumn: false,
    indexColumnProps: {
      title: '序号',
    },
    actionColumn: {
      width: 60,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    immediate: true,
  });

  // 弹框注册
  const [registerModal, { openModal }] = useModal();

  // 解析queJson并拼接orderNum+queCon的辅助函数
  function formatQueJson (queJsonStr: string) {
    // 空值处理
    if (!queJsonStr) return '无质量问题';
    try {
      const queList = JSON.parse(queJsonStr);
      // 非数组格式处理
      if (!Array.isArray(queList)) return '问题格式异常';
      // 拼接orderNum + queCon，多个问题用分号分隔
      return queList.map((item) => `问题${item.orderNum || ''}:${item.queCon || ''}`).join('; ');
    } catch (error) {
      console.error('解析质量问题JSON失败:', error);
      return '问题数据解析失败';
    }
  };

  /**
   * 根据标签获取表格数据（已解决/未解决）
   * @param result 弹框数据
   */
  function getQuaQueListByTab() {
    return async (params: any) => {
      const isOk = activeKey.value === 'resolved' ? true : false;
      return await getDataQuaQueList({ ...params, isOk: isOk });
    };
  }

  /**
   * 打开弹框函数
   * @param result 弹框数据
   */
  function handleOpenModal(record: any, mode: 'view' | 'edit' | 'add' = 'view') {
    pageMode.value = mode;
    openModal(true, {
      record,
      mode,
    });
  }

  /**
   * 弹框结果处理函数
   * @param result 弹框数据
   */
  async function handleModalSuccess(result: any) {
    try{
      if (pageMode.value === 'add') {
        console.log(result);
        await addDataQuaQue(result);
      } else if (pageMode.value === 'edit') {
        await editDataQuaQue(result);
      }
      // 刷新表格
      await nextTick();
      reloadUnresolved();
      reloadResolved();
    } catch(error) {
      console.log('操作失败：', error);
    }
  }
  /**
 * 通用页面跳转方法
 * @param record 当前行数据
 * @param path 目标路径（树形结构所在页面的路由地址）
 */
async function handleGoToPage(record: any) {
  try {
    const mineCode = record.mineCode;
    const targetNode = findNode(
      mineStore.getMineTree,
      (item) => item.id === mineCode,
      { id: 'id', pid: 'parentId', children: 'childDepart' }
    );

    let minePath = '';
    if (targetNode) {
      minePath = targetNode.parentId; // 取parentId作为minePath
      console.log('minePath（当前节点的parentId）:', minePath);
    } else {
      message.warning(`未找到矿码【${mineCode}】对应的矿井节点`);
      return;
    }

    // 跳转页面（可携带拼接后的矿名/路径等参数）
    router.push({
      path: `/sealed/${minePath}`,
      query: {},
    });

  } catch (error) {
    console.error('矿节点定位失败:', error);
    message.error('矿节点定位失败，请稍后重试');
  }
}

  /**
   * 气泡取消按钮通用回调
   */
  function handleCancel() {
    // 取消操作，无逻辑（仅关闭气泡）
  }

  /**
   * 生成已解决气泡提示文案：XX矿井XX问题是否解决了吗？
   */
  const getResolveDesc = computed(() => (record: any) => {
    const mineName = record.mineName || '该'; // 矿井名称兜底
    return `是否确认${mineName}矿井问题已解决？`;
  });

  /**
   * 删除记录方法
   * @param record 当前行数据
   */
  async function handleDeleteRecord(record: any) {
    try {
      await deleteDataQuaQue({ id: record.id });
      await nextTick();
      reloadUnresolved();
    } catch (error) {
      console.error('删除失败：', error);
    }
  }

  /**
   * 将记录改为已处理
   * @param record 当前行数据
   */
  async function handleOKRecord(record: any) {
    const copyRecord = {
      ...record,
      isOk : true,
      updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
    };
    copyRecord.isOk = true
    try {
      await editDataQuaQue(copyRecord);
      await nextTick();
      reloadUnresolved();
      reloadResolved();
    }catch (error) {
      console.error('操作失败：', error);
    }
  }

    /**
   * 获取全部未解决数据（不分页）
   */
  async function getAllUnresolvedData() {
    try {
      const res = await getDataQuaQueList({ pageNum: 1, pageSize: 9999, isOk: false });
      return res.records || []; // 请根据实际接口返回结构调整（比如res.list / res.data等）
    } catch (error) {
      console.error('获取未解决数据失败:', error);
      return [];
    }
  }

  /**
   * 获取全部已解决数据（不分页）
   */
  async function getAllResolvedData() {
    try {
      const res = await getDataQuaQueList({ pageNum: 1, pageSize: 9999, isOk: true });
      return res.records || []; // 请根据实际接口返回结构调整
    } catch (error) {
      console.error('获取已解决数据失败:', error);
      return [];
    }
  }

  /**
   * 格式化导出数据（统一字段名 + 状态文本）
   */
  function formatExportData(dataList: any[]) {
    return dataList.map(item => ({
      '煤矿名称': item.mineName || '',
      '煤矿简称': item.mineNameAbbr || '',
      '生产状态': productionStatusMap[item.mineProStatus]?.label || '未知状态',
      '在线状态': item.mineLinkStatus === 1 ? '在线' : (item.mineLinkStatus === 0 ? '离线' : '/'),
      '质量问题详情': formatQueJson(item.queJson),
      '当前状态': item.isOk ? '已解决' : '未解决',
      '处理时间': item.updateTime || ''
    }));
  }

  /**
   * 导出Excel核心方法
   */
  async function handleExportExcel() {
    // 声明关闭函数
    let hideLoading: () => void = () => {};
    try {
      // 初始化loading并获取关闭函数
      hideLoading = message.loading('正在导出数据，请稍候...');
      
      const unresolvedList = await getAllUnresolvedData();
      const resolvedList = await getAllResolvedData();

      const formattedUnresolved = formatExportData(unresolvedList);
      const formattedResolved = formatExportData(resolvedList);

      const workbook = XLSX.utils.book_new();
      const unresolvedSheet = XLSX.utils.json_to_sheet(formattedUnresolved);
      const resolvedSheet = XLSX.utils.json_to_sheet(formattedResolved);

      XLSX.utils.book_append_sheet(workbook, unresolvedSheet, '未解决');
      XLSX.utils.book_append_sheet(workbook, resolvedSheet, '已解决');

      const fileName = `数据质量问题_${dayjs().format('YYYYMMDDHHmmss')}.xlsx`;
      XLSX.writeFile(workbook, fileName);

      // 关闭加载提示
      hideLoading();
      message.success('导出成功！');
    } catch (error) {
      // 容错：若loading已初始化，再调用关闭
      if (hideLoading) {
        hideLoading();
      }
      console.error('Excel导出失败:', error);
      message.error('导出失败，请稍后重试');
    }
  }
</script>

<style scoped lang="less">
  .data-quality-page {
    padding: 0 12px;
    margin: 16px;
    border: 1px solid @border-color-base;
    .ant-form {
      background-color: #fff;
    }
  }
  .form-part {
    padding: 12px 10px 6px 10px;
    margin-bottom: 8px;
    background-color: #ffffff;
    border-radius: 2px;
  }
  .add-button {
    margin-bottom: 10px;
  }
  .action-btn {
    height: 30px;
    cursor: pointer;
    margin-right: 10px;

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