<template>
  <div class="white pa-3">
    <m-filter :option="filter" @search="handleSearch" />
    <div class="d-flex my-3">
      <v-card
        v-for="(item, index) in items"
        :key="item.title"
        :class="`${index === items.length - 1 ? '' : 'mr-3'} auto pointer`"
        :elevation="5"
        @click="handleClick(item)"
      >
        <v-chip
          class="ma-2"
          :color="item.color"
          label
        >
          <v-icon left>
            {{ item.icon }}
          </v-icon>
          {{ item.title }}
        </v-chip>
        <v-card-text :class="`text-center ${item.color}--text text-h4`">
          <div v-loading="loading">{{ item.value }}</div>
        </v-card-text>
        <v-card-actions></v-card-actions>
      </v-card>
    </div>
    <div class="d-flex">
      <m-card
        v-for="item in list"
        :key="item.title"
        :title="item.title"
        :class="item.class"
      >
        <low-code v-loading="loading" :option="item.option" height="350"></low-code>
      </m-card>
    </div>
    <m-dialog :visible.sync="dialogVisible" :title="dialogTitle" :footer="false">
      <m-table
        :headers="headers"
        :items="table.items"
        :loading="table.loading"
        :disable-sort="true"
        :page-info="table.pageInfo"
        :total="table.total"
        :elevation="0"
        :show-select="false"
        :is-tools="false"
      >
        <template #actions="{ item }">
          <template v-if="clickKey === 'unscheduledCount'">
            <v-btn text color="primary">启用调度</v-btn>
          </template>
          <template v-else>
            <v-btn
              text
              color="primary"
              @click="handleClickTableItem(item)"
            >
              {{ btnTitle }}
            </v-btn>
          </template>
        </template>
      </m-table>
      <!-- <m-log v-model="log.drawer" :data="log.data"></m-log> -->
      <v-navigation-drawer
        v-model="log.drawer"
        fixed
        temporary
        right
        width='700'
        style="z-index: var(--zIndex-dialog);"
      >
        <div v-loading="log.loading" style="min-height: 500px;">
          <div class="pa-3 font-weight-bold white" style="font-size: 18px; position: sticky; top: 0">
            {{ log.title }}
          </div>
          <div v-for="(log, index) in log.data" :key="index" class="pa-3">
            {{ log }}
          </div>
        </div>
      </v-navigation-drawer>
    </m-dialog>
  </div>
</template>

