<template>
  <a-spin
    :id="containerId"
    ref="container"
    :spinning="spin.isLoading"
    :tip="spin.tip"
    style="width: 100%; height: 100%"
    wrapperClassName="fitHeight"
  >
    <a-alert type="success">
      <template slot="description">
        <a-row>
          <a-col :span="sizeInfo.topAlert.col1.span">
            <a-icon type="" /> 刷新次数: &nbsp;
            <a-tag color="blue"> {{ totalQuery }} </a-tag>
            <a-tag color="orange" v-if="showCountdown">
              <count-down style="font-size: 14px" :target="new Date().getTime() + config.refreshProps.interval" />
            </a-tag>
          </a-col>
          <a-col :span="sizeInfo.topAlert.col2.span" :style="{ marginTop: sizeInfo.topAlert.col2.marginTop + 'px' }">
            <a-icon type="" /> 报警合计: &nbsp;
            <a-tag color="red"> {{ totalWarn }} </a-tag>
          </a-col>
          <a-col :span="sizeInfo.topAlert.col3.span" :style="{ marginTop: sizeInfo.topAlert.col3.marginTop + 'px' }">
            <a-icon type="" /> 最后刷新: &nbsp;
            <a-tag color="orange">
              {{ lastQuery }}
            </a-tag>
          </a-col>
        </a-row>
      </template>
    </a-alert>
    <a-row :style="{ height: sizeInfo.midOutRow.height }">
      <a-col :span="sizeInfo.midChart1.span" :style="{ height: sizeInfo.midChart1.height }">
        <div :id="chartMain.id" class="chart"></div>
      </a-col>
      <a-col :span="sizeInfo.midChart2.span" :style="{ height: sizeInfo.midChart2.height }">
        <div :id="chartSub.id" class="chart"></div>
      </a-col>
    </a-row>
    <a-row v-show="sizeInfo.bottomTxt.visible">
      <a-col :span="24"></a-col>
    </a-row>
  </a-spin>
</template>

<script>
import * as echarts from 'echarts'
import elementResizeDetector from 'element-resize-detector'
import _ from 'lodash'
import moment from 'moment'
import { aggregate } from 'echarts-simple-transform'
import warnApi from '@/api/warnApi'
import CountDown from '@/components/CountDown/CountDown'
import defaultOption from './funcs/warnRealChartOption'

const breakPoints = { xxl: 1600, xl: 1200, lg: 992, md: 768, sm: 458, xs: -1 }
const sizeInfoBreaks = {
  topAlert: {
    col1: {
      span: { md: 8, sm: 12, xs: 24 },
      marginTop: { sm: 0, xs: 0 }
    },
    col2: {
      span: { md: 8, sm: 12, xs: 24 },
      marginTop: { sm: 0, xs: 8 }
    },
    col3: {
      span: { md: 8, sm: 24, xs: 24 },
      marginTop: { md: 0, sm: 8, xs: 8 }
    }
  },
  midOutRow: {
    height: { md: 'calc(100% - 58px)', sm: 'calc(100% - 58px)', xs: 'auto' }
  },
  midChart1: {
    span: { md: 8, sm: 12, xs: 24 },
    height: { md: '100%', sm: '100%', xs: '200px' }
  },
  midChart2: {
    span: { md: 16, sm: 12, xs: 24 },
    height: { md: '100%', sm: '100%', xs: '200px' }
  },
  bottomTxt: {
    visible: { md: true, xs: false }
  }
}
const sizeProp = [];
(function pickSizeProp (obj, parent) {
  const keys = Object.keys(breakPoints)
  function isSizeProperty (src, name) {
    return _.isObject(src) && _.keys(src).some(p2 => {
      return keys.indexOf(p2) >= 0
    })
  }

  _.forOwn(obj, (v, k) => {
    const link = `${parent}${parent === '' ? '' : '.'}${k}`
    if (_.isObject(v) && isSizeProperty(v)) {
      sizeProp.push(link)
    } else if (_.isObject(v) || _.isArray(v)) {
      pickSizeProp(v, link)
    }
  })
})(sizeInfoBreaks, '')

