<template>
  <div class="app-container">
    <!-- 筛选 -->
    <el-form :inline="true">
      <el-form-item label="抓取应用">
        <el-select
          v-model="condition.filter"
          placeholder="抓取应用"
          filterable
          clearable
        >
          <el-option
            v-for="item in fetchApps"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="serchData">查询</el-button>
      </el-form-item>
    </el-form>
    <el-row style="margin-bottom: 20px">
      <el-button type="primary" @click="createTask">创建抓取任务</el-button>
    </el-row>
    <!--表格-->
    <el-table :data="newgetTask" stripe style="width: 100%" border>
      <el-table-column
        prop="id"
        label="任务ID"
        min-width="10%"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="taskName"
        label="抓取任务"
        width="180"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="appName"
        label="应用"
        width="180"
        align="center"
      ></el-table-column>

      <el-table-column prop="name" label="任务进度" min-width="35%">
        <template slot-scope="scope">
          <el-progress
            :text-inside="true"
            :stroke-width="24"
            :percentage="scope.row.percent"
            :show-text="true"
            status="success"
          ></el-progress>
          <div>
            {{
              scope.row.currentFetchNum ? scope.row.currentFetchNum : 0
            }}(当前) /
            {{ scope.row.totalFetchNum ? scope.row.totalFetchNum : 0 }}(总共)
          </div>
        </template>
      </el-table-column>

      <el-table-column
        prop="executeTimeDesc"
        label="执行耗时"
        min-width="18%"
        align="center"
      ></el-table-column>

      <el-table-column
        label="任务状态"
        prop="status"
        width="180"
        align="center"
      >
        <template slot-scope="scope">
          <!--          <el-button type="text" size="small">执行</el-button>-->
          <Tag type="info" v-if="scope.row.status == 0"> 未启用 </Tag>
          <Tag type="primary" v-if="scope.row.status == 1"> 等待执行 </Tag>
          <Tag type="warning" v-else-if="scope.row.status == 2"> 执行中 </Tag>
          <Tag type="success" v-else-if="scope.row.status == 3"> 已完成 </Tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="createdAt"
        label="创建时间"
        min-width="18%"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="updatedAt"
        label="更新时间"
        min-width="18%"
        align="center"
      ></el-table-column>
      <el-table-column prop="name" label="操作" min-width="25%" align="center">
        <template slot-scope="scope">
          <!--          <el-button type="text" size="small">执行</el-button>-->

          <el-button
            v-if="scope.row.status === 0"
            icon="el-icon-check"
            type="primary"
            size="small"
            @click="openFetchTask(scope.row.id)"
            >启用</el-button
          >
          <el-button
            icon="el-icon-delete"
            type="warning"
            size="small"
            @click="delFetchTask(scope.row.id)"
            >删除</el-button
          >
          <el-button
            icon="el-icon-circle-plus"
            type="primary"
            size="small"
            @click="cloneTask(scope.row)"
            >克隆</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 弹框-->
    <el-dialog
      :visible.sync="dialogFormVisible"
      class="Bulletframe"
      @close="cancelFrom"
    >
      <el-button type="text" class="Bulletframe_text">基础信息</el-button>

      <el-form :model="formLabelAlign">
        <el-form-item
          :label-width="formLabelWidth"
          class="fosno"
          label="抓取应用"
        >
          <el-input
            v-model="formLabelAlign.appName"
            @change="autoGenFetcherTaskName"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item
          :label-width="formLabelWidth"
          class="fosno"
          label="计划名称"
        >
          <el-input
            v-model="formLabelAlign.taskName"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          :label-width="formLabelWidth"
          class="fosno"
          label="应用类型"
        >
          <el-select
            v-model="formLabelAlign.category"
            placeholder="选择应用类型"
          >
            <el-option-group
              v-for="group in appCategory"
              :key="group.label"
              :label="group.label"
            >
              <el-option
                v-for="item in group.children"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>

        <el-button type="text" class="Bulletframe_text">抓取目标</el-button>
        <el-form-item
          :label-width="formLabelWidth"
          class="fosno"
          label="目标素材类型"
        >
          <el-select v-model="formLabelAlign.targetType">
            <el-option
              v-for="item in materialTargetType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" class="fosno" label="日期">
          <el-date-picker
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            type="daterange"
            :picker-options="pickerOptions2"
            v-model="formLabelAlign.time"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="startTime"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          :label-width="formLabelWidth"
          class="fosno"
          label="目标的URL"
        >
          <el-input
            v-model="formLabelAlign.url"
            prefix-icon="el-icon-search"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelFrom">取消</el-button>
        <el-button type="primary" @click="CreateTaskbtn()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getTask, cresteTask, getEnums } from "@/api/cloud";
