<template>
  <div class="flex flex-col h-full">
    <SearchForm :fields="fields" :params="params" :search="search">
      <template #type="{ item, params }">
        <t-select
          v-model="params[item.prop]"
          :options="taskTypeList"
          clearable
        ></t-select>
      </template>
    </SearchForm>
    <div class="flex-1 page-wrap">
      <t-table
        size="small"
        row-key="id"
        :columns="columns"
        :data="tableData"
        bordered
        :pagination="{
          defaultCurrent: 1,
          defaultPageSize: 10,
          onChange,
          showJumper: true,
          showPageSize: false,
          total: pagination.total,
          current: pagination.pageNumber,
        }"
        v-loading="tableLoading"
      >
        <template #result="{ col, row }">
          <span
            :class="row.result === '成功' ? 'color-success' : 'color-error'"
            >{{ row.result }}</span
          >
        </template>
        <template #status="{ col, row }">
          <status-tag :value="row[col.colKey]" type="taskStatus"></status-tag>
        </template>
        <template #create-time="{ col, row }">
          {{ timestampFilter(row[col.colKey]) }}
        </template>
        <template #operate="{ col, row }">
          <div class="table-operations">
            <template v-if="perm.LINK_Export">
              <t-link
                :disabled="!row.hasReportFile"
                theme="primary"
                hover="color"
                @click="handleDownload(row, 'REPORT_FILE')"
              >
                导出日志
              </t-link>
            </template>
            <template v-if="perm.LINK_Download">
              <t-link
                :disabled="!row.hasResultFile"
                theme="primary"
                hover="color"
                @click="handleDownload(row, 'EXPORT_FILE')"
              >
                下载文件
              </t-link>
            </template>
          </div>
        </template>
      </t-table>
    </div>

    <my-dialog
      :visible="logVisible"
      header="日志"
      :width="800"
      attach="body"
      @close="logVisible = false"
    >
      <p v-for="(cont, cidx) in logList" :key="cidx"> {{ cont }}</p>
      <template #foot>
        <t-button theme="primary" @click="logVisible = false">确定</t-button>
      </template>
    </my-dialog>
  </div>
</template>

<script setup name="TaskManage">
import { ref, reactive } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import useFetchTable from '@/hooks/useFetchTable';

import { taskQueryApi } from '@/api/system';
import { getAttachmentFile } from '@/api/user';
import { dictToOptionList, downloadByUrl } from '@/utils/tool';
import { DATA_TASK_STATUS, DATA_TASK_RESULT } from '@/config/constants';
import { timestampFilter } from '@/utils/filter';
import usePermission from '@/hooks/usePermission';
import { enumListByType } from '@/api/common';
const { perm } = usePermission();

const fields = ref([
  {
    prop: 'type',
    label: '任务类型',
    type: 'select',
    labelWidth: 70,
    colSpan: 6,
  },
  {
    prop: 'status',
    label: '任务状态',
    type: 'select',
    labelWidth: 80,
    colSpan: 6,
    options: dictToOptionList(DATA_TASK_STATUS),
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'result',
    label: '任务结果',
    type: 'select',
    labelWidth: 80,
    colSpan: 6,
    options: dictToOptionList(DATA_TASK_RESULT),
    attrs: {
      clearable: true,
    },
  },
  {
    type: 'buttons',
    colSpan: 2,
    children: [
      {
        type: 'button',
        text: '搜索',
        onClick: () => {
          search();
        },
      },
    ],
  },
]);
const params = reactive({
  status: '',
  type: '',
  result: '',
});

const columns = [
  { colKey: 'type', title: '任务类型' },
  { colKey: 'status', title: '任务状态', width: 100 },
  { colKey: 'result', title: '任务结果', width: 100 },
  { colKey: 'createName', title: '创建人' },
  { colKey: 'createTime', title: '创建时间', cell: 'create-time', width: 180 },
  {
    title: '管理',
    colKey: 'operate',
    fixed: 'right',
    width: 160,
  },
];
const {
  loading: tableLoading,
  pagination,
  tableData,
  search,
  onChange,
} = useFetchTable(taskQueryApi, {
  params,
});

const taskTypeList = ref([]);
async function getTaskTypeList() {
  const res = await enumListByType('TASK_TYPE_ENUM');
  taskTypeList.value = dictToOptionList(res || {});
}
getTaskTypeList();

const logVisible = ref(false);
const logList = ref([]);

async function handleDownload(row, type) {
  const res = await getAttachmentFile(row.id, type).catch(() => {});
  if (!res) return;

  if (type === 'REPORT_FILE') {
    logVisible.value = true;
    logList.value = (res.content || '').split('\n');
    return;
  }

  const url = res.url;
  if (url.endsWith('.txt')) {
    window.open(url);
    return;
  }

  downloadByUrl(url);
  MessagePlugin.success('文件下载成功！');
}
</script>
