<template>
  <div>
    <manager-ui
      :loading="loading"
      :query-model="qureyParam"
      :query-items="queryItems"
      :static-data="staticData"
      :column-items="columnItems"
      :table-data="tableData"
      :pagination="page"
      :spread-threshold="1"
      :show-add-btn="showAddBtn"
      show-table-tools
      @create="addPage"
      @selection-change="handleSelectionChange"
      @searchClick="searchClick"
      @search="search"
      @resetForm="reset"
    >
      <template slot="taskType" slot-scope="scope">
        {{ scope.scope.row.taskType|toCase(staticData.taskTypeList,'dataId', 'dataName') }}
      </template>
      <template slot="tableTools">
        <el-button v-rule-code="'dataAddress_del'" type="text" icon="el-icon-delete-solid">
          <span @click="batchDeleteClick">
            删除
          </span>
        </el-button>
      </template>
      <template slot="chartType" slot-scope="scope">
        {{ scope.scope.row.chartType|toCase(staticData.chartTypeList,'dataId', 'dataName') }}
      </template>
      <template slot="action" slot-scope="scope">
        <el-context-menu :menus="menus" :scope="scope.scope" :default="3" @oper="clickRow" />
      </template>
    </manager-ui>
    <!-- 操作日志 -->
    <manager-dialog :visible.sync="LogDialog" title="操作日志" @close="closeOperLog">
      <c-Table
        :column="operLogColumns"
        :table-data="operLogData"
        :pager-count="pagerCount"
        :page="pageQueryLog"
        @handleCurrentChange="handleCurrentChangeLog"
        @handleSizeChange="handleSizeChangeLog"
      >
        <!-- 操作 -->
        <template slot="logaction" slot-scope="scope">
          <!-- <el-context-menu v-if="scope.scope.row.operationStatus == '完成'" :menus="menusLog" default="1":visibles="[scope.scope.row.operationStatus == '完成']"  @oper="clickRowLog" :scope="scope.scope"></el-context-menu> -->
          <span v-if="scope.scope.row.operationStatus == '完成'" class="executionResult" @click="clickRowLog(scope.scope)">执行结果</span>
          <span v-if="scope.scope.row.operationStatus == '失败'" class="filespan">{{ scope.scope.row.execuResult }}</span>
        </template>
      </c-Table>
      <span slot="footer" class="dialog-footer">
        <el-button style="border-radius: 3px" type="primary" @click="closeOperLog">关闭</el-button>
      </span>
    </manager-dialog>
    <!-- 结果查看 -->
    <manager-dialog :visible.sync="resultDialog" title="结果查看" @close="closeResultDialog">
      <!-- 渲染图表 -->
      <div>
        <div class="audit-header">{{ resultDetail.auditTaskName }}
          <el-button icon="el-icon-download" circle type="mini" @click="saveImage('Top3Img', resultDetail.auditTaskName)" /></div>
        <div id="Top3Img" ref="Top3Img">
          <template v-if="resultDetail.type == 'bar'">
            <bar-chart :height="resultHeight" :chart-bar-data="resultDetail.chartData" :show-legend="true" />
          </template>
          <template v-else-if="resultDetail.type == 'line'">
            <line-chart :height="resultHeight" :chart-data="resultDetail.chartData" :show-legend="true" />
          </template>
          <template v-else-if="resultDetail.type == 'pie'">
            <pie-chart :height="resultHeight" :chart-pie-data="resultDetail.chartData" :show-legend="true" />
          </template>
          <template v-else-if="resultDetail.type == 'mapScatter'">
            <!-- <map-Scatter-chart :height="resultHeight" :chart-scatter-data="resultDetail.chartData"></map-Scatter-chart> -->
            <map-area-chart :height="resultHeight" :chart-area-data="resultDetail.chartData" :show-legend="true" :is-zoom="true" />
          </template>
          <template v-else-if="resultDetail.type == 'table'">
            <!-- :page="pageQueryLog" 分页 @handleCurrentChange="handleCurrentChangeResult" @handleSizeChange="handleSizeChangeResult"-->
            <div style="padding:3px 6px;">
              <c-Table :column="resultDetail.columns" :height="resultHeight" :table-data="resultDetail.tableData" :page="pageResult" :hidden="true" />
            </div>
            <!-- </div> -->
          </template>
          <template v-else-if="resultDetail.type == 'radar'">
            <!-- <div :style="{width:item.width,height:item.height}"> -->
            <radar-chart :height="resultHeight" :chart-radar-data="resultDetail.chartData" :show-legend="true" />
          </template>
        </div>
        <!-- </el-card> -->
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeResultDialog">关闭</el-button>
      </span>
    </manager-dialog>
    <transition>
      <router-view />
    </transition>
  </div>
