<template>
  <a-drawer
      width="100%"
      :visible="show"
      @close="close"
      :after-visible-change="openDrawer"
      :destroy-on-close="true"
      class="monitoring_container"
    >
    <template slot="title">
      <a-button @click="close" icon="caret-left" class="a_back"></a-button>
      <span class="detail_title">
        周期任务监控
        <template v-if="data.jobType=='datadev'">(数据开发)</template>
      </span>
      <div class="refresh">
        <a-button type="link" @click="toJobTask">查看调度任务</a-button>
        <span @click="refresh">刷新&nbsp;<a-icon type="reload" /></span>
      </div>
    </template>
    <div class="monitoring_content">
      <a-card size="small" title="任务信息概览" class="no_border">
        <a-row class="card-list" :gutter="20">
          <a-col :span="6">任务名称：{{data.jobName}}</a-col>
          <a-col :span="6">状态：
            <a-tag class="tag_or" v-if="data.taskState == 'SUCCESS'">运行成功</a-tag>
            <a-tag class="tag_value" v-else-if="data.taskState == 'RUNNING'">运行中</a-tag>
            <a-tag class="tag_and" v-else-if="data.taskState == 'WALKING'">异常运行中</a-tag>
            <a-tag class="tag_entry" v-else>{{ returnTaskState(data.taskState) }}</a-tag>
          </a-col>
          <a-col :span="6">创建时间：{{data.createTime}}</a-col>
          <a-col :span="6">负责人：{{data.createBy || '--'}}</a-col>
        </a-row>
        <a-row class="card-list" :gutter="20">
          <a-col :span="6">所属集群：{{data.clusterName || '--'}}</a-col>
          <a-col :span="6">开始时间：{{data.startTime}}</a-col>
          <a-col :span="6">结束时间：{{data.endTime || '--'}}</a-col>
          <!-- <a-col :span="6">总吞吐量：{{mainNodeInf.length > 0 ? mainNodeInf[0].ioCount : '--'}}</a-col> -->
          <a-col :span="6">总吞吐量：{{taskList.length > 0 ? taskList[0].insertCount : '--'}}</a-col>
        </a-row>
        <a-row class="card-list last" :gutter="20">
          <a-col :span="6">任务ID：{{data.id}}</a-col>
          <a-col :span="6">作业ID：{{data.jobId}}</a-col>
        </a-row>
      </a-card>
      <div class="card_top">
        <a-tabs default-active-key="task">
          <a-tab-pane key="task" tab="任务展示">
            <div class="Process_pre">
              <vxe-table
                ref="taskTree"
                show-overflow
                show-header-overflow
                border
                resizable
                :loading="taskLoading"
                :row-config="{ isHover: true }"
                :data="taskList"
                :tree-config="{
                  expandAll: true,
                  reserve: true,
                  trigger: 'cell'
                }"
                height="auto"
              >
                <vxe-column type="seq" title="序号" width="80" align="center"></vxe-column>
                <vxe-column field="name" title="名称" tree-node></vxe-column>
                <vxe-column field="type" title="类别">
                  <template #default="{ row }">
                    {{ row.type | filterType }}
                  </template>
                </vxe-column>
                <vxe-column field="status" title="状态">
                  <template #default="{ row }">
                    <a-tag class="tag_or" v-if="row.status == 'SUCCESS'">运行成功</a-tag>
                    <a-tag class="tag_value" v-else-if="row.status == 'RUNNING'">运行中</a-tag>
                    <a-tag class="tag_and" v-else-if="row.status == 'WALKING'">异常运行中</a-tag>
                    <a-tag class="tag_entry" v-else>{{ returnTaskState(row.status) }}</a-tag>
                  </template>
                </vxe-column>
                <vxe-column field="runningCount" title="运行中/成功/失败(flink任务数量)">
                  <template #header="{}">
                    <span>运行中/成功/失败</span>
                    <a-tooltip placement="rightTop">
                      <template slot="title">flink任务数量，即"转换"的数量</template>
                      <a-icon type="info-circle" style="margin-left:5px;"/>
                    </a-tooltip>
                  </template>
                  <template #default="{ row }">
                    <span class="running">{{ row.runningCount || 0 }}</span>/
                    <span class="success">{{ row.successCount || 0 }}</span>/
                    <span class="fail">{{ row.failedCount || 0 }}</span>
                  </template>
                </vxe-column>
                <vxe-column field="startTime" title="开始时间"></vxe-column>
                <vxe-column field="endTime" title="结束时间"> </vxe-column>
                <vxe-column field="period" title="运行时长"> </vxe-column>
                <vxe-column field="insertCount" title="吞吐数量"> </vxe-column>
                <vxe-column field="title" title="操作" align="center" v-if="data.jobType=='datadev'">
                  <template #default="{ row }">
                    <a-button
                      v-if="row.type == 'model' || row.type == 'indicator'"
                      type="link"
                      @click="toDebug(row)"
                    >
                      调试
                    </a-button>
                    <span v-else>--</span>
                  </template>
                </vxe-column>

                <template #empty>
                  <a-empty
                    :image-style="{
                      height: '80px',
                    }"
                  >
                    <span slot="description"> 暂无数据 </span>
                  </a-empty>
                </template>
              </vxe-table>
            </div>
          </a-tab-pane>
          <a-tab-pane key="process" tab="流程预览" force-render>
            <a-spin :spinning="jobLoading">
              <div class="Process_pre">
                <devLinkProcess v-if="data.jobType == 'datadev'" :jobId="data.jobId" :nodeList="linkNodeList"></devLinkProcess>
                <jobProcess v-else :jobId="data.jobId" :dataDetail="jobProcessDetail" :taskList="taskList"></jobProcess>
              </div>
            </a-spin>
          </a-tab-pane>
        </a-tabs>
      </div>
      <a-card size="small" title="运行日志" class="no_border card_top">
        <a-spin :spinning="logLoading">
          <div class="log_container">
            <logCollapse :data="logData"></logCollapse>
          </div>
        </a-spin>
      </a-card>
    </div>
    <debugDesign v-model="debugInfo.show" :type="debugInfo.type" :showEdit="false" :info="debugInfo.info"></debugDesign>
  </a-drawer>
