<template>
  <div class="oo-page">
    <div class="oo-server">
    	<h3 class="page-name" v-show="$customs.flag">{{title}}</h3>
      <div class="table-search">
        <Form :model="model" :label-width="100" ref="searchForm">
          <Row :gutter="15">
            <i-col span="6">
              <FormItem label="任务名称：" prop="nameLike">
                <Input v-model="model.nameLike" placeholder="请输入任务名称：" clearable></Input>
              </FormItem>
            </i-col>
            <i-col span="6">
              <div class="table-search-btns">
                <Button type="primary" icon="ios-search" @click="searchTable">搜索</Button>
                <Button
                  type="primary"
                  icon="ios-refresh"
                  @click="resetSearch"
                  style="margin-left:10px"
                >重置</Button>
              </div>
            </i-col>
          </Row>
        </Form>
      </div>
      <cs-dynamic-table ref="child" :prop="csTable" :parent="this">
        <template slot="form" scope="props">
          <task-form
            :model="props.obj"
            :action="props.action"
            :tableVm="props.tableVm"
            @closeModal="props.closeModal"
            :tableInfo="props.tableInfo"
            ref="form"
          ></task-form>
        </template>
      </cs-dynamic-table>
      <Modal
        v-model="detailFlag"
        title="轮询任务明细"
        width="80"
        :mask-closable="false"
        @on-cancel="closeDetail"
      >
        <report-recurring ref="result2" @closeModal="closeDetail"></report-recurring>
        <div slot="footer"></div>
      </Modal>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import taskForm from "./task-form.vue";
import reportRecurring from "./report-recurring.vue";
import CmdRecurring from "../command/command-recurring.vue";

@Component({
  components: {
    CmdRecurring,
    reportRecurring,
    taskForm
  }
})
export default class AuditTask extends Vue {
  private model: any = {};
  private modelFlag: boolean = false;
  private detailFlag: boolean = false;
  private startLoading: boolean = false;
  private stopLoading: boolean = false;
title: any = "";
  private csTable: any = {
    formWidth: 80,
    parentVm: this,
    dataSrc: this.$msPrefix.automation + "/api/v1/data/list/auditMission",
    delSrc: this.$msPrefix.automation + "/api/v1/data/delete/auditMission/",
    batchDelUri: this.$msPrefix.automation + "/api/v1/data/batch/auditMission",
    dataProp: "data.content",
    postMethod: true,
    pageableProp: {
      pageSize: "data.size",
      total: "data.totalElements",
      currentPage: "data.number"
    },
    showIndex: true,
    emptyModel: {
      cron:"",
      description:"",
      name:"",
      policyId:""
    },
    actions: {
      //表头操作按钮
      replace: false,
       def: [
      ]
    },
    columns: [
      {
        type: "selection",
        width: 60,
        align: "center"
      },
      {
        key: "name",
        title: "任务名称",
        align: "center",
        ellipsis: true,
        tooltip: true,
        sortable: "custom"
      },
      {
        key: "excuteType",
        title: "类型",
        align: "center",
        ellipsis: true,
        tooltip: true,
        render: (h, params) => {
          let excuteType = params.row.excuteType == "immediate" ? "立即执行" : "延迟执行";
          return h("span", excuteType);
        }
      },
      {
        key: "cron",
        title: "cron表达式",
        align: "center",
        ellipsis: true,
        tooltip: true,
        sortable: "custom"
      },
      // {
      //   key: "description",
      //   title: "任务详情",
      //   align: "center",
      //   ellipsis: true,
      //   tooltip: true
      // },
      {
        key: "status",
        title: "状态",
        align: "center",
        ellipsis: true,
        tooltip: true,
        sortable: "custom",
        render: (h, params) => {
          let statusDes = params.row.status == 0 ? "启动" : params.row.status == 2 ? "已执行" : "停止";
          return h("span", statusDes);
        }
      },
      {
        key: "result",
        title: "结果",
        align: "center",
        ellipsis: true,
        tooltip: true,
        render: (h, params) => {
          let menus = [
            {
              icon: "ios-create-outline",
              action: "detail",
              label: "任务明细",
              type: "primary"
            }
          ];
          let detailEvent = this.detailEvent;
          return h("div", [
            h("CsButton", {
              props: {
                actions: menus,
                click: detailEvent,
                data: params.row,
                size: "small",
                styleCss: "marginRight:5px",
                disabled: params.row._disabled
              }
            })
          ]);
        }
      },
      {
        key: "action",
        title: "操作",
        minWidth: 200,
        align: "center",
        render: (h, params) => {
          console.error('sssss',params.row.excuteType == "delay" && params.row.status)
          let menus = [
            {
              icon: "ios-create-outline",
              action: "update",
              label: "编辑",
              type: "primary"
            },
            {
              icon: "md-trash",
              action: "delete",
              label: "删除",
              type: "error"
            },
            {
              icon: "ios-play",
              action: "start",
              label: "启用",
              // loading: this.getStartLoading(),
              type: "success",
              disabled: (params.row.excuteType == "delay" && params.row.status == 0 )
            },
            {
              icon: "ios-pause",
              action: "stop",
              label: "停止",
              // loading: this.getStopLoading(),
              type: "warning",
              disabled: (params.row.excuteType == "immediate" && params.row.status == 2) || (params.row.excuteType == "delay" && params.row.status == 1)
            }
          ];
          let clickEvent = this.clickEvent;
          return h("div", [
            h("CsButton", {
              props: {
                actions: menus,
                click: clickEvent,
                data: params.row,
                size: "small",
                styleCss: "marginRight:5px",
                disabled: params.row._disabled
              }
            })
          ]);
        }
      }
    ]
  };

