<template>
  <div class="periodictaskslog_container body_container">
    <a-spin :spinning="loading">
      <a-row>
        <a-col :span="24">
          <span class="search_label first">任务类型：</span>
          <a-select
            class="small"
            allowClear
            placeholder="请选择"
            :dropdownMatchSelectWidth="false"
            dropdownClassName="type-select-dropdown"
            v-model="pager.appType"
            :options="appTypeList"
            @change="querySearch"
          >
          </a-select>
          <span class="search_label">任务：</span>
          <a-select
            allowClear
            class="small"
            placeholder="请选择"
            show-search
            :default-active-first-option="false"
            option-filter-prop="children"
            v-model="pager.jobId"
            :dropdownMatchSelectWidth="false"
            dropdownClassName="job-select-dropdown"
            @search="searchJobList"
            @change="querySearch"
            :options="jobList"
          >
          </a-select>
          <span class="search_label">状态：</span>
          <a-select
            class="small"
            placeholder="请选择"
            v-model="pager.logStatus"
            :options="statusList"
            @change="querySearch"
          >
          </a-select>
          <span class="search_label">调度时间：</span>
          <a-range-picker
            style="width: 360px;"
            :locale="locale"
            :ranges="rangesDate"
            :default-value="[moment().startOf('day'), moment().endOf('day')]"
            :disabled-date="disabledDate"
            :placeholder="['请选择','请选择']"
            :show-time="{ format: 'HH:mm:ss' }"
            format="YYYY-MM-DD HH:mm:ss"
            separator="至"
            @change="onTimeChange">
            <a-icon slot="suffixIcon" type="calendar" />
          </a-range-picker>
          <div class="search_btn">
            <a-button type="primary" icon="search" @click="querySearch">查询</a-button>
            &nbsp;
            <a-button type="primary" icon="delete" @click="clearLog">清理</a-button>
          </div>
        </a-col>
        <!-- <a-col :span="4" align="right">
          <a-button type="primary" icon="search" @click="querySearch">查询</a-button>
          &nbsp;
          <a-button type="primary" icon="delete" @click="clearLog">清理</a-button>
        </a-col> -->
      </a-row>
      <div class="table_list">
        <vxe-table
          show-overflow
          show-header-overflow
          border
          resizable
          :row-config="{ isHover: true }"
          :data="lists"
          height="auto"
        >
          <vxe-column type="seq" title="序号" width="50" align="center"></vxe-column>
          <vxe-column field="jobInfo.jobDesc" title="任务名称"></vxe-column>
          <vxe-column field="jobInfo.jobType" title="任务类型">
            <template #default="{ row }">
              {{ appTypeListForRow(row.jobInfo.jobType) }}
            </template>
          </vxe-column>
          <vxe-column field="triggerTime" title="调度时间"></vxe-column>
          <vxe-column field="triggerCode" title="调度结果">
            <template #default="{ row }">
              <a-tag class="tag_or" v-if="row.handleCode == 200">已成功</a-tag>
              <a-tag class="tag_value" v-else-if="row.triggerCode == 200 & row.handleCode == 0">进行中</a-tag>
              <a-tag class="tag_entry" v-else>已失败</a-tag>
              <!-- {{ row.triggerCode | filterTriCode(row.handleCode) }} -->
            </template>
          </vxe-column>
          <vxe-column title="调度备注">
            <template #default="{ row }">
              <a-popover placement="rightTop">
                <template slot="content">
                  <p style="max-width:500px;" v-html="row.triggerMsg"></p>
                </template>
                <a-button type="link">详细</a-button>
              </a-popover>
            </template>
          </vxe-column>
          <vxe-column field="handleTime" title="执行时间"></vxe-column>
          <vxe-column field="handleCode" title="执行结果">
            <template #default="{ row }">
              <a-tag class="tag_or" v-if="row.handleCode == 200">已成功</a-tag>
              <a-tag class="tag_value" v-else-if="row.triggerCode == 200 & row.handleCode == 0">进行中</a-tag>
              <a-tag class="tag_entry" v-else>已失败</a-tag>
              <!-- {{ row.handleCode | filterHandleCode(row.triggerCode) }} -->
            </template>
          </vxe-column>
          <vxe-column field="handleMsg" title="执行备注"></vxe-column>
          <vxe-column title="操作" width="120" align="center">
            <template #default="{ row }">
              <a-button type="link" v-if="row.triggerCode == 200 || row.handleCode == 200" @click="logFlow(row)">执行日志</a-button>
            </template>
          </vxe-column>
          <template #empty>
            <a-empty
              :image-style="{
                height: '80px',
              }"
            >
              <span slot="description"> 暂无数据 </span>
            </a-empty>
          </template>
        </vxe-table>
      </div>
      <vxe-pager
        background
        :current-page.sync="pager.pageNum"
        :page-size.sync="pager.pageSize"
        :total="total"
        @page-change="getFlowList"
        :layouts="['Total', 'PrevJump', 'JumpNumber', 'NextJump', 'FullJump']"
      >
      </vxe-pager>
    </a-spin>
    <a-modal
      v-model="show"
      title="日志清理"
      okText="保存"
      cancelText="取消"
      @ok="submit"
    >
      <a-form-model
        :label-col="{span: 4}"
        :wrapper-col="{span: 18}"
        :model="formList"
        :rules="{
          type: [{ required: true, message: '请选择清理方式', trigger: 'change' }]
        }"
        ref="formList"
      >
        <a-form-model-item label="执行器" prop="jobGroup">
          <a-select
            placeholder="请选择"
            v-model="formList.jobGroup"
            :options="jobGroupList"
            disabled
          >
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="任务" prop="jobId">
          <a-select
            placeholder="请选择"
            show-search
            :default-active-first-option="false"
            option-filter-prop="children"
            v-model="formList.jobId"
            @search="searchJobList"
            :options="jobList"
            disabled
          >
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="清理方式" prop="type">
          <a-select
            placeholder="请选择"
            :options="typeList"
            v-model="formList.type"
          >
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-drawer
      :visible="logCont.show"
      width="50%"
      :destroyOnClose="true"
      class="periodictask_log_cont"
      @close="logCont.show=false"
    >
      <template slot="title">
        日志内容
        <a-button class="copy" type="primary" size="small" @click="copyLog" icon="copy">复制</a-button>
      </template>
      <div class="dispatch_showLog_container">
        <jsonView :data="logCont.info"></jsonView>
      </div>
    </a-drawer>
  </div>