</template>
<script>
const $dataIntegration = require("@/api/dataIntegration");
const $standardModel = require("@/api/datadevelopment/standardModel");
const logCollapse = require("@/components/logCollapse").default;
const devLinkProcess = require("../../components/devlinkprocess.vue").default;
const jobProcess = require("../../components/jobprocess.vue").default;
const debugDesign = require("@/components/debugDesign").default;

export default {
  components: {
    logCollapse,
    devLinkProcess,
    jobProcess,
    debugDesign
  },
  props: {
    visible: [Boolean],
    data: [Object]
  },
  computed:{
    show: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
    returnTaskState() {
      return (val) => {
        let item = this.statueList.find(item => { return item.value ==  val})
          if (item) {
            return item.label;
          } else {
            return "未知"
          }
      }
    }
  },
  filters: {
    filterType(val) {
      switch(val) {
        case "job":
          return "作业"
        case "transform":
          return "转换"
        case "model":
          return "事实模型"
        case "sql":
          return "SQL"
        case "indicator":
          return "指标"
        default: 
          return "未知分类"
      }
    }
  },
  data() {
    return {
      timer: undefined,
      taskLoading: false,
      jobLoading: false,
      job: {},
      taskList: [],
      logLoading: false,
      logData: [],
      statueList: [],
      linkNodeList: [],
      jobProcessDetail: {},
      debugInfo: {
        show: false,
        type: undefined,
        info: {}
      }
    }
  },
  methods: {
    openDrawer(val) {
      if(val) {
        this.statueList = $dataIntegration.monitorStatueList;
        this.getTaskList();
        this.initData();
        this.getLog();
        this.timer = setInterval(() => {
          this.getTaskList();
        }, 1000 * 60)
      }
    },
    /**
     * @Author: y_zp
     * @description: 手动刷新
     */
    refresh() {
      this.taskLoading = true;
      this.getTaskList();
      this.getLog();
    },
    /**
     * @Author: y_zp
     * @description: 任务展示
     */
    getTaskList() {
      //定时刷新时，不需要加载loading
      this.taskList.length == 0 && (this.taskLoading = true);
      $dataIntegration
        .getTaskTree(this.data.id)
        .then((req) => {
          this.taskList = [];
          this.taskList.push(req.data);
        })
        .finally(() => {
          this.$refs.taskTree && this.$refs.taskTree.setAllTreeExpand(true);
          this.taskLoading = false;
          // 定时更新流程预览节点状态
          // if (this.job.data && this.job.data.jsonDetail) {
          //   try {
          //     let cells = JSON.parse(this.job.data.jsonDetail);
          //     this.setCanvas(cells, this.job);
          //   } catch (e) {}
          // }
        })
    },

    /**
     * @Author: y_zp
     * @description: 运行日志
     */
    getLog() {
      this.logLoading = true;
      if (this.data.jobType == "datadev") {
        $standardModel
          .getMonitorTaskLog(this.data.id)
          .then((req) => {
            this.logData = req.data;
          })
          .finally(() => {
            this.logLoading = false;
          })
      } else {
        $dataIntegration
          .getTaskLog(this.data.id)
          .then((req) => {
            this.logData = req.data;
          })
          .finally(() => {
            this.logLoading = false;
          })
      }
    },

    /**
     * @Author: 
     * @description: 流程预览
     */
    initData() {
       this.jobLoading = true;
      if(this.data.jobType == "datadev") {
        $standardModel
          .getMonitorNodeList({ linkId: this.data.jobId })
          .then((req) => {
            this.linkNodeList = req.data;
        }).finally(() => {
          this.jobLoading = false;
        })
      } else {
        $dataIntegration
          .getJobDetail({ id: this.data.jobId })
          .then((req) => {
            let job = req.data;
            if (job) {
              this.jobProcessDetail = job
            } else {
              this.jobLoading = false;
            }
          })
          .finally(() => {
            this.jobLoading = false;
          })
      }
    },
    /**
     * @Author: y_zp
     * @description: 调试
     */
    toDebug(row) {
      console.log(row)
      this.debugInfo = {
        show: true,
        type: row.type == "indicator" ? 2 : 1,
        info: {
          id: row.stepId
        }
      }
    },
    /**
     * @Author: y_zp
     * @description: 查看调度任务
     */
    toJobTask() {
      this.$router.push({
        path: "/periodicTasks",
        query: {
          type: "CRON",
          scheduleJobId: this.data.jobInfoId,
        }
      });
      this.close();
    },
    
    close() {
      this.show = false;
      this.taskList = [];
      this.timer && clearInterval(this.timer)
    }

  }
}
</script>
<style lang="less" scoped>
.monitoring_container {
  .a_back {
    position: absolute;
    top:0;
    left: 0;
    width: 54px;
    height: 54px;
    border: 0;
    font-size: 20px;
    color: rgba(0, 0, 0, 0.7);
    border-radius: 0;
    border-right: 1px solid #e9e9e9;
    &:hover {
      background: rgba(0, 0, 0, 0.1);
    }
  }
  .detail_title {
    margin-left: 40px;
  }
  .refresh {
    cursor: pointer;
    float: right;
    margin-right: 30px;
    .ant-btn {
      font-size: 16px;
      margin-top: -4px;
    }
  }
  .monitoring_content {
    height: calc(100vh - 85px);
    overflow: hidden;
    overflow-y: scroll;
  }
  .ant-drawer-content {
    background: #eff2fd;
  }
  .card-list {
    padding: 8px 4px 0;
    &.last {
      padding-bottom: 12px;
    }
  }
  .card_top {
    margin-top: 12px;
  }
  .Process_pre {
    width: 100%;
    height: 280px;
    margin-bottom: 12px;
    .running {
      color: #2d5afa;
      margin: 0 5px;
    }
    .success {
      color: #29DF7E;
      margin: 0 5px;
    }
    .fail {
      color: #EA4B4B;
      margin: 0 5px;
    }
  }
  .table-list {
    padding-bottom: 12px;
    height: 300px;
  }
  .log_container {
    padding-bottom: 12px;
    max-height: calc(100vh - 150px);
    overflow: hidden;
    overflow-y: scroll;
  }
}
</style>