import { openFetchTask, delFetchTask } from "@/api/air_center";
import moment from "moment";
export default {
  data() {
    return {
      /* 初始化数据表格数组 */
      newgetTask: [],
      appCategory: [],
      /* 下拉列表*/
      options: [],
      /* 提取任务*/
      condition: {
        filter: null,
      },
      /* 弹框的信息参数*/
      formLabelAlign: {
        taskName: "" /* 计划名*/,
        category: "",
        appName: "",
        startDate: "",
        endDate: "",
        url: "" /* 目标的url*/,
        targetType: 0,
        time: [],
      },
      /* 弹框的样式*/
      formLabelWidth: "110px",

      /* 抓取任务条件 目标素材类型 */
      materialTargetType: [
        { label: "全部类型", value: 0 },
        { label: "仅图片", value: 1 },
        { label: "仅视频", value: 2 },
      ],

      /* 弹窗的状态*/
      dialogFormVisible: false,
      pickerOptions2: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              const start = new Date();
              picker.$emit("pick", [start, start]);
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
              picker.$emit("pick", [start, start]);
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近半年",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30 * 6);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一年",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30 * 12);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      /* 任务状态*/
      stateFormat(row, column) {
        if (row.status === 1) {
          return `<Tag>等待执行</Tag>`;
        } else if (row.status === 2) {
          return "<Tag>正在执行</Tag>";
        } else if (row.status === 3) {
          return "<Tag>任务完成</Tag>";
        }
      },
    };
  },
  created() {
    this.APIGetEnums();
    this.APIGetTask();
  },
  mounted() {},
  watch: {
    newgetTask() {
      this.timer();
    },
  },
  destroyed() {
    clearTimeout(this.timer);
  },
  computed: {
    autoGenFetcherTaskName() {
      let ts = moment().format("HH:mm");
      this.formLabelAlign.taskName = `抓取_${this.formLabelAlign.appName}_广告素材_${ts}_Fetcher`;
    },
  },
  methods: {
    openFetchTask(id) {
      openFetchTask({ taskId: id }).then((res) => {
        if (res.status === 200) {
          this.$message({
            message: `打开抓取任务:${id}成功`,
            type: "success",
          });
          this.serchData();
        } else {
          this.$message({
            message: `${res.msg}`,
            type: "warning",
          });
        }
      });
    },

    delFetchTask(id) {
      console.log("del", id);
      delFetchTask({ taskId: id }).then((res) => {
        if (res.status === 200) {
          this.$message({
            message: `删除任务:${id}成功`,
            type: "success",
          });
          this.serchData();
        } else {
          this.$message({
            message: `${res.msg}`,
            type: "warning",
          });
        }
      });
    },

    /* 获取公共参数*/
    /* 定时器 */
    timer() {
      return setTimeout(() => {
        this.APIGetTask();
      }, 15000);
    },

    /* 获取公共参数 */
    APIGetEnums() {
      getEnums().then((res) => {
        console.log(res);
        this.options = res.result.data.categorys;
        this.fetchApps = res.result.data.fetchApps;
        this.appCategory = res.result.data.categorys;
      });
    },

    /* 获取任务列表 */
    APIGetTask() {
      let params = {
        appId: this.condition.filter,
      };
      getTask(params).then((res) => {
        console.log("抓取任务列表", res);
        this.newgetTask = res.result.data;
      });
    },

    /* 创建任务列表 */
    APIcresteTask() {
      let data = {
        /* 计划名*/
        taskName: this.formLabelAlign.taskName,
        /* 应用名*/
        appName: this.formLabelAlign.appName,
        /* 分类*/
        category: this.formLabelAlign.category,
        /* 目标URL*/
        sourceUrl: this.formLabelAlign.url,
        /* 开始/结束日期*/
        startDate: this.formLabelAlign.startDate,
        endDate: this.formLabelAlign.endDate,
        /* 素材目标类型 */
        fetchType: parseInt(this.formLabelAlign.targetType),
      };
      // let arr = [];
      // arr.push(data)
      cresteTask(data).then((res) => {
        console.log(res);
      });
    },

    /* 查询 */
    serchData() {
      console.log("查询" + "1111");
      this.APIGetTask();
    },

    /*  创建任务 */
    createTask() {
      this.dialogFormVisible = true;
    },

    cloneTask(row) {
      this.dialogFormVisible = true;
      this.formLabelAlign.taskName = row.taskName;
      this.formLabelAlign.appName = row.appName;
      this.formLabelAlign.category = String(row.category);
      this.formLabelAlign.url = row.sourceUrl;
      this.formLabelAlign.startDate = "";
      this.formLabelAlign.endDate = "";
      this.formLabelAlign.time = [];
    },

    cancelFrom() {
      this.dialogFormVisible = false;
      this.formLabelAlign.taskName = "";
      this.formLabelAlign.appName = "";
      this.formLabelAlign.category = "";
      this.formLabelAlign.url = "";
      this.formLabelAlign.startDate = "";
      this.formLabelAlign.endDate = "";
      this.formLabelAlign.time = [];
    },

    /* 创建抓取任务确定 */
    CreateTaskbtn(clone) {
      // 清理创建表单数据

      // this.formLabelAlign = {}

      this.APIcresteTask();
      setTimeout(this.APIGetTask(), 500);
      this.dialogFormVisible = false;
    },

    /* 日期 */
    startTime() {
      this.startDate();
      this.endDate();
      console.log("开始日期" + this.startDate(), "结束日期" + this.endDate());
      this.formLabelAlign.startDate = this.startDate();
      this.formLabelAlign.endDate = this.endDate();
    },

    /* 开始日期 */
    startDate() {
      let createTime = this.formLabelAlign.time[0];
      var date = new Date(createTime);
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = date.getDate();
      d = d < 10 ? "0" + d : d;
      const startDate = y + "-" + m + "-" + d;
      return startDate;
    },

    /* 结束日期 */
    endDate() {
      let endTime = this.formLabelAlign.time[1];
      var date = new Date(endTime);
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = date.getDate();
      d = d < 10 ? "0" + d : d;
      const endDate = y + "-" + m + "-" + d;
      return endDate;
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.text_con-progress {
  width: 150px;
  height: 5px;
  margin-top: 0.2rem;
  border-radius: 0.16rem;
  background-color: #999999;
}

.text_con-progress-complete {
  height: 100%;
  border-radius: 0.16rem;
  background-color: #ffae28;
}
</style>
