<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <!-- Tab标签页 -->
  <Tabs v-model:activeKey="activeKey" class="common-page-tabs" type="line" @change="handleTabChange">
    <TabPane key="unresolved" tab="实时分析">
      <BasicTable style="padding: 0" @register="registerUnresolvedTable">
        <template #resetBefore>
          <!-- <a-button type="primary" class="ml-8px" preIcon="mdi:page-next-outline" @click="handleOpenModal({}, 'add')"> 新增问题 </a-button> -->
          <a-button type="default" class="ml-8px" preIcon="mdi:download" @click="handleOpenExportModal('unresolved')"> 导出 </a-button>
        </template>
        <template #queJson="{ record }">
          <div style="display: flex; align-items: center; gap: 8px; width: 100%; justify-content: space-between">
            <span style="white-space: pre-line; word-wrap: break-word; line-height: 1.6; display: block; text-align: left; padding: 2px 4px">
              {{ record?.queJson ? formatQueJson(record.queJson) : '' }}
            </span>
            <button @click="record && handleOpenModal(record, 'view')" class="action-btn" title="查看问题详情">
              <SvgIcon name="view" />
            </button>
          </div>
        </template>
        <!-- <template #action="{ record }">
          <button @click="handleOpenModal(record, 'edit')" class="action-btn" title="编辑该问题">
            <SvgIcon name="edit" />
          </button>
          <Popconfirm
            title="删除确认"
            description="是否确认删除？"
            okText="确认"
            cancelText="取消"
            @confirm="handleDeleteRecord(record)"
            @cancel="handleCancel"
            placement="top"
          >
            <button class="action-btn" title="删除该问题">
              <SvgIcon name="delete" />
            </button>
          </Popconfirm>
          <Popconfirm
            title="标记已解决确认"
            :description="getResolveDesc(record)"
            okText="确认"
            cancelText="取消"
            @confirm="handleOKRecord(record)"
            @cancel="handleCancel"
            placement="top"
          >
            <button class="action-btn" title="标记该问题为已解决">
              <SvgIcon name="solved" />
            </button>
          </Popconfirm>
          <button @click="handleGoToPage(record)" class="action-btn" title="监测详情">
            <SvgIcon name="database" />
          </button>
        </template> -->
      </BasicTable>
    </TabPane>
    <TabPane key="resolved" tab="历史数据">
      <BasicTable style="padding: 0" @register="registerResolvedTable">
        <template #resetBefore>
          <a-button type="default" class="ml-8px" preIcon="mdi:download" @click="handleOpenExportModal('resolved')"> 导出 </a-button>
        </template>
        <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" title="查看问题详情">
              <SvgIcon name="view" />
            </button>
          </div>
        </template>
        <template #action="{ record }">
          <button @click="handleOpenModal(record, 'view')" class="action-btn" title="问题详情">
            <SvgIcon name="details" />
          </button>
        </template>
      </BasicTable>
    </TabPane>
  </Tabs>

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

  <!-- 导出时间选择Modal-->
  <Modal
    v-model:open="exportModalVisible"
    title="选择导出时间范围"
    :width="600"
    @ok="handleExportConfirm"
    @cancel="handleExportCancel"
    okText="确认导出"
    cancelText="取消"
    centered
    :confirm-loading="exportConfirmLoading"
    destroyOnClose
    :bodyStyle="{ padding: '20px' }"
  >
    <a-form
      ref="exportFormRef"
      :model="exportFormData"
      :rules="exportFormRules"
      layout="horizontal"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
    >
      <a-form-item v-for="schema in exportFormSchema" :key="schema.field" :name="schema.field" :label="schema.label" :rules="schema.rules">
        <component
          :is="getExportFormComponent(schema.component)"
          v-model:value="exportFormData[schema.field]"
          v-bind="schema.componentProps"
          :placeholder="`请选择${schema.label}`"
          style="width: 100%"
        />
      </a-form-item>
    </a-form>
  </Modal>
</template>