  detailEvent(name: string, obj: any) {
    this.detailFlag = true;
    (this.$refs.result2 as any).postTableData(obj.id, obj.name, false);
    console.log(name, obj);
     (this.$globalFun() as any).getMethod('show')
  }
  closeDetail() {
    this.detailFlag = false;
    (this.$globalFun() as any).getMethod('close')
  }

  clickEvent(name: string, obj: any, index: number, action: any) {
    if (name == "delete") {
      (this.$refs.child as any).handleDelete(obj.id);
    } else if (name == "update") {
      (this.$refs.child as any).formInfo.title =
        name == "update" ? "编辑" : "详情";
      (this.$refs.child as any).formInfo.action =
        name == "update" ? "update" : "detail";
      (this.$refs.child as any).formInfo.model = _.cloneDeep(obj);
      let taskFrom = this.$refs.form as any;
      let policys = taskFrom.$refs.policys;
      policys.policyId = obj.policyId;
      policys.updateData();
      if (obj.job.jobRes) {
        let res = obj.job.jobRes.map(job => job.id.res);
        taskFrom.resList = res;
      }
      if (obj.cron) {
        taskFrom.cron = obj.cron;
      }
      (this.$refs.child as any).dialogVisible = true;
      (this.$globalFun() as any).getMethod('show')
    } else if (name == "start") {
      this.startTask(obj, action);
    } else {
      this.abandomTask(obj, action);
    }
    
  }

  // getStartLoading() {
  //   return this.startLoading;
  // }

  // getStopLoading() {
  //   return this.stopLoading;
  // }

  getPostData() {
    var data = _.cloneDeep(this.model);
    if (data.scriptServerEntity) {
      data = JSON.parse(
        JSON.stringify(data).replace(
          /scriptServerEntity/g,
          "scriptServerEntity.id"
        )
      );
    }
    var postData = {};
    this.filterData(postData, data);
    this.csTable.postData = postData;
  }
  filterData(postData, data) {
    var keys = Object.keys(data);
    keys.forEach(item => {
      if ([0, false].includes(data[item]) || (data[item] && data[item])) {
        postData[item] = ["" + data[item]];
      }
    });
  }

  searchTable() {
    this.getPostData();
    console.error(this.csTable.postData);
    (this.$refs.child as any).getData();
  }
  resetSearch() {
    (this.$refs.searchForm as any).resetFields();
  }
  mounted() {
    // this.getAllList();
    this.title = (this.$globalFun() as any).getMethod('title')
  }
  addTask() {
    (this.$refs.child as any).formInfo.model = {};
    (this.$refs.child as any).formInfo.title = "新建任务";
    (this.$refs.child as any).formInfo.action = "save";
    let taskFrom = this.$refs.form as any;
    let policys = taskFrom.$refs.policys;
    policys.policyId = "";
    policys.updateData();
    taskFrom.resList = [];
    taskFrom.cron = "* * * * *";
    (this.$refs.child as any).dialogVisible = true;
     (this.$globalFun() as any).getMethod('show')
  }

  handleDelete() {}
  startTask(obj: any, action: any) {
    if (obj.job.jobRes) {
      let jobres = obj.job.jobRes;
      let res = jobres.map(item => item.id.res);
      obj.resources = res;
    }

    this.startLoading = true;
    this.getApiData(
      "post",
      this.$msPrefix.automation + "/api/v1/audit/start",
      obj,
      res => {
        if (res.rtnCode == 0) {
          this.$tools.message("success", "启动任务成功");
          (this.$refs.child as any).getData();
        }
        this.startLoading = false;
      },
      err => {
        this.startLoading = false;
        // this.$tools.message("error", "启动任务失败！");
      }
    );
  }
  abandomTask(obj: any, action: any) {
    if (obj.job.jobRes) {
      let jobres = obj.job.jobRes;
      let res = jobres.map(item => item.id.res);
      obj.resources = res;
    }
    this.stopLoading = true;
    this.getApiData(
      "post",
      this.$msPrefix.automation + "/api/v1/audit/stop",
      obj,
      res => {
        if (res.rtnCode == 0) {
          this.$tools.message("success", "停止任务成功！");
          (this.$refs.child as any).getData();
        }
        this.stopLoading = false;
      },
      err => {
        this.$tools.message("error", "停止任务失败！");
        this.stopLoading = false;
      }
    );
  }
  closeModal() {
    this.modelFlag = !1;
  }
}
</script>
