<template>
  <div>
    <div class="tw-bg-white tw-p-5 tw-rounded-xl tw-mb-5">
      <a-button class="query-btn" @click="clickSearch">查询</a-button>
    </div>

    <div class="tw-bg-white tw-p-5 tw-rounded-xl">
      <a-table
        rowKey="id"
        :columns="columns"
        :scroll="{ x: 1200 }"
        :data-source="data"
        :pagination="{
          pageSize: pageSize,
          current: pageNo,
          total: totalElements,
          showTotal: () => ``,
          onChange: (pageNoChanged, pageSizeChanged) => {
            pageNo = pageNoChanged;
            pageSize = pageSizeChanged;
          },
        }"
      >
        <template #action="{ record }">
          <span>
            <a-button v-if="record.filePath" @click="toDownload(record)"
              >下载文件</a-button
            >
            <a-button @click="toDelete(record)">删除</a-button>
          </span>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getTaskList, deleteTask } from "@/api/taskManagement";
import { useMainStore } from "@/store";
import { TaskItem } from "@/types";
import { message, Modal } from "ant-design-vue";
import { watch, onMounted } from "vue";

const store = useMainStore();
store.currentLocation = "项目管理 / 任务管理";

let data = $ref<TaskItem[]>([]);
let pageSize = $ref(10);
let pageNo = $ref(1);
let totalElements = $ref(0);
async function search() {
  await fetchData();
}

async function clickSearch() {
  pageNo = 1;
  await fetchData();
}

watch(() => [pageNo, pageSize], fetchData);

async function fetchData() {
  const res = await getTaskList({
    pageSize,
    pageNo,
  });
  // console.log(res);
  data = res.data.content;
  pageNo = res.data.pageNo;
  pageSize = res.data.pageSize;
  totalElements = res.data.totalElements;
}

const columns = [
  {
    title: "任务类型",
    dataIndex: "taskTypeName",
    ellipses: true,
  },
  {
    title: "状态",
    dataIndex: "statusMsg",
    width: 100,
  },
  {
    title: "用时",
    dataIndex: "spentTime",
    width: 140,
  },
  {
    title: "状态",
    dataIndex: "statusName",
    width: 100,
  },
  {
    title: "状态描述",
    dataIndex: "statusMsg",
  },
  {
    title: "操作",
    key: "action",
    slots: { customRender: "action" },
    fixed: "right",
    width: 200,
  },
];

onMounted(async () => {
  await search();
});

function toDownload(row: TaskItem) {
  if (row.filePath) window.open(row.filePath);
}
function toDelete(row: TaskItem) {
  Modal.confirm({
    title: "提示",
    content: "确认删除？",
    cancelText: "取消",
    okText: "确定",
    onOk: async () => {
      await deleteTask(row.id);
      await search();
      void message.success({ content: "操作成功" });
    },
  });
}
</script>