<script setup lang="ts">
  import { ref, nextTick, onMounted, reactive } from 'vue';
  import { BasicTable } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { Tabs, TabPane, message, Modal, DatePicker } from 'ant-design-vue';
  import type { FormInstance } from 'ant-design-vue/es/form';
  import DataQualityModal from './components/DataQualityModal.vue';
  import { SvgIcon } from '/@/components/Icon';
  import { columns, searchFormSchema, exportFormSchema, historyColumns, historySearchFormSchema } from './dataQuality.data';
  import { getDataQuaQueList, addDataQuaQue, editDataQuaQue, getMineDataQualityHistory } from '../basicInfo.api';
  // import { findNode } from '/@/utils/helper/treeHelper';
  // import { useMineDepartmentStore } from '/@/store/modules/mine';
  // import { getDictItemsByCode } from '/@/utils/dict';
  import dayjs, { Dayjs } from 'dayjs';
  import { useListPage } from '/@/hooks/system/useListPage';
  // import { advancedRoutePush } from '/@/utils/index.js';

  // 实例化矿井Store
  // const mineStore = useMineDepartmentStore();
  // 响应式数据
  const activeKey = ref('unresolved'); // 激活的Tab键
  const pageMode = ref('add');

  // 导出Modal相关状态
  const exportModalVisible = ref(false);
  const exportFormRef = ref<FormInstance>();
  const exportConfirmLoading = ref(false);
  const exportType = ref<'resolved' | 'unresolved'>('unresolved'); // 记录当前导出类型
  const exportConfig = ref({
    url: '/province/dataQuaQue/exportDataQuaQueList',
    name: '数据质量问题反馈',
    params: {
      isOk: 0,
      startTime: '',
      endTime: '',
    },
  });

  // 导出表单数据和规则（参考DataQualityModal写法）
  const exportFormData = reactive({
    startTime: null as Dayjs | null,
    endTime: null as Dayjs | null,
  });

  // 提取导出表单规则（从exportFormSchema）
  const exportFormRules = reactive({
    startTime: exportFormSchema.find((item) => item.field === 'startTime')?.rules || [],
    endTime: exportFormSchema.find((item) => item.field === 'endTime')?.rules || [],
  });

  // 导出表单组件映射
  const exportFormComponentMap = {
    DatePicker,
  };

  // 获取导出表单组件
  const getExportFormComponent = (componentName: string) => {
    return exportFormComponentMap[componentName as keyof typeof exportFormComponentMap];
  };

  // 未解决表格注册
  const { tableContext: tableContextA, onExportXls: onExportXlsA } = useListPage({
    tableProps: {
      api: async (params: any) => {
        return await getDataQuaQueList({ ...params, isOk: false });
      },
      columns: columns, // 绑定动态列
      formConfig: {
        autoSearch: true,
        labelWidth: 120,
        schemas: searchFormSchema,
        showAdvancedButton: false,
        schemaGroupNames: ['常规查询'],
        actionColOptions: { span: 6 },
      },
      useSearchForm: true,
      pagination: true,
      showIndexColumn: false,
      indexColumnProps: {
        title: '序号',
      },
      showActionColumn: false,
      // actionColumn: {
      //   width: 200,
      //   title: '操作',
      //   dataIndex: 'action',
      //   slots: { customRender: 'action' },
      // },
      immediate: false, // 先不立即加载，等状态数据获取后再加载
    },
    exportConfig: {
      url: '/province/mineData/exportMineDataQuality',
      name: '数据质量问题反馈',
      params: {},
    },
  });

  const [registerUnresolvedTable, { reload: reloadUnresolved }] = tableContextA;

  // 已解决表格注册
  const { tableContext: tableContextB, onExportXls: onExportXlsB } = useListPage({
    tableProps: {
      api: async (params: any) => {
        return await getMineDataQualityHistory({ ...params, isOk: true });
      },
      columns: historyColumns,
      formConfig: {
        autoSearch: true,
        labelWidth: 120,
        schemas: historySearchFormSchema,
        showAdvancedButton: false,
        schemaGroupNames: ['常规查询'],
      },
      useSearchForm: true,
      pagination: true,
      striped: true,
      showIndexColumn: false,
      indexColumnProps: {
        title: '序号',
      },
      showActionColumn: false,
      // actionColumn: {
      //   width: 60,
      //   title: '操作',
      //   dataIndex: 'action',
      //   slots: { customRender: 'action' },
      // },
      immediate: false, // 先不立即加载
    },
    exportConfig: {
      url: '/province/mineData/exportMineDataQualityHistory',
      name: '数据质量历史数据',
      params: {},
    },
  });

  const [registerResolvedTable, { reload: reloadResolved }] = tableContextB;

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

  /**
   * 打开导出时间选择Modal
   * @param type 导出类型：resolved 或 unresolved
   */
  function handleOpenExportModal(type: 'resolved' | 'unresolved') {
    exportType.value = type;
    exportModalVisible.value = true;
    // 打开Modal时重置表单
    nextTick(() => {
      exportFormRef.value?.resetFields();
      exportFormData.startTime = null;
      exportFormData.endTime = null;
    });
  }

  /**
   * 导出Modal确认处理
   */
  async function handleExportConfirm() {
    try {
      exportConfirmLoading.value = true;
      // 表单校验（参考DataQualityModal的校验方式）
      if (!exportFormRef.value) return;
      const validateResult = await exportFormRef.value.validate();
      if (!validateResult) return;

      // 格式化时间
      const startTime = exportFormData.startTime?.format('YYYY-MM-DD HH:mm:ss') || '';
      const endTime = exportFormData.endTime?.format('YYYY-MM-DD HH:mm:ss') || '';

      // 校验时间逻辑（结束时间不能早于开始时间）
      if (exportFormData.startTime && exportFormData.endTime && dayjs(endTime).isBefore(dayjs(startTime))) {
        message.error('结束时间不能早于开始时间');
        return;
      }

      // 根据类型选择对应的exportConfig和导出方法
      exportConfig.value.params = {
        isOk: exportType.value === 'resolved' ? 1 : 0,
        startTime,
        endTime,
      };

      if (exportType.value === 'unresolved') {
        await onExportXlsA();
      } else {
        await onExportXlsB();
      }

      // 关闭Modal
      exportModalVisible.value = false;
      // message.success('导出请求已发送，请注意查收文件');
    } catch (error: any) {
      console.error('导出失败：', error);
      message.error(error.message || '导出失败，请检查表单填写是否正确');
    } finally {
      exportConfirmLoading.value = false;
    }
  }

  /**
   * 导出Modal取消处理
   */
  function handleExportCancel() {
    exportModalVisible.value = false;
    // 取消时重置表单
    exportFormRef.value?.resetFields();
    exportFormData.startTime = null;
    exportFormData.endTime = null;
  }

  // 解析queJson并拼接orderNum+queCon的辅助函数
  function formatQueJson(queJsonStr: string) {
    // 空值处理
    if (!queJsonStr) return '无质量问题';
    try {
      const queList = JSON.parse(queJsonStr);
      // 非数组格式处理
      if (!Array.isArray(queList)) return '问题格式异常';
      // 空数组处理
      if (queList.length === 0) return '无质量问题';
      return queList
        .map((item) => {
          const goafName = item.goafName;
          const queCon = item.queCon || '无描述';
          return `<${goafName}工作面老空区永久密闭监测>存在的问题：${queCon}`;
        })
        .join('\n'); // 多个问题分行显示
    } catch (error) {
      console.error('解析质量问题JSON失败:', error);
      return '问题数据解析失败';
    }
  }

  // 安全重载当前激活的表格
  async function safeReloadActiveTable() {
    await nextTick();
    if (activeKey.value === 'unresolved') {
      try {
        await reloadUnresolved();
      } catch (e) {
        console.warn('未解决表格重载失败:', e);
      }
    } else {
      try {
        await reloadResolved();
      } catch (e) {
        console.warn('已解决表格重载失败:', e);
      }
    }
  }
  // 按需重载双表格（先注释掉）
  // async function reloadBothTableSafely() {
  //   await nextTick();
  //   // 未解决表格：await + try/catch 捕获异步错误
  //   try {
  //     await reloadUnresolved();
  //   } catch (e) {
  //     console.warn('未解决表格暂未就绪，跳过重载:', e);
  //   }
  //   // 已解决表格：同理，一个报错不影响另一个
  //   try {
  //     await reloadResolved();
  //   } catch (e) {
  //     console.warn('已解决表格暂未就绪，跳过重载:', e);
  //   }
  // }

  // tabs切换事件
  async function handleTabChange(key: string) {
    activeKey.value = key;
    await safeReloadActiveTable();
  }

  /**
   * 打开弹框函数
   * @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') {
        await addDataQuaQue(result);
      } else if (pageMode.value === 'edit') {
        await editDataQuaQue(result);
      }
      await safeReloadActiveTable();
    } catch (error) {
      console.error('操作失败：', error);
    }
  }

  // /**
  //  * 通用页面跳转方法
  //  * @param record 当前行数据
  //  * @param path 目标路径（树形结构所在页面的路由地址）
  //  */
  // async function handleGoToPage(record: any) {
  //   try {
  //     const mineCode = record.mineCode;
  //     const targetNode = findNode(mineStore.getDepartTree, (item) => item.fax === mineCode, { id: 'id', pid: 'parentId', children: 'childDepart' });

  //     let minePath = '';
  //     if (targetNode) {
  //       minePath = targetNode.parentId;
  //     } else {
  //       message.warning(`未找到矿码【${mineCode}】对应的矿井节点`);
  //       return;
  //     }

  //     // 跳转页面（可携带拼接后的矿名/路径等参数）
  //     advancedRoutePush({ path: `/sealed/${minePath}`, query: { deptId: targetNode.id } });
  //   } 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();
  //     await safeReloadActiveTable();
  //   } 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'),
  //   };
  //   try {
  //     await editDataQuaQue(copyRecord);
  //     await safeReloadActiveTable();
  //     message.success('标记为已解决成功');
  //   } catch (error) {
  //     console.error('操作失败：', error);
  //     message.error('操作失败，请稍后重试');
  //   }
  // }

  // ========== 初始化：先获取状态数据，再加载表格 ==========
  onMounted(async () => {
    await safeReloadActiveTable();
  });
</script>

<style scoped lang="less">
  .form-part {
    padding: 12px 10px 6px 10px;
    margin-bottom: 8px;
    background-color: @white;
    border-radius: 2px;
  }
  .add-button {
    margin-bottom: 10px;
  }
  .action-btn {
    height: 30px;
    cursor: pointer;
    margin-right: 10px;

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