<template>
  <BasicTable @register="registerTable" @expand="tabelexpand">
    <template #toolbar v-if="props.showToolbar">
      <div >
        <a-button
          id="how-to-edit"
          class="font-bold"
          type="link"
          @click="openDrawer(true, { value: '', type: 'def' })"
          >👉如何新增任务?
        </a-button>
        <a-button type="primary" @click="handleAdd">新增</a-button>
      </div>
    </template>
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'action'">
        <TableAction
          stopButtonPropagation
          :actions="[
            {
              label: record.childrenTasks.length > 1 ? '下载全部' : '下载',
              icon: IconEnum.DOWNLOAD,
              type: 'primary',
              color: 'success',
              ghost: true,
              ifShow: () => {
                if (record.progress.includes('100%')) {
                  return true;
                } else {
                  return false;
                }
              },
              onClick: handleDownload.bind(null, record),
            },
          ]"
        />
      </template>
    </template>
    <template #expandedRowRender>
      <BasicTable @register="registerChildTable">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <TableAction
              stopButtonPropagation
              :actions="[
                {
                  label: '详情',
                  icon: IconEnum.EDIT,
                  type: 'primary',
                  ghost: true,
                  ifShow: () => {
                    if (
                      record.progressStatus != 'PENDING' &&
                      record.progressStatus != 'STARTED' &&
                      record.progressStatus != 'REVOKED'
                    ) {
                      return true;
                    } else {
                      return false;
                    }
                  },
                  onClick: handleDetail.bind(null, record),
                },
                {
                  label: '下载',
                  icon: IconEnum.DOWNLOAD,
                  type: 'primary',
                  color: 'success',
                  ghost: true,
                  ifShow: () => {
                    if (
                      record.progressStatus != 'PENDING' &&
                      record.progressStatus != 'STARTED' &&
                      record.progressStatus != 'REVOKED'
                    ) {
                      return true;
                    } else {
                      return false;
                    }
                  },
                  onClick: handleDownload.bind(null, record),
                },
                {
                  label: '终止任务',
                  icon: IconEnum.DELETE,
                  type: 'primary',
                  danger: true,
                  ghost: true,
                  ifShow: () => {
                    if (record.progressStatus == 'PENDING') {
                      return true;
                    } else {
                      return false;
                    }
                  },
                  popConfirm: {
                    placement: 'left',
                    title: '是否终止当前任务?',
                    confirm: handleStop.bind(null, record),
                  },
                },
              ]"
            />
          </template>
        </template>
      </BasicTable>
    </template>
  </BasicTable>
  <DocumentTasksModal @register="registerModal" @reload="reload" />
  <DocsDrawer @register="registerDrawer" />
  <ResultDetailDrawer @register="registerResultDetailDrawer" />
</template>

