<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" />
</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,
  } 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 { onMounted, ref } from 'vue';
  import { DocumentTasksPermissionsVO } from '@/api/taskPermissions/DocumentTasksPermissions/model';
  let props = defineProps(['useSearchForm', 'showTableSetting', 'showToolbar', 'pagination']);
  defineOptions({ name: 'DocumentTasks' });
  const documentData = ref<DocumentTasksPermissionsVO>();
  const [registerDrawer, { openDrawer }] = useDrawer();
  const childTableData = ref([]);
  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 timer = ref<any>(null);
  // //页面在刷新的时候可以加loading显示 方便页面展示
  // const loading = ref(false);
  // //使countdown定时增加 如果增加到我们想要的时间 也就是变量autoRefreshTime 执行刷新
  // const countdown = ref(0);
  // //定时刷新的时间 现在设置的为6 也就是6秒刷新一次数据
  // const autoRefreshTime = ref(30);
  const [registerModal, { openModal }] = useModal();
  onMounted(async () => {
    documentData.value = await getTasksPermissionsByUserId();
    // timer.value = window.setInterval(() => {
    //   //不loading的时候才会执行
    //   if (!loading.value) {
    //     //countdown小于我们想要的定时时间的时候 定时器也是一秒执行一次 就继续+1
    //     if (countdown.value < autoRefreshTime.value) {
    //       countdown.value = countdown.value + 1;
    //       //当定时器到时间的时候 去干我们想干的事情 refresh()
    //       if (countdown.value === autoRefreshTime.value) {
    //         countdown.value = 0;
    //         reload();
    //       }
    //     }
    //   }
    // }, 1000);
  });
  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);
      if (record.taskName == 'schemEvaluation') {
        // res.result=generateTable(JSON.parse(res.result as string))
        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) {
      openDrawer(true, { value: '加载失败，请刷新页面', type: 'markdown' });
    }
    //根据record.id查询结果详情
  }

  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>