export default {
  name: 'WarnReal',
  components: {
    CountDown
  },
  props: {
    widgetItemData: {
      type: Object,
      default: () => { }
    }
  },
  data () {
    return {
      moment,
      showCountdown: false,
      spin: {
        isLoading: false,
        tip: ''
      },
      minSize: { width: 330, height: 260 },

      warnList: Object.freeze([]),
      containerId: 'warnRealContainer' + moment().unix(),
      chartMain: { id: 'warnRealChart' + moment().unix(), chart: {} },
      chartSub: {
        id: 'warnRealChartSub' + moment().unix(), chart: {}, sourceKey: undefined,
        chartType: 'hBar' // vBar,  hBar, pie
      },

      configVisible: false,
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
      config: {
        coorX: 0,
        coorY: 0,
        refreshProps: {
          canRefresh: true,
          interval: 30 * 1000,
          lastRecord: undefined,
          mid: -1,
          stopLog: []
        }
      },

      sizeInfo: {
        topAlert: {
          col1: {
            span: 12,
            marginTop: 0
          },
          col2: {
            span: 12,
            marginTop: 0
          },
          col3: {
            span: 24,
            marginTop: 8
          }
        },
        midOutRow: {
          height: 'auto'
        },
        midChart1: {
          span: 24,
          height: '200px'
        },
        midChart2: {
          span: 24,
          height: '200px'
        },
        bottomTxt: {
          visible: false
        }
      },

      totalWarn: 0,
      totalQuery: 0,
      lastQuery: ''
    }
  },
  methods: {
    executeFromParent (which, paras) {
      switch (which) {
        case 'SHOWCONFIG':
          this.configVisible = true
          break
        default:
          break
      }
    },
    handleOk () {
      this.configVisible = false
      this.$emit('configChanged')
    },
    handleCancel () {
      this.configVisible = false
    },

    chartInit () {
      this.chartMain.chart.setOption(defaultOption.chartMainDefault(this.chartMain.id))

      this.chartSub.chart.setOption(defaultOption.chartSubDefault(this.chartSub, this.warnList))
    },
    pickLastZjyTime () {
      if (this.widgetItemData.wellRecord.zjy === 1) {
        if (this.warnList.length === 0) {
          return null
        }
        let last = ''
        this.warnList.map(p => {
          if (p.warnTime > last) {
            last = p.warnTime
          }
        })
        return last
      }
      return null
    },
    queryWarn () {
      if (this._isDestroyed) return
      this.showCountdown = false
      this.lastQuery = moment().format("YYYY-MM-DD HH:mm:ss")
      this.totalQuery++
      const well = this.widgetItemData.wellRecord
      const queryBody = {
        jh: well.JH,
        checkZjy: well.zjy === 1,
        checkFzqk: well.ltd === 1 && this.config.coorX !== 0 && this.config.coorY !== 0,
        checkGc: well.ltd === 1,
        zjyLastTime: this.pickLastZjyTime(),
        coorX: this.config.coorX,
        coorY: this.config.coorY
      }
      warnApi.queryFocusWarn(queryBody)
        .then(res => {
          const zjy = _.get(res.result, 'zjy', null)
          const fzqk = _.get(res.result, 'fzqk', null)
          const gc = _.get(res.result, 'gc', null)
          const newData = []
          const that = this
          function tranWarn (list) {
            list.map(p => {
              newData.push({
                key: p.key,
                jh: p.jh,
                canceled: false,
                queryTime: p.requestStart,
                warnTime: p.warnTime,
                source: p.source,
                catogary: p.catogary,
                warnMsg: p.bjnr
              })
            })
            that.totalWarn += list.length
          }
          zjy && tranWarn(zjy)
          fzqk && tranWarn(fzqk)
          gc && tranWarn(gc)

          this.warnList = this.warnList.concat(newData)
          this.chartMain.chart.setOption({
            dataset: {
              id: 'raw',
              source: this.warnList
            }
          })
          if (!this.chartSub.sourceKey && this.warnList.length > 0) {
            this.debounceSubChartFllow(this.warnList[0].source)
          } else {
            this.debounceSubChartFllow(this.chartSub.sourceKey)
          }
          this.showCountdown = true

          _.delay(this.queryWarn, this.config.refreshProps.interval)
        }).catch(e => {
          if (!this._isDestroyed) {
            this.$message.info(e.message)
            this.showCountdown = true
            _.delay(this.queryWarn, this.config.refreshProps.interval)
          }
        })
    },
    stopRefresh () {
      // TODO: dropped
    },
    subChartFllow (srcName) {
      this.chartSub.sourceKey = srcName
      this.chartSub.chart.setOption({
        title: {
          text: srcName,
          left: 'center',
          top: 8
        },
        dataset: [{
          id: 'raw',
          source: this.warnList
        }, {
          id: 'right',
          transform: [
            {
              type: 'filter',
              config: {
                dimension: 'source',
                '=': srcName
              }
            },
            {
              type: 'ecSimpleTransform:aggregate',
              config: {
                resultDimensions: [
                  { from: 'catogary' },
                  { name: 'c1', from: 'source', method: 'count' }
                ],
                groupBy: 'catogary'
              }
            },
            {
              type: 'sort',
              config: {
                dimension: 'c1',
                order: 'desc'
              }
            }
          ]
        }]
      })
    },
    checkWarnType () {
      warnApi.queryWellCoordinate({ jh: this.widgetItemData.wellRecord.JH })
        .then(res => {
          if (res.result.exist) {
            this.config.coorX = res.result.coor[0]
            this.config.coorY = res.result.coor[1]
          }
          this.queryWarn()
        }).catch(e => {
          this.$message.info(e.message)
        })
    }
  },
  created () {
    echarts.registerTransform(aggregate)
    this.debounceResize = _.debounce((rec) => {
      const { chartMain, chartSub } = this
      chartMain.chart.resize()
      chartSub.chart.resize()
    }, 200)

    this.debounceSubChartFllow = _.debounce((srcName) => {
      this.subChartFllow(srcName)
    }, 200)

    this.debounceMediaQuery = _.debounce((width, height) => {
      const keys = Object.keys(breakPoints)
      // media query logic
      let fitIndex = -1
      for (var p in breakPoints) {
        fitIndex++
        if (width >= breakPoints[p]) {
          break
        }
      }
      _.forEach(sizeProp, p1 => {
        const vals = _.get(sizeInfoBreaks, p1, undefined)
        for (var k = fitIndex; k < keys.length; k++) {
          const sizeKey = keys[k]
          if (vals && _.has(vals, sizeKey)) {
            _.set(this.sizeInfo, p1, vals[sizeKey])
            break
          }
        }
      })
      // ------------- end -------------------------------
      defaultOption.mediaChangedOption(fitIndex, this.chartMain, this.chartSub)
    }, 200)
  },
  mounted () {
    this.chartMain.chart = echarts.init(document.getElementById(this.chartMain.id), 'shine')
    this.chartSub.chart = echarts.init(document.getElementById(this.chartSub.id), 'shine')
    const that = this
    this.chartMain.chart.on('mouseover', function (event) {
      const name = event.name
      that.chartSub.sourceKey = name
      that.debounceSubChartFllow(name)
    })

    this.$nextTick(function () {
      this.chartSub['container'] = this.$refs.container.$el
      this.chartInit()
      this.checkWarnType()
    })

    const erd = elementResizeDetector()
    erd.listenTo(this.$refs.container.$el, function (el) {
      that.$nextTick(function () {
        var h = el.offsetHeight - 50
        var w = el.offsetWidth - 42
        h = _.max([that.minSize.height, h])
        w = _.max([that.minSize.width, w])
        that.debounceResize({ w, h })
        that.debounceMediaQuery(el.offsetWidth)
      })
    })
  },
  computed: {},
  watch: {}
}
</script>

<style lang="less" scoped>
.chart {
  min-height: 150px;
  width: 100%;
  height: 100%;
}
.fitHeight {
  /deep/ .ant-spin-container {
    height: 100%;
  }
}
/deep/ .ant-descriptions-title {
  margin-bottom: 0px;
}
/deep/ .ant-input:disabled {
  color: rgba(0, 0, 0, 0.85);
}
</style>