<script setup lang="ts">
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { DocumentTasksList, DocumentTasksStop } from '@/api/documentReview/DocumentTasks';
  import { getTasksPermissionsByUserId } from '@/api/taskPermissions/DocumentTasksPermissions';
  import {
    DocumentTaskResultsInfoByTaskId,
    DocumentTaskResultDownload,
    getDetailResultsByTaskId,
  } from '@/api/documentReview/DocumentTaskResults';
  import { useModal } from '@/components/Modal';
  import DocumentTasksModal from './DocumentTasksModal.vue';
  import { formSchemas, columns, childColumns } from './DocumentTasks.data';
  import { IconEnum } from '@/enums/appEnum';
  import { useDrawer } from '@/components/Drawer';
  import DocsDrawer from '@/views/documentReview/DocumentTasks/DocsDrawer.vue';
  import ResultDetailDrawer from '@/views/documentReview/DocumentTasks/ResultDetailDrawer.vue';
  import { onMounted, ref } from 'vue';
  import { DocumentTasksPermissionsVO } from '@/api/taskPermissions/DocumentTasksPermissions/model';
  import { DocumentTaskResultDetailVO } from '@/api/documentReview/DocumentTaskResults/model';
  let props = defineProps(['useSearchForm', 'showTableSetting', 'showToolbar', 'pagination']);
  defineOptions({ name: 'DocumentTasks' });
  const documentData = ref<DocumentTasksPermissionsVO>();
  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerResultDetailDrawer, { openDrawer: openResultDetailDrawer }] = useDrawer();
  const childTableData = ref([]);
  const taskResultDetail = ref<DocumentTaskResultDetailVO[]>([]);
  const [registerTable, { reload }] = useTable({
    api: DocumentTasksList,
    showIndexColumn: false,
    clickToRowSelect: false,
    rowKey: 'id',
    title: props.showTableSetting?"方案审核任务列表":'',
    expandRowByClick: false,
    useSearchForm: props.useSearchForm,
    showTableSetting: props.showTableSetting,
    beforeFetch: async (record) => {
      if (props.pagination == false) {
        (record.pageNum = 1), (record.pageSize = 5);
      }
    },
    pagination: props.pagination,
    formConfig: {
      schemas: formSchemas,
      baseColProps: {
        xs: 24,
        sm: 24,
        md: 24,
        lg: 6,
      },
    },
    columns: columns,
    actionColumn: {
      width: 200,
      title: '操作',
      key: 'action',
      fixed: 'right',
    },
  });
  const [registerChildTable, { setProps: setChildProps }] = useTable({
    size: 'small', //紧凑型表格
    api: getchildTableData,
    columns: childColumns,
    rowKey: 'id',
    useSearchForm: false,
    showIndexColumn: false,
    showTableSetting: false,
    pagination: false,
    maxHeight: 50,
    actionColumn: {
      width: 200,
      title: '操作',
      key: 'action',
      fixed: 'right',
    },
  });
  const [registerModal, { openModal }] = useModal();
  onMounted(async () => {
    documentData.value = await getTasksPermissionsByUserId();
  });
  const cleanHtml = (content) => {
    // 移除DOCTYPE和html标签
    content = content.replace(/<!DOCTYPE[^>]*>/i, '');
    content = content.replace(/<html[^>]*>/i, '');
    content = content.replace(/<\/html>/i, '');

    // 移除head部分
    content = content.replace(/<head>[\s\S]*?<\/head>/i, '');

    // 移除body标签
    content = content.replace(/<body[^>]*>/i, '');
    content = content.replace(/<\/body>/i, '');

    return content.trim();
  };
  async function handleDetail(record: Recordable) {
    try {
      let res = await DocumentTaskResultsInfoByTaskId(record.id);
      
      // 如果原API返回结果为空，则尝试使用新API获取详细结果
      if (!res || !res.result) {
        try {
          const detailRes = await getDetailResultsByTaskId(record.id);
          if (detailRes && detailRes.length > 0) {
            taskResultDetail.value = detailRes;
            openResultDetailDrawer(true, { 
              taskResultDetail: detailRes, 
              taskInfo: record
            });
            return;
          }
        } catch (detailEx) {
          console.error('获取详细结果失败', detailEx);
        }
      }
      
      // 原有逻辑保留
      if (record.taskName == 'schemEvaluation') {
        const updatedHtmlText = res.result?.replace(
          /文件名称：\S+/g,
          `文件名称：${record.documentName}`,
        );

        openDrawer(true, { value: cleanHtml(updatedHtmlText), type: 'markdown' });
      } else if (record.taskName == 'checkDocumentError') {
        openDrawer(true, { value: res.result, type: 'markdown' });
      } else {
        openDrawer(true, { value: res.result, type: 'markdown' });
      }
      console.log('res', res);
    } catch (ex) {
      // 如果原API失败，尝试使用新API
      try {
        const detailRes = await getDetailResultsByTaskId(record.id);
        if (detailRes && detailRes.length > 0) {
          taskResultDetail.value = detailRes;
          openResultDetailDrawer(true, { 
            taskResultDetail: detailRes, 
            taskInfo: record,
          });
          return;
        }
      } catch (detailEx) {
        console.error('获取详细结果也失败', detailEx);
        openDrawer(true, { value: '加载失败，请刷新页面', type: 'markdown' });
      }
    }
  }

  async function handleStop(record: Recordable) {
    await DocumentTasksStop(record.id);
    await reload();
  }

  function handleAdd() {
    openModal(true, { update: false });
  }
  function tabelexpand(expanded, record) {
    if (expanded) {
      childTableData.value = record.childrenTasks;
      // reloadChildTable()
      console.log('expanded, record', expanded, record);
    }
  }
  // 修改后的 getchildTableData 函数
  function getchildTableData() {
    console.log('childTableData', childTableData.value);
    const height = 50 * childTableData.value.length;
    setChildProps({ maxHeight: height });

    // 返回一个 Promise 对象，包含预期的数据结构
    return Promise.resolve(childTableData.value);
  }
  async function handleDownload(record: Recordable) {
    if (record.childrenTasks?.length > 1) {
      await DocumentTaskResultDownload(record.childrenTasks.map((item) => item.id));
      await reload();
    } else if (record.childrenTasks?.length == 1) {
      await DocumentTaskResultDownload([record.childrenTasks[0].id]);
      
      await reload();
    } else {
      await DocumentTaskResultDownload([record.id]);
      await reload();
    }
  }
</script>

<style scoped></style>
