<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"
      >
        <!-- <template #title>
          <v-select
            v-model="item.query"
            label="时间"
            placeholder="请选择时间"
            class="input-width-m default"
            :items="item.items"
            :menu-props="{ offsetY: true }"
            hide-details outlined dense attach clearable
          ></v-select>
        </template> -->
        <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="table.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"
        @pageHandleChange="handlePageChange"
      >
        <template #actions="{ item }">
          <!-- <template v-if="clickItem.key === 'total'">
            <v-btn text color="primary">查看生产线</v-btn>
          </template> -->
          <template v-if="clickItem.key === '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>
    </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
} from '@/api/dataFactory'
export default {
  name: 'production-line-monitor',
  components: { MFilter, LowCode, MCard, MDialog, MTable, MLog },
  data () {
    return {
      dialogVisible: false,
      dialogTitle: '',
      table: {
        headers: [
          { text: '名称', value: 'name' },
          { text: '操作', value: 'actions' }
        ],
        items: [],
        pageInfo: {
          size: 10,
          current: 1
        },
        total: 0,
        loading: false
      },
      log: {
        drawer: false,
        data: null
      },
      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: 'times',
            value: [],
            range: true,
            dateType: 'day',
            placeholder: '请选择要查看的日期',
            clearable: true
          }
        ]
      },
      loading: false,
      query: {
        times: []
      },
      dictList: {
        normalCount: '1',
        executingCount: '2',
        stopCount: '3',
        exceptionCount: '4',
        total: null,
        unscheduledCount: null
      },
      items: [
        {
          title: '生产线数量',
          key: 'total',
          api: productionLineLog,
          isLine: true,
          value: 0,
          icon: 'mdi-chart-timeline-variant',
          color: 'primary'
        },
        {
          title: '正常执行数量',
          key: 'normalCount',
          api: productionLineLog,
          isLine: true,
          value: 0,
          icon: 'mdi-timer-check-outline',
          color: 'success'
        },
        {
          title: '正在执行数量',
          key: 'executingCount',
          api: productionLineLog,
          isLine: true,
          value: 0,
          icon: 'mdi-timer-sync-outline',
          color: 'info'
        },
        {
          title: '停止执行数量',
          key: 'stopCount',
          api: productionLineLog,
          isLine: true,
          value: 0,
          icon: 'mdi-timer-cancel-outline',
          color: 'warning'
        },
        {
          title: '异常执行数量',
          key: 'exceptionCount',
          api: productionLineLog,
          isLine: true,
          value: 0,
          icon: 'mdi-timer-alert-outline',
          color: 'error'
        },
        {
          title: '调度执行总数量',
          key: 'dispatchCount',
          api: productionLineLogDetail,
          value: 0,
          icon: 'mdi-timer-play-outline',
          color: 'primary'
        },
        {
          title: '未调度执行数量',
          key: 'unscheduledCount',
          value: 0,
          icon: 'mdi-timer-pause-outline',
          color: 'default'
        }
      ],
      clickItem: {},
      taskStatus: []
    }
  },
  computed: {
    btnTitle () {
      return `查看${this.clickItem.isLine ? '最新' : ''}日志`
    }
  },
  created () {
    this.init()
  },
  methods: {
    async init () {
      this.loading = true
      try {
        const { data } = await productionLineMonitor(this.query)
        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.table.total = 0
      this.table.pageInfo.current = 1
      this.table.items = []
      this.clickItem = item
      this.initTable()
    },
    async initTable () {
      this.table.loading = true
      try {
        const query = {
          times: this.query.times,
          ...this.table.pageInfo
        }
        if (Object.keys(this.dictList).includes(this.clickItem.key)) {
          Object.assign(query, {
            type: this.dictList[this.clickItem.key]
          })
        }
        // if (this.clickItem.key === 'dispatchCount') {
        //   Object.assign(query, {
        //     runStatus: '1'
        //   })
        // }
        if (this.clickItem.key === 'unscheduledCount') {
          Object.assign(query, {
            status: '0'
          })
          delete query.times
        }
        const subApi = Object.keys(this.dictList).includes(this.clickItem.key) ? productionLineBasePage : productionLineLogPage
        const { data } = await subApi(query)
        this.table.total = data.total
        this.table.items = data.records
      } 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()
    },
    handlePageChange (index) {
      this.table.pageInfo.current = index
      this.initTable()
    },
    async handleClickTableItem (item) {
      if (Object.keys(this.dictList).includes(this.clickItem.key)) {
        // 跳转生产线明细
      }
      // console.log(item)
      if (!this.clickItem.api) {
        return
      }
      try {
        const { data } = await this.clickItem.api({ id: item.id })
        this.log.data = data
        setTimeout(() => {
          this.log.drawer = true
        })
      } catch (error) {
        this.$snackbar.error(error)
      }
    }
  }
}
</script>

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