<template>
  <PageWrapper dense>
    <BasicTable @register="registerTable" @expand="tableExpand">
      <template #toolbar>
        <div>
          <a-button
            id="how-to-edit"
            class="font-bold"
            type="link"
            @click="openDrawer(true, { value: '', type: 'def' })"
            >👉如何新增任务?
          </a-button>
          <a-button
            @click="
              downloadExcel(TenderTaskExport, '招标摘要任务数据', getForm().getFieldsValue())
            "
            v-auth="'productManagement:TenderTask:export'"
            >导出</a-button
          >
          <a-button
            type="primary"
            danger
            @click="multipleRemove(TenderTaskRemove)"
            :disabled="!selected"
            v-auth="'productManagement:TenderTask:remove'"
            >删除</a-button
          >
          <a-button
            type="primary"
            @click="handleAdd"
            v-auth="'productManagement:TenderTask:add'"
            >新增</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),
              },
              {
                label: '删文件',
                icon: IconEnum.DOWNLOAD,
                type: 'primary',
                color: 'error',
                ghost: true,
                ifShow: () => {
                  if (record.progress.includes('100%')) {
                    if(record.delFile=='Y'){
                        return false;
                    }
                    return true;
                  } else {
                    return false;
                  }
                },
                onClick: handleDeleteFile.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>
    <TenderTaskModal @register="registerModal" @reload="reload" />
    <TenderDocsDrawer @register="registerDrawer" />
    <TenderResultDetailDrawer 
      :visible="resultDetailDrawerVisible" 
      :taskResultDetail="taskResultDetail"
      :taskInfo="currentTaskInfo"
      @update:visible="resultDetailDrawerVisible = $event" 
      @close="handleResultDetailDrawerClose" 
    />
  </PageWrapper>
</template>

<script setup lang="ts">
  import { PageWrapper } from '@/components/Page';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import {
    TenderTaskList,
    TenderTaskExport,
    TenderTaskRemove,
    TenderTaskStop,
    TenderTaskDeleteFile,
  } from '@/api/tenderReview/TenderTask';
  import { downloadExcel } from '@/utils/file/download';
  import { useModal } from '@/components/Modal';
  import TenderTaskModal from './TenderTaskModal.vue';
  import { formSchemas, columns, childColumns } from './TenderTask.data';
  import { IconEnum } from '@/enums/appEnum';
  import TenderDocsDrawer from './TenderDocsDrawer.vue';
  import { useDrawer } from '@/components/Drawer';
  import {
    TenderTaskResultDownload,
    getDetailResultsByTaskId,
  } from '@/api/tenderReview/TenderTaskResults';
  import TenderResultDetailDrawer from './TenderResultDetailDrawer.vue';
  import { onMounted, ref } from 'vue';
  import { TenderTaskResultDetailVO } from '@/api/tenderReview/TenderTaskResults/model';

  const [registerDrawer, { openDrawer }] = useDrawer();
  const resultDetailDrawerVisible = ref(false);
  const childTableData = ref([]);
  const taskResultDetail = ref<TenderTaskResultDetailVO[]>([]);
  const currentTaskInfo = ref<Recordable>({});

  defineOptions({ name: 'TenderTask' });

  const [registerTable, { reload, multipleRemove, selected, getForm }] = useTable({
    rowSelection: {
      type: 'checkbox',
    },
    title: '招标审核任务列表',
    api: TenderTaskList,
    showIndexColumn: false,
    clickToRowSelect: false,
    rowKey: 'id',
    expandRowByClick: false,
    useSearchForm: true,
    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 () => {
  });

  const handleResultDetailDrawerClose = () => {
    resultDetailDrawerVisible.value = false;
  };

  async function handleDetail(record: Recordable) {
    try {
      const detailRes = await getDetailResultsByTaskId(record.id);
      if (detailRes && detailRes.length > 0) {
        taskResultDetail.value = detailRes;
        currentTaskInfo.value = record;
        resultDetailDrawerVisible.value = true;
        return;
      }
    } catch (detailEx) {
      console.error('获取详细结果失败', detailEx);
    }  
  }

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

  function handleAdd() {
    openModal(true, { update: false });
  }

  function tableExpand(expanded, record) {
    if (expanded) {
      childTableData.value = record.childrenTasks;
      console.log('expanded, record', expanded, record);
    }
  }

  async function handleDeleteFile(record: Recordable) {
    await TenderTaskDeleteFile(record.childrenTasks[0].ossId);
    await reload();
  }

  // 修改后的 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 TenderTaskResultDownload(record.childrenTasks.map((item) => item.id));
      await reload();
    } else if (record.childrenTasks?.length == 1) {
      await TenderTaskResultDownload([record.childrenTasks[0].id]);
      await reload();
    } else {
      await TenderTaskResultDownload([record.id]);
      await reload();
    }
  }

  async function handleDelete(record: Recordable) {
    await TenderTaskRemove([record.id]);
    await reload();
  }
</script>

<style scoped></style>