<script>
import MFilter from '@/components/Filter'
import LowCode from '@/charts/lowCode'
import MCard from '@/components/MCard'
import MDialog from '@/components/Dialog'
import MTable from '@/components/List/table'
// import MLog from '../components/logPage'
import {
  productionLineMonitor,
  // productionLineBasePage,
  // productionLineLogPage,
  // productionLineLogDetail,
  // productionLineLog,
  getProductionLineTasksLogs,
  // getProductionLineList,
  getProductionLineTasks,
  getProductionLineUnscheduled
} from '@/api/dataFactory'
import {
  dateFormat
} from '@/utils/date'
export default {
  name: 'production-line-monitor',
  components: { MFilter, LowCode, MCard, MDialog, MTable },
  data () {
    return {
      dialogVisible: false,
      dialogTitle: '',
      table: {
        items: [],
        pageInfo: {
          size: 10,
          current: 1
        },
        total: 0,
        loading: false
      },
      log: {
        drawer: false,
        loading: false,
        title: null,
        data: []
      },
      list: [
        {
          title: '调度报表',
          key: 'line',
          option: {
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'cross',
                label: {
                  backgroundColor: '#6a7985'
                }
              }
            },
            grid: {
              left: '20',
              right: '20',
              bottom: '20',
              containLabel: true
            },
            xAxis: [
              {
                type: 'category',
                boundaryGap: false,
                data: []
              }
            ],
            yAxis: [
              {
                type: 'value'
              }
            ],
            series: []
          },
          class: 'mr-3 left',
          query: null,
          items: [
            { text: '每天', value: '0' },
            { text: '每月', value: '1' },
            { text: '每年', value: '2' }
          ]
        },
        {
          title: '执行成功失败对比',
          key: 'pie',
          option: {
            tooltip: {
              trigger: 'item'
            },
            series: [
              {
                name: '执行成功失败对比',
                type: 'pie',
                radius: '75%',
                label: {
                  formatter: '{b} {c}次 ( {d}% )'
                },
                data: []
              }
            ]
          },
          class: 'auto',
          query: null,
          items: [
            { text: '每天', value: '0' },
            { text: '每月', value: '1' },
            { text: '每年', value: '2' }
          ]
        }
      ],
      filter: {
        list: [
          {
            type: 'datePicker',
            key: 'exec_date',
            value: dateFormat('YYYY-mm-dd', new Date()),
            dateType: 'date',
            placeholder: '请选择要查看的日期',
            clearable: true
          }
        ]
      },
      loading: false,
      query: {
        exec_date: dateFormat('YYYY-mm-dd', new Date())
      },
      dictList: {
        success: 0,
        running: 0,
        stopped: 0,
        failed: 0,
        scheduledCount: 0,
        total: 0,
        unscheduledCount: 0
      },
      clickItem: {},
      clickKey: null,
      taskStatus: []
    }
  },
  computed: {
    headers () {
      if (this.clickKey === 'unscheduledCount') {
        return [
          { text: '名称', value: 'name' },
          { text: '调度频率', value: 'schedule_frequency' },
          { text: '操作', value: 'actions' }
        ]
      }
      return [
        { text: '名称', value: 'target_table' },
        { text: '状态', value: 'raw_state' },
        { text: '操作', value: 'actions' }
      ]
    },
    btnTitle () {
      return `查看${this.clickItem.isLine ? '最新' : ''}日志`
    },
    items () {
      return [
        // {
        //   title: '生产线数量',
        //   key: 'total',
        //   api: getProductionLineList,
        //   isLine: true,
        //   value: this.dictList.total,
        //   icon: 'mdi-chart-timeline-variant',
        //   color: 'primary'
        // },

        {
          title: '调度执行总数量',
          key: 'total',
          api: getProductionLineTasks,
          value: this.dictList.total,
          icon: 'mdi-timer-play-outline',
          color: 'primary'
        },
        {
          title: '正常执行数量',
          key: 'success',
          api: getProductionLineTasks,
          isLine: true,
          value: this.dictList.success,
          icon: 'mdi-timer-check-outline',
          color: 'success'
        },
        {
          title: '正在执行数量',
          key: 'running',
          api: getProductionLineTasks,
          isLine: true,
          value: this.dictList.running,
          icon: 'mdi-timer-sync-outline',
          color: 'info'
        },
        {
          title: '停止执行数量',
          key: 'stopped',
          api: getProductionLineTasks,
          isLine: true,
          value: this.dictList.stopped,
          icon: 'mdi-timer-cancel-outline',
          color: 'warning'
        },
        {
          title: '异常执行数量',
          key: 'failed',
          api: getProductionLineTasks,
          isLine: true,
          value: this.dictList.failed,
          icon: 'mdi-timer-alert-outline',
          color: 'error'
        },
        {
          title: '未调度执行数量',
          key: 'unscheduledCount',
          api: getProductionLineUnscheduled,
          value: this.dictList.unscheduledCount,
          icon: 'mdi-timer-pause-outline',
          color: 'default'
        }
      ]
    }
  },
  created () {
    this.init()
  },
  methods: {
    async init () {
      this.loading = true
      try {
        const { data } = await productionLineMonitor(this.query)
        const item = data.find(e => e.dag_id === 'dataops_productline_execute_dag')
        if (!item.runs.length) {
          return
        }
        item.runs = item.runs.sort((a, b) => new Date(a.local_exec_time).getTime() - new Date(b.local_exec_time).getTime())
        const _arr = item.runs[0]
        this.clickItem = item
        this.dictList = {
          success: _arr.tasks.success,
          running: _arr.tasks.running,
          stopped: _arr.tasks.stopped,
          failed: _arr.tasks.failed,
          // scheduledCount: _arr.tasks.scheduled_total,
          total: _arr.tasks.scheduled_total,
          // total: _arr.total,
          unscheduledCount: _arr.unscheduled_total
        }
        // this.items.forEach(_ele => {
        //   _ele.value = data[_ele.key] || 0
        // })
        // this.list.forEach(_e => {
        //   if (_e.key === 'line') {
        //     if (!data.lineChartMap) {
        //       _e.option.xAxis[0].data = []
        //       _e.option.series = []
        //       return
        //     }
        //     _e.option.xAxis[0].data = data.lineChartMap.title
        //     _e.option.series = data.lineChartMap.series.map(_ele => {
        //       return {
        //         name: _ele.name,
        //         type: 'line',
        //         stack: 'Total',
        //         symbolSize: 12,
        //         areaStyle: {},
        //         label: {
        //           show: true,
        //           position: 'top'
        //         },
        //         emphasis: {
        //           focus: 'series'
        //         },
        //         data: _ele.data
        //       }
        //     })
        //     return
        //   }
        //   const item = _e.option.series.find(_v => _v.name === '执行成功失败对比')
        //   if (!data.ratioMap) {
        //     item.data = []
        //     return
        //   }
        //   item.data = Object.keys(data.ratioMap).map(name => {
        //     return {
        //       value: data.ratioMap[name],
        //       name
        //     }
        //   })
        // })
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.loading = false
      }
    },
    async handleClick (item) {
      this.dialogVisible = true
      this.dialogTitle = item.title
      this.clickKey = item.key
      this.table.total = 0
      this.table.pageInfo.current = 1
      this.table.items = []
      // if (item.value === 0) {
      //   return
      // }
      if (item.key === 'unscheduledCount') {
        this.drillUnscheduled(item)
        return
      }
      this.table.loading = true
      try {
        const { data } = await item.api({
          dag_id: this.clickItem.dag_id,
          run_id: this.clickItem.runs[0].run_id,
          state: item.key
        })
        this.table.total = data.tasks.length
        this.table.items = data.tasks
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.table.loading = false
      }
    },
    async drillUnscheduled (item) {
      this.table.loading = true
      try {
        const { data } = await item.api()
        this.table.total = data.length
        this.table.items = data.map(e => {
          return {
            ...e,
            ...e.target_table
          }
        })
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.table.loading = false
      }
    },
    handleSearch (val) {
      if (!val.times) {
        this.query.times = []
        this.init()
        return
      }
      Object.assign(this.query, {
        times: val.times.map(_e => _e + ' 00:00:00')
      })
      this.init()
    },
    async handleClickTableItem (item) {
      this.log.title = item.target_table
      this.log.data = []
      setTimeout(() => {
        this.log.drawer = true
        this.log.loading = true
      })
      try {
        const { data } = await getProductionLineTasksLogs({
          dag_id: this.clickItem.dag_id,
          run_id: this.clickItem.runs[0].run_id,
          task_id: item.task_id,
          try_number: item.try_number
        })

        this.log.data = data.log.replace(/\\n/g, '\n').split('\n')
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.log.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.left {
  width: 60%;
}
.auto {
  flex: 1;
}
.pointer {
  cursor: pointer;
  user-select: none;
}
.default {
  font-weight: 400;
}
</style>