</template>
<script>
// eslint-disable-next-line no-unused-vars
import { checkRuleCodeExit } from '@ability/directive/rule-code'
import table from '@ability/mixins/table'
import staticsData from '@ability/mixins/staticsData'
import { batchDelTasks, viewRecentResult, getAuditTaskList, getOperRecord, viewTaskOperRecordResult, getLogTypeList } from '../api/analysis-audit-manage'
import cTable from '@ability/components/cTable'
import barChart from '@ability/components/Echarts/BarChart'
import lineChart from '@ability/components/Echarts/LineChart'
import pieChart from '@ability/components/Echarts/PieChart'
// import mapScatterChart from '@ability/components/Echarts/mapScatterChart'
import mapAreaChart from '@ability/components/Echarts/mapAreaChart'
import radarChart from '@ability/components/Echarts/radarChart'
import html2canvas from 'html2canvas'
export default {
  components: {
    cTable,
    barChart,
    lineChart,
    pieChart,
    // mapScatterChart,
    mapAreaChart,
    radarChart
  },
  mixins: [table, staticsData],
  data() {
    return {
      loading: false,
      // 查询参数
      qureyParam: {
        taskName: null, // 任务名称
        taskType: null, // 任务类型
        indexId: null, // 日志类型
        timeSeriesType: null, // 分析日志时序类型
        chartType: null, // 图表类型
        businessIds: []// 包含业务系统
      },
      // 查询条件
      queryItems: [
        {
          type: 'input',
          span: 12,
          key: 'taskName',
          label: '任务名称'
        },
        {
          type: 'select',
          span: 12,
          key: 'taskType',
          placeholder: '请选择任务类型',
          label: '任务类型',
          option: 'taskTypeList',
          optionLabel: 'dataName',
          optionValue: 'dataId'
        },
        {
          type: 'select',
          span: 12,
          key: 'indexId',
          placeholder: '请选择日志类型',
          label: '日志类型',
          option: 'logTypeList',
          optionLabel: 'indexName',
          optionValue: 'indexId'
        },
        {
          type: 'select',
          span: 12,
          key: 'chartType',
          placeholder: '请选择图表类型',
          label: '图表类型',
          option: 'chartTypeList',
          optionLabel: 'dataName',
          optionValue: 'dataId'
        },
        {
          type: 'select',
          span: 12,
          key: 'timeSeriesType',
          placeholder: '请选择分析日志时序类型',
          label: '分析日志时序类型',
          option: 'analyzeLogTimingList',
          optionLabel: 'dataName',
          optionValue: 'dataId'
        },
        {
          type: 'treeSelect',
          span: 12,
          key: 'businessIds',
          placeholder: '请选择归属业务系统',
          label: '归属业务系统',
          dataTree: 'businessTree'
        }
      ],
      // 列
      columnItems: [
        {
          type: 'selection',
          width: 50
        },
        {
          _key: 'taskName',
          prop: 'taskName',
          label: '任务名称',
          width: 160,
          showOverflowTooltip: true
        },
        {
          _key: 'taskType',
          prop: 'taskType',
          label: '任务类型',
          width: 80,
          render: true,
          showOverflowTooltip: true
        },
        {
          _key: 'taskRemark',
          prop: 'taskRemark',
          label: '任务说明',
          showOverflowTooltip: true
        },
        {
          _key: 'taskCycleName',
          prop: 'taskCycleName',
          label: '任务周期',
          showOverflowTooltip: true
        },
        {
          _key: 'startTimeStr',
          prop: 'startTimeStr',
          label: '任务开始时间',
          width: 140,
          showOverflowTooltip: true
        },
        {
          _key: 'execuTime',
          prop: 'execuTime',
          label: '任务执行时间',
          width: 140,
          showOverflowTooltip: true
        },
        {
          _key: 'taskStatusStr',
          prop: 'taskStatusStr',
          label: '任务状态',
          width: 80,
          showOverflowTooltip: true
        },
        {
          _key: 'execuNum',
          prop: 'execuNum',
          label: '执行次数',
          width: 80,
          showOverflowTooltip: true
        },
        {
          _key: 'indexIdName',
          prop: 'indexIdName',
          label: '日志类型',
          width: 100,
          showOverflowTooltip: true
        },
        {
          _key: 'timeSeriesTypeName',
          prop: 'timeSeriesTypeName',
          label: '时序类型',
          width: 80,
          showOverflowTooltip: true
        },
        {
          _key: 'timeSeriesName',
          prop: 'timeSeriesName',
          label: '日志时序',
          width: 140,
          showOverflowTooltip: true
        },
        {
          _key: 'chartType',
          prop: 'chartType',
          label: '图表类型',
          width: 110,
          render: true,
          showOverflowTooltip: true
        },
        {
          _key: 'action',
          prop: 'action',
          label: '操作',
          fixed: 'right',
          render: true,
          width: 150
        }
      ],
      tableData: [],
      menus: [
        {
          text: '查看',
          command: 'detail',
          icon: 'el-icon-s-order'
        },
        {
          text: '修改',
          command: 'modify',
          icon: 'el-icon-edit'
        },
        {
          text: '删除',
          command: 'del',
          icon: 'el-icon-delete',
          iconColor: 'red'
          // visible:true
        },
        {
          text: '执行结果',
          command: 'result',
          icon: 'el-icon-thumb'
          // visible:true
        },
        {
          text: '操作日志',
          command: 'operlog',
          icon: 'el-icon-chat-line-square'
        }
      ],
      logTypeListData: [], // 日志类型
      // 操作日志
      menusLog: [
        {
          text: '执行结果',
          command: 'executionresult',
          visible: true
        }
      ],
      LogDialog: false,
      // 操作日志分页
      pageQueryLog: {
        current: 1,
        size: 10,
        total: 0
      },
      pagerCount: 5,
      // 操作日志请求传参
      operLogParams: {
        logAuditaskLogMap: {
          taskId: null// 任务id
        },
        page: {
          current: 1,
          size: 10,
          total: 0
        }
      },
      // 操作日志
      operLogData: [],
      operLogColumns: [
        {
          label: '操作状态',
          prop: 'operationStatus'
        },
        {
          label: '执行时间',
          prop: 'execuTime'
        },
        {
          label: '操作人',
          prop: 'createUserName'
        },
        {
          label: '执行结果',
          render: true,
          _slotName: 'logaction',
          width: '150'
        }
      ],
      // 结果查看
      resultDialog: false,
      resultDetail: {
        auditTaskName: '', // 任务名称
        type: '', // 类型
        chartData: {}, // 图表
        columns: [], // 列表
        tableData: []
      },
      resultHeight: '300px',
      deleteData: {
        ids: []
      },
      pageResult: {
        current: 1,
        size: 10,
        total: 0
      }
    }
  },
  computed: {
    showAddBtn() {
      // auditAnalysis_del 删除权限
      // return checkRuleCodeExit('auditAnalysis_add')
      return true
    },
    staticData() {
      return {
        // 任务类型
        taskTypeList: [
          {
            dataId: '0',
            dataName: '实时任务'
          },
          {
            dataId: '1',
            dataName: '历史任务'
          },
          {
            dataId: '2',
            dataName: '周期任务'
          }
        ],
        // 分析日志时序类型
        analyzeLogTimingList: [
          {
            dataId: '0',
            dataName: '时间范围'
          },
          {
            dataId: '1',
            dataName: '单位时间'
          }
        ],
        // 图表类型
        chartTypeList: [
          {
            dataId: '0',
            dataName: '分组统计表'
          },
          {
            dataId: '1',
            dataName: '趋势图'
          },
          {
            dataId: '2',
            dataName: '饼图'
          },
          {
            dataId: '3',
            dataName: '柱状图'
          },
          {
            dataId: '4',
            dataName: '地图'
          },
          {
            dataId: '5',
            dataName: '雷达图'
          },
          {
            dataId: '6',
            dataName: '一览表'
          }
        ],
        // 任务周期
        taskCycleList: [
          {
            dataId: '0',
            dataName: '按日'
          },
          {
            dataId: '1',
            dataName: '按周'
          },
          {
            dataId: '2',
            dataName: '按月'
          }
        ],
        // 日志状态
        taskStatusList: [
          {
            dataId: '0',
            dataName: '实时'
          },
          {
            dataId: '1',
            dataName: '创建'
          },
          {
            dataId: '2',
            dataName: '执行中'
          },
          {
            dataId: '3',
            dataName: '完成'
          },
          {
            dataId: '4',
            dataName: '等待下一次执行'
          },
          {
            dataId: '5',
            dataName: '失败'
          }
        ],
        // 日志分析时序
        analysisLogTimingTypeList: [
          {
            dataId: '0',
            dataName: '时间范围'
          },
          {
            dataId: '1',
            dataName: '单位时间'
          }
        ],
        logTypeList: this.logTypeListData,
        businessTree: this.businessTree
      }
    }
  },
  beforeRouteUpdate(to, from, next) {
    if (from.name == 'auditAnalysisAddnew') {
      this.search()
    } else if (from.name == 'auditAnalysisResults') {
      const taskId = localStorage.getItem('taskId')
      if (taskId != null) {
        this.operLogParams.logAuditaskLogMap.taskId = taskId
        this.getOperLogData()
        this.operLogDialog = true
        localStorage.removeItem('taskId')
      }
    }
    next()
  },
  beforeRouteLeave(to, from, next) {
    // eslint-disable-next-line valid-typeof,no-empty
    if (typeof (localStorage.getItem('taskId')) == undefined || typeof (localStorage.getItem('taskId')) == null) {
    } else {
      localStorage.removeItem('taskId')
    }
    next()
  },
  created() {
    this.search()
    this.getlogTypeListData()
    this.getBusinessTree()
  },
  methods: {
    // 下面是methods中的内容
    // 图片转换格式的方法 直接使用就好  不需要知道为什么
    dataURLToBlob(dataurl) {
      const arr = dataurl.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    },
    /* 保存图片的方法（即按钮点击触发的方法）
      第一个参数为需要保存的div的id名
      第二个参数为保存图片的名称 */
    saveImage(divText, imgText) {
      const canvasID = this.$refs[divText]
      const that = this
      const a = document.createElement('a')
      html2canvas(canvasID).then(canvas => {
        const dom = document.body.appendChild(canvas)
        dom.style.display = 'none'
        a.style.display = 'none'
        document.body.removeChild(dom)
        const blob = that.dataURLToBlob(dom.toDataURL('image/png'))
        a.setAttribute('href', URL.createObjectURL(blob))
        // 这块是保存图片操作  可以设置保存的图片的信息
        a.setAttribute('download', imgText + '.png')
        document.body.appendChild(a)
        a.click()
        URL.revokeObjectURL(blob)
        document.body.removeChild(a)
      })
    },
    addPage() {
      this.$router.push(
        { name: 'auditAnalysisAddnew', params: { taskId: null, oper: 'add', type: 1 }}
      )
    },
    // 获取日志类型
    getlogTypeListData() {
      // 获取日志类型
      getLogTypeList().then(
        resp => {
          if (resp.data.returnCode == '0') {
            this.logTypeListData = resp.data.data
          }
        },
        error => {
          this.$message.error(error.message)
        }
      )
    },
    batchDeleteClick: function() {
      const ids = this.multipleSelection.map(item => {
        return item.taskId
      })
      if (ids.length == 0) {
        this.$message.warning('请选择删除的记录')
        return false
      }
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(ids)
      }).catch(() => {})
    },
    clickRow(command, scope) {
      const taskId = scope.row.taskId
      if (command == 'detail') { // 查看
        this.$router.push({ name: 'auditAnalysisAddnew', params: { taskId: taskId, oper: 'detail', type: 3 }}) //, params:{oper:'modify',id:index}
      } else if (command == 'modify') { // 修改
        this.$router.push({ name: 'auditAnalysisAddnew', params: { taskId: taskId, oper: 'modify', type: 2 }}) //, params:{oper:'modify',id:index}
      } else if (command == 'del') { // 删除
        const arr = []
        arr.push(scope.row.taskId)
        this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.handleDelete(arr)
        }).catch(() => { })
      } else if (command == 'result') { // 执行结果
        // this.getResultInfo(taskId)
        this.$router.push({ name: 'auditAnalysisResults', params: { taskId: taskId }})
      } else { // 操作日志
        this.operLogParams.logAuditaskLogMap.taskId = taskId
        this.getOperLogData()
      }
    },
    handleDelete(ids) {
      this.deleteData.ids = ids
      batchDelTasks(this.deleteData).then((resp) => {
        if (resp.data.returnCode == '0') {
          this.page.current = 1
          this.$message.success('删除成功')
          this.search()
        }
      })
    },
    reset() {
      Object.assign(this.$data, this.$options.data())
      this.getlogTypeListData()
      this.getBusinessTree()
      this.search()
    },
    searchClick() {
      this.search()
    },
    search() {
      this.loading = true
      getAuditTaskList(
        {
          logAuditaskMap: this.qureyParam,
          page: this.page
        }
      ).then((resp) => {
        if (resp.data.returnCode == '0') {
          this.tableData = resp.data.data.list
          const { current, size, total } = resp.data.data.page
          this.page.current = current
          this.page.size = size
          this.page.total = total
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 操作日志
    getOperLogData() {
      getOperRecord(this.operLogParams).then(resp => {
        if (resp.data.returnCode == '0') {
          this.operLogData = resp.data.data.list
          this.$set(this.pageQueryLog, 'size', resp.data.data.page.size)
          this.$set(this.pageQueryLog, 'current', resp.data.data.page.current)
          this.$set(this.pageQueryLog, 'total', resp.data.data.page.total)
          this.LogDialog = true
        }
      })
    },
    // 操作日志
    closeOperLog() {
      this.$set(this.pageQueryLog, 'current', 1)
      this.$set(this.pageQueryLog, 'size', 10)
      this.operLogParams.page.current = 1
      this.LogDialog = false
    },
    handleCurrentChangeLog(current) {
      this.operLogParams.page.current = current
      this.getOperLogData()
    },
    handleSizeChangeLog(size) {
      this.operLogParams.page.size = size
      this.getOperLogData()
    },
    // 结果查看
    getResultInfo(taskId) {
      this.loading = true
      this.loaingText = '数据请求中，请稍候'
      viewRecentResult(taskId).then(resp => {
        if (resp.data.returnCode == '0') {
          this.loading = false
          this.resultDialog = true
          this.resultDetail.auditTaskName = resp.data.data.auditTaskName
          this.resultDetail.type = resp.data.data.type
          this.$set(this.resultDetail, 'chartData', resp.data.data.chartData)
          this.$set(this.resultDetail, 'columns', resp.data.data.columns)
          this.$set(this.resultDetail, 'tableData', resp.data.data.tableData)
        } else {
          this.loading = false
          // this.$message.error(resp.data.returnMsg)
        }
      }, error => {
        this.loading = false
        this.$message.error(error.returnMsg)
      })
    },
    // 操作日志--查看任务执行结果
    clickRowLog(scope) {
      console.log(scope.row)
      const recordId = scope.row.recordId
      const operationStatus = scope.row.operationStatus
      if (operationStatus == '完成') {
        this.viewExecutionResult(recordId)
        // console.log(1234)
        // this.$router.push({name:'auditAnalysisResults',params: { recordId: recordId}})
        // localStorage.setItem('taskId',this.operLogParams.logAuditaskLogMap.taskId)
        // this.operLogDialog = false
      }
    },
    // 查看任务执行结果
    viewExecutionResult(recordId) {
      viewTaskOperRecordResult(recordId).then(resp => {
        if (resp.data.returnCode == '0') {
          this.resultDialog = true
          this.resultDetail.auditTaskName = resp.data.data.auditTaskName
          this.resultDetail.type = resp.data.data.type
          this.$set(this.resultDetail, 'chartData', resp.data.data.chartData)
          this.$set(this.resultDetail, 'columns', resp.data.data.columns)
          this.$set(this.resultDetail, 'tableData', resp.data.data.tableData)
        } else {
          // this.$message.error(resp.data.returnMsg)
        }
        // eslint-disable-next-line handle-callback-err
      }, error => {
        // this.$message.error(error.returnMsg)
      })
    },
    closeResultDialog() {
      this.resultDialog = false
    }
  }
}
</script>
<style lang="scss" scoped>
.executionResult{
  color:#4C8AE8;
  font-size:12px;
  cursor:pointer;
}
.filespan{
  color:#E42F3B;
  font-size:12px;
}
.audit-header{
  color: transparent;
  background-color: black;
  border-left:4px solid #0096E4 ;
  text-shadow: rgba(255,255,255,0.5) 0 5px 6px, rgba(255,255,255,0.2) 1px 3px 3px;
  -webkit-background-clip: text;
  padding:6px;
}
</style>
