<template>
  <!-- Tab标签页 -->
  <Tabs v-model:activeKey="activeKey" class="data-quality-page" type="line">
    <TabPane key="unresolved" tab="未解决">
      <div class="add-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：添加 flex: 1 占据剩余空间，text-align: center 实现文字居中 -->
            <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, '/basicInfo/accessStatistics')" class="action-btn">
            <SvgIcon name="details" />
          </button>
        </template>
      </BasicTable>
    </TabPane>
    <TabPane key="resolved" tab="已解决">
      <BasicTable style="padding: 0" @register="registerResolvedTable">
        <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 } from 'ant-design-vue';
  import DataQualityModal from './components/DataQualityModal.vue';
  import { SvgIcon } from '/@/components/Icon';
  import { columns, searchFormSchema } from './dataQuality.data';
  import { getDataQuaQueList, addDataQuaQue, deleteDataQuaQue, editDataQuaQue } from '../basicInfo.api';
  import dayjs from 'dayjs'; 
  // 路由实例
  const router = useRouter();
  // 响应式数据
  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 目标路径
   */
  function handleGoToPage(record: any, path: string) {
    // 跳转时携带当前煤矿的编号作为参数（根据实际需求调整携带的参数）
    router.push({
      path,
      // query: {
      //   orderNo: record.orderNo, // 煤矿编号
      //   mineName: record.mineName // 煤矿名称
      // }
    });
  }

  /**
   * 气泡取消按钮通用回调
   */
  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);
    }
  }
</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>