</template>
<script>
/**
 * @Author: y_zp
 * @description: 调度日志-周期任务日志
 */
import selectdata from '../components/selectdata.js'
const $dispatchcenter = require("@/api/dispatchcenter");
const $appService = require("w-vue-middle/api/appService");
import jsonView from "vue-json-views";

export default {
  components: {
    jsonView
  },
  data() {
    let rangesDate = {
      近1小时: [moment().subtract(1, 'hours'), moment()],
      近3小时: [moment().subtract(3, 'hours'), moment()],
      近12小时: [moment().subtract(12, 'hours'), moment()],
      近24小时: [moment().subtract(1, 'days'), moment()],
      近7天: [moment().subtract(7, 'days'), moment()],
      近1个月: [moment().subtract(1, 'months'), moment()]
    }
    return {
      loading: false,
      rangesDate: rangesDate,
      total: 1,
      appTypeList: [],
      jobGroupList: [],
      initJobList: [],
      jobList: [],
      statusList: [],
      typeList: [],
      pager: {
        pageNum: 1,
        pageSize: 15,
        appType: undefined,
        jobId: undefined,
        logStatus: undefined,
        filterTime: moment().startOf('day').format('YYYY-MM-DD HH:mm:ss') + ' - ' + moment().endOf('day').format('YYYY-MM-DD HH:mm:ss'),
        scheduleType: undefined
      },
      lists: [],
      show: false,
      formList: {
        jobGroup: 0,
        jobId: 0,
        qlfs: undefined
      },
      logCont: {
        show: false,
        info: {}
      }
    }
  },
  filters: {
    filterTriCode(v1, v2) {
      if(v2 == 200) {
        return '成功'
      }  else if(v1 == 200 && v2 == 0) {
        return '进行中'
      } else {
        return '失败'
      }
    },
    filterHandleCode(v1, v2) {
      if (v1 == 200) {
        return '成功'
      } else if(v1 == 0 && v2 == 200) {
        return '进行中'
      } else {
        return '失败'
      }
    }
  },
  watch: {
    '$route'(val) {
      this.pager.scheduleType = this.$route.query.type || val.meta.type
      this.pager.jobId = this.$route.query.jobId || 0;
      this.getAppType();
      this.getjobGroup();
      this.getJobInfo();
      this.getFlowList();
    }
  },
  computed: {
  	appTypeListForRow(jobType) {
      return function (jobType) {
        let appType = this.appTypeList.find(item  => item.value == jobType);
        if(appType){
          return appType.label;
        }
        return "--";
      }
  	}
  },
  created() {
    this.pager.scheduleType = this.$route.query.type || this.$route.meta.type
    this.pager.jobId = this.$route.query.jobId || 0
    this.statusList = selectdata.statusList;
    this.typeList = selectdata.typeList;
    this.getAppType();
    this.getjobGroup();
    this.getJobInfo();
    this.getFlowList();
  },
  methods:{
    /**
     * @Author: y_zp
     * @description: 设置不可选日期
     */
    disabledDate(cur) {
      return cur && cur > moment().endOf('day')
    },

    /**
     * @Author: y_zp
     * @description: 获取列表
     */
    getFlowList() {
      this.loading = true
      $dispatchcenter
        .getjobLogList(this.pager)
        .then((req) => {
          this.total = Number(req.count)
          this.lists= req.data
        })
        .finally(() => {
          this.loading = false
        })
    },

    /**
     * @Author: y_zp
     * @description: 获取任务列表
     */
    getJobInfo() {
      $dispatchcenter
        .getJobInfo({
          pageNum: 1,
          pageSize: 1000000,
          queryParams: {
            F_scheduleType_eq: this.pager.scheduleType,
          }
        })
        .then((req) => {
          let list = req.data.map(item => {
            return {
              label: item.jobDesc,
              value: item.jobInfoId
            }
          })
          this.initJobList = list;
          this.initJobList.unshift({
            label: '全部',
            value: 0
          });
          let newList  = this.initJobList.length > 15 ? this.initJobList.slice(0, 15) : this.initJobList;
          // 点击调度任务[查询日志]
          if(this.pager.jobId) {
            let curItem = newList.find(i => { return i.value == this.pager.jobId })
            if(!curItem) {
              let v = this.initJobList.find(i => { return i.value == this.pager.jobId });
              newList.splice(1, 0 , v)
            }
          }
          this.jobList = newList;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /**
     * @Author: y_zp
     * @description: 任务列表搜索
     */
    searchJobList(val) {
      let templist = this.initJobList;
      if (templist.length > 0) {
        if (val) {
          templist = templist.filter(item => {
            return item.label && item.label.toLocaleLowerCase().indexOf(val.toLocaleLowerCase()) > -1;
          })
        }
        templist = templist.slice(0, 15);
      }
      this.jobList = templist;
    },

    /**
     * @Author: y_zp
     * @description: 获取执行器列表
     */
    getjobGroup() {
      this.jobGroupList = []
      $dispatchcenter
        .getJobList({
          pageNum: 1,
          pageSize: 100,
        })
        .then((req) => {
          req.data.forEach(item => {
            this.jobGroupList.push({
              label: item.title,
              value: item.jobGroupId
            });
            this.jobGroupList.unshift({
              label: '全部',
              value: 0
            })

          })
        })
        .finally(() => {});
    },
    /**
     * @Author: y_zp
     * @description: 获取应用类型列表
     */
    getAppType() {
      $appService
        .getSysDictData({ pageNum: 1, pageSize: 1000000, queryParams: { F_dictType_eq: "job_type" }})
        .then((req) => {
          this.appTypeList = req.data.map(item => {
            return {
              label: item.dictLabel,
              value: item.dictValue
            }
          })
        })
    },

    /**
     * @Author: y_zp
     * @description: 查询
     */
    querySearch() {
      this.pager.pageNum = 1
      this.getFlowList()
    },

    /**
     * @Author: y_zp
     * @description: 选择时间
     */
    onTimeChange(date, dateString) {
      this.pager.filterTime = dateString[0] + ' - ' + dateString[1]
      this.querySearch()
    },

    /**
     * @Author: y_zp
     * @description: 执行日志
     */
    logFlow(row) {
      $dispatchcenter
      .logDetailCat({
        executorAddress: row.executorAddress,
        fromLineNum: 1,
        logId: row.jobLogId,
        triggerTime: Date.parse(row.triggerTime)
      })
      .then((req) => {
        this.logCont = {
          show: true,
          info: { logContent: req.data.content.logContent }
        }
      })
    },
    /**
     * @Author: y_zp
     * @description: 日志复制
     */
    copyLog() {
      this.$copyClipboard(this.logCont.info.logContent)
    },

    /**
     * @Author: y_zp
     * @description: 日志清理
     */
    clearLog() {
      this.show = true
    },

    /**
     * @Author: y_zp
     * @description: 清理日志提交
     */
    submit() {
      this.$refs.formList.validate((valid) => {
        if(valid) {
          $dispatchcenter
            .jobLogDelete({ ...this.formList })
            .then((req) => {
              this.show = false;
              this.$message.success("清理日志成功！");
            })
            .finally(() => {
              this.getFlowList()
            })
        }
      })
    }

  }
}
</script>
<style lang="less" scoped>
.periodictaskslog_container {
  .search_btn {
    float: right;
    text-align: right;
  }
  .search_label.first {
    margin-left: 0;
  }
  .ant-select.small {
    width: 100px;
  }
  .ant-select.middle {
    width: 140px;
  }
  .table_list {
    width: 100%;
    height: calc(100vh - 230px);
    display: inline-block;
    margin-top: 16px;
  }
}
.ant-select-dropdown {
  &.job-select-dropdown {
    width: 200px;
  }
  &.type-select-dropdown {
    width: 140px;
  }
}
.ant-card.remark .ant-card-head {
  padding-left: 14px !important;
}
.ant-card.remark .ant-card-head::before {
  left: 3px !important;
}
.ant-card.remark .ant-card-body {
  padding-left: 4px !important;
}
.dispatch_showLog_container {
  height: calc(100vh - 100px);
  overflow: hidden;
  overflow-y: scroll;
  /deep/.json-view-container .json-view .json-value {
    white-space: pre-line;
  }
}
.periodictask_log_cont {
  .copy {
    cursor: pointer;
    float: right;
    margin-right: 30px;
  }
}
</style>