<template>
  <div class="blue-background">
    <div class="lighter-container">
      <div class="left-row">
        <div>
          <div>状态：</div>
          <el-tag
            size="large"
            :effect="focusTaskStatus.includes('all') ? 'dark' : ''"
            type="primary"
            @click="changeTaskStatus()"
          >
            全部
          </el-tag>
          <template v-for="status in taskStatus" :key="status.index">
            <el-tag
              size="large"
              :effect="focusTaskStatus.includes(status.index) ? 'dark' : ''"
              type="primary"
              @click="changeTaskStatus(status)"
            >
              {{ status.name }}
            </el-tag>
          </template>
        </div>
        <div>
          <div>类别：</div>
          <el-tag
            size="large"
            :effect="focusTaskType.includes('all') ? 'dark' : ''"
            type="primary"
            @click="changeTaskType()"
          >
            全部
          </el-tag>
          <template v-for="type in taskType" :key="type.index">
            <el-tag
              size="large"
              :effect="focusTaskType.includes(type.index) ? 'dark' : ''"
              type="primary"
              @click="changeTaskType(type)"
            >
              {{ type.name }}
            </el-tag>
          </template>
        </div>
      </div>
      <div class="row">
        <el-input
          class="searcher"
          v-model="searcher"
          placeholder="请输入任务名称相关关键字"
        />
        <el-button type="primary" @click="pullTaskData(1)">搜索</el-button>
        <el-button type="primary" @click="reset(), pullTaskData(1)">重置</el-button>
      </div>
    </div>
    <div class="lighter-container">
      查询到{{ taskNum }}条任务
      <el-table table-layout="fixed" row-key="main_id" :data="taskData" class="table">
        <el-table-column prop="main_c_name" label="名称" />
        <el-table-column prop="main_c_user_name" label="用户" />
        <el-table-column prop="main_c_state" label="类型">
          <template #default="scope">
            <el-tag
              effect="dark"
              v-show="getType(scope.row.main_c_type) != null"
              disable-transitions
              >{{ getType(scope.row.main_c_type)?.name ?? "" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="main_c_state" label="状态">
          <template #default="scope">
            <el-tag
              effect="dark"
              v-show="getStatus(scope.row.main_c_state) != null"
              :type="statusStaticInfo[scope.row.main_c_state]?.tagType ?? ''"
              disable-transitions
              >{{ getStatus(scope.row.main_c_state)?.name ?? "" }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column prop="main_c_start_time" label="任务开始时间">
          <template #default="scope">
            {{ timeFormatter(scope.row.main_c_start_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="main_c_end_time" label="任务结束时间">
          <template #default="scope">
            {{ timeFormatter(scope.row.main_c_end_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="main_c_file_name" label="结果">
          <template #default="scope">
            <span
              class="link"
              v-if="scope.row.main_c_file != null && scope.row.main_c_file_name != null"
              @click="downloadWithBlob(scope.row.main_c_file, scope.row.main_c_file_name)"
            >
              {{ scope.row.main_c_file_name }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="360">
          <template #default="scope">
            <el-button
              type="primary"
              @click="
                () => {
                  dialog = true;
                  focusTask = scope.row;
                }
              "
            >
              查看详情
            </el-button>
            <template
              v-if="scope.row.main_c_file != null && scope.row.main_c_file_name != null"
            >
              <el-button
                type="primary"
                @click="
                  downloadWithBlob(scope.row.main_c_file, scope.row.main_c_file_name)
                "
              >
                下载结果
              </el-button>
              <el-button type="primary" @click="preView(scope.row.main_c_file)">
                预览结果
              </el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <div class="between-row">
        <div><!--empty div--></div>
        <el-pagination
          layout="prev, pager, next"
          :total="taskNum"
          @change="(page) => pullTaskData(page)"
        />
      </div>
    </div>
    <el-dialog v-model="dialog" :show-close="true" width="750">
      <template #header>
        <div class="my-header">
          <span class="second-title">{{ focusTask.main_c_name }}</span>
        </div>
      </template>
      <el-descriptions class="margin-top" label-width="128" :column="1" border>
        <el-descriptions-item label="任务名称">
          {{ focusTask.main_c_name }}
        </el-descriptions-item>
        <el-descriptions-item label="任务描述">
          {{ focusTask.main_c_comment }}
        </el-descriptions-item>
        <el-descriptions-item label="任务类型">
          <el-tag
            effect="dark"
            v-show="getType(focusTask.main_c_type) != null"
            disable-transitions
            >{{ getType(focusTask.main_c_type)?.name ?? "" }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="用户名">
          {{ focusTask.main_c_user_name }}
        </el-descriptions-item>
        <el-descriptions-item label="用户id">
          {{ focusTask.main_c_user_id }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag
            effect="dark"
            :type="statusStaticInfo[focusTask.main_c_state]?.tagType ?? ''"
            disable-transitions
            >{{ getStatus(focusTask.main_c_state)?.name ?? "" }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="任务开始时间">
          {{ timeFormatter(focusTask.main_c_start_time) }}
        </el-descriptions-item>
        <el-descriptions-item label="任务结束时间">
          {{ timeFormatter(focusTask.main_c_end_time) }}
        </el-descriptions-item>
        <el-descriptions-item label="结果文件">
          {{ focusTask.main_c_file_name }}

          <template
            v-if="focusTask.main_c_file != null && focusTask.main_c_file_name != null"
          >
            <el-button
              type="primary"
              size="small"
              @click="downloadWithBlob(focusTask.main_c_file, focusTask.main_c_file_name)"
            >
              下载结果
            </el-button>
            <el-button
              type="primary"
              size="small"
              @click="preView(focusTask.main_c_file)"
            >
              预览结果
            </el-button>
          </template>
        </el-descriptions-item>
        <el-descriptions-item label="原始数据">
          <template
            v-if="
              focusTask.main_c_source_file_name != null &&
              focusTask.main_c_source_file != null
            "
          >
            {{ focusTask.main_c_source_file_name }}
            <br />
          </template>
          <template v-if="focusTask.main_c_source_data != null">
            <div class="hide-scrollbar long-text">
              {{ truncateText(focusTask.main_c_source_data, 10000) }}
            </div>
          </template>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import { getTasks, getCName } from "@/api/rwgl";

export default {
  data() {
    return {
      searcher: "",
      taskStatus: [],
      focusTaskStatus: ["all"],
      statusStaticInfo: {
        0: {
          tagType: "primary",
        },
        1: {
          tagType: "primary",
        },
        2: {
          tagType: "success",
        },
        3: {
          tagType: "danger",
        },
      },
      taskType: [],
      focusTaskType: ["all"],
      taskData: [],
      taskNum: 0,
      focusTask: {},
      dialog: false,
      page: 1,
    };
  },
  mounted() {
    this.pullTaskStatus();
    this.pullTaskType();
    this.pullTaskData(1);
  },
  methods: {
    async pullTaskStatus() {
      this.taskStatus = (await getCName("task_status")).sort((a, b) => a.index - b.index);
    },
    changeTaskStatus(status) {
      if (status == null) {
        this.focusTaskStatus = ["all"];
      } else {
        let set = new Set(this.focusTaskStatus);
        set.delete("all");
        let index = status.index;
        if (this.focusTaskStatus.includes(index)) {
          set.delete(index);
        } else {
          set.add(index);
        }
        this.focusTaskStatus = Array.from(set);
      }
      // if(this.taskStatus.length==this.focusTaskStatus.length){
      //     this.focusTaskStatus = ["all"]
      // }
    },
    getCheckedStatus() {
      if (this.focusTaskStatus.includes("all")) {
        return null;
      } else {
        return this.focusTaskStatus;
      }
    },
    getStatus(index) {
      for (let i = 0; i < this.taskStatus.length; i++) {
        const e = this.taskStatus[i];
        if (e.index == index) {
          return e;
        }
      }
    },
    async pullTaskType() {
      this.taskType = (await getCName("yzt_task_type")).sort((a, b) => a.index - b.index);
    },
    changeTaskType(types) {
      if (types == null) {
        this.focusTaskType = ["all"];
      } else {
        let set = new Set(this.focusTaskType);
        set.delete("all");
        let index = types.index;
        if (this.focusTaskType.includes(index)) {
          set.delete(index);
        } else {
          set.add(index);
        }
        this.focusTaskType = Array.from(set);
      }
    },
    getCheckedType() {
      if (this.focusTaskType.includes("all")) {
        return null;
      } else {
        return this.focusTaskType;
      }
    },
    getType(index) {
      for (let i = 0; i < this.taskType.length; i++) {
        const e = this.taskType[i];
        if (e.index == index) {
          return e;
        }
      }
    },
    async pullTaskData(page) {
      if (page != null) this.page = page;
      let res = await getTasks(
        this.page,
        10,
        this.searcher,
        this.getCheckedStatus(),
        this.getCheckedType()
      );
      this.taskNum = res.count;
      this.taskData = res.data;
    },
    timeFormatter(time) {
      if (time == null) return;

      let date = new Date(time);

      return date.toLocaleString();
    },
    async downloadWithBlob(url, filename) {
      try {
        const response = await fetch(systemConfig.dmsDataProxy + url);
        const blob = await response.blob();
        const blobUrl = window.URL.createObjectURL(blob);

        const link = document.createElement("a");
        link.href = blobUrl;
        link.download = filename || "file";
        link.click();

        // 清理URL对象
        window.URL.revokeObjectURL(blobUrl);
      } catch (error) {
        console.error("下载失败:", error);
      }
    },
    reset() {
      this.focusTaskStatus = ["all"];
      this.searcher = "";
    },
    preView(url) {
      window.open("fileView?url=" + systemConfig.dmsDataProxy + url, "_blank");
    },
    truncateText(text, maxLength = 40) {
      if (typeof text !== "string" || text.length <= maxLength) {
        return text;
      }
      return text.substring(0, maxLength) + "…";
    },
  },
};
</script>

<style lang="less" scoped>
* {
  --el-table-bg-color: #eeeeee0b;
  /* 表格背景 */
  --el-table-header-bg-color: #eeeeee0b;
  /* 表头背景 */
  --el-table-tr-bg-color: #eeeeee0b;
  /* 行背景 */
  --el-table-row-hover-bg-color: #eeeeee0b;
  /* 行悬浮背景 */
  --el-table-header-text-color: #ededed;
  /* 表头文字颜色 */
}

.font,
.title,
.super-title,
.title-sub,
.second-title,
.third-title,
.strong-data,
link {
  color: #fff;
}

.hide-scrollbar {
  -ms-overflow-style: none;
  /* IE和Edge */
  scrollbar-width: none;
  /* Firefox */
}

.hide-scrollbar::-webkit-scrollbar {
  display: none;
  /* Chrome, Safari和Opera */
}

.long-text {
  width: 100%;
  height: 200px;
  overflow: scroll;
}

.icon {
  color: #fff;
  fill: currentColor;
}

.middle {
  text-align: center;
}

.darkblue-background,
.dark-background,
.bluedark-background,
.blue-background,
.image-background {
  padding-top: 40px;
  padding-bottom: 40px;
  margin-left: 0;
  padding-left: 90px;
  padding-right: 90px;
  min-height: 600px;
}

.darkblue-background {
  background: linear-gradient(to bottom, #02060c 0%, #0f3460 40%, #0f3460 100%);
}

.dark-background {
  background: #0a0a08;
}

.blue-background,
body {
  background: #0f3460;
}

.bluedark-background {
  background: linear-gradient(to bottom, #0f3460 0%, #0f3460 60%, #02060c 100%);
}

.image-background {
  background-repeat: no-repeat;
  background-position: center;
  background-size: 100% auto;
}

.lighter-container {
  background-color: #eeeeee0b;
  padding: 10px;
  margin: 15px;
  vertical-align: middle;
  border-radius: 3%;
}

.lightblue-container {
  border-radius: 3%;
  padding: 10px;
  margin: 15px;
  background: linear-gradient(to bottom, #215476 0%, #28638b 66%, #337aac 100%);
  font-size: 20px;

  .third-title {
    font-size: 28px;
    padding: 0;
  }
}

.middle-container {
  display: flex !important;
  justify-content: center;
  flex-direction: column;
  padding: 0;
  align-items: stretch;
}

.row,
.warp-row,
.between-row,
.left-row {
  display: flex !important;
  justify-content: space-around;
  padding: 0;
  align-items: stretch;
}

.warp-row {
  flex-wrap: wrap;
}

.between-row {
  justify-content: space-between;
}

.left-row {
  justify-content: flex-start;
}
.left-row > * {
  margin-right: 15px;
}

.col {
  display: flex !important;
  justify-content: space-around;
  flex-direction: column;
}

.dense-col {
  display: flex !important;
  justify-content: center;
  flex-direction: column;
}

.start-reverse-col {
  display: flex !important;
  justify-content: start;
  flex-direction: column-reverse;
}

.dense-col > *,
.start-reverse-col > * {
  margin: 10px;
}

.grid-2x2 {
  display: grid !important;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  width: 100%;
  height: 80%;
}

.strong-data {
  font-size: 32px;
  font-weight: bold;
  text-align: center;
}

.title {
  font-size: 36px;
  margin-top: 10px;
  text-align: center;
  font-weight: bold;
}

.super-title {
  font-size: 44px;
  margin-top: 10px;
  text-align: center;
  font-weight: bold;
}

.title-sub {
  font-size: 16px;
  margin-top: 10px;
  color: rgb(192, 192, 192);
  text-align: center;
}

.second-title {
  font-size: 20px;
  margin-top: 10px;
  padding-left: 10px;
  border-left: 2px solid #3498db;
  font-weight: bold;
}

.third-title {
  font-size: 18px;
  margin-top: 10px;
  padding-left: 10px;
  display: flex;
  font-weight: bold;
}

.link {
  font-weight: bold;
  /* 字体加粗 */
  text-decoration: underline;
  /* 下划线 */
  cursor: pointer;
  /* 鼠标悬浮时变为手型（可点击形式） */
}

.searcher {
  background-color: #334155;
  margin-right: 15px;
}

.blue {
  color: #3498db;
}

.grey {
  color: rgb(192, 192, 192);
}

.lightgrey {
  color: rgb(229, 229, 229);
}

#echart1 {
  width: 100%;
  height: 450px;
}

.container {
  width: 1920px;
  margin: 0 auto;
}
</style>
