<template>
  <a-spin
    :id="containerId"
    ref="container"
    :spinning="spin.isLoading"
    :tip="spin.tip"
    style="width: 100%; height: 100%"
    wrapperClassName="fitHeight"
  >
    <a-form-model v-if="false">
      <a-row>
        <a-col span="8">
          <a-form-model-item
            label="井号"
            :labelCol="{ span: 8 }"
            :wrapperCol="{ span: 16 }"
            :style="{ color: 'white' }"
          >
            <a-select v-model="selectedJh" default-value="lucy" @change="handleJhChange">
              <a-select-option value="jack"> Jack </a-select-option>
              <a-select-option value="lucy"> Lucy </a-select-option>
              <a-select-option value="disabled" disabled> Disabled </a-select-option>
              <a-select-option value="Yiminghe"> yiminghe </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col span="16" v-show="false">
          <a-form-model-item label="模式" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
            <a-radio-group v-model="mode">
              <a-radio-button value="many"> 多天 </a-radio-button>
              <a-radio-button value="single"> 单天 </a-radio-button>
            </a-radio-group>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>

    <a-row v-show="!selectedJh" style="height: 100%; min-height: 200px">
      <a-col span="24">
        <a-empty description="请选择井号"> </a-empty>
      </a-col>
    </a-row>
    <a-row v-show="selectedJh !== undefined" :style="{ height: sizeInfo.midOutRow.height }">
      <a-col span="24" style="height: 100%">
        <component
          ref="chartComponent"
          @dataReady="handleDataReayChange"
          :jh="jhRecord.JH"
          :jhRecord="widgetItemData"
          :key="disCacheKey"
          :is="chartComponent"
        />
      </a-col>
    </a-row>
    <a-modal
      title="报警实时统计-配置项"
      :width="970"
      :visible="configVisible"
      @cancel="handleCancel"
      @ok="handleOk"
      :maskClosable="false"
      destroyOnClose
    >
      <a-form-model :model="config" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="井号">
          <a-input v-model="config.jh" disabled />
        </a-form-model-item>

        <a-form-model-item>
          <span slot="label">
            最新数据时间&nbsp;
            <a-tooltip title="存储的源数据最新时间值（实时刷新的）">
              <a-icon style="color: rgb(82, 196, 26)" type="question-circle" />
            </a-tooltip>
          </span>
          <a-date-picker
            disabled
            format="YYYY-MM-DD HH:mm:ss"
            v-model="config.lastTime"
            :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
          />
        </a-form-model-item>
        <a-form-model-item label="日期">
          <a-date-picker v-model="config.queryDate" style="width: 195px" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </a-spin>
</template>

<script>
import elementResizeDetector from 'element-resize-detector'
import _ from 'lodash'
import moment from 'moment'
import warnApi from '@/api/warnApi'
import { mapState } from 'vuex'

const breakPoints = { xxl: 1600, xl: 1200, lg: 992, md: 768, sm: 458, xs: -1 }
const sizeInfoBreaks = {
  midOutRow: {
    height: { md: 'calc(100% - 8px)', sm: 'calc(100% - 8px)', xs: 'calc(100% - 8px)' }
  },
  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' }
  }
}
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: 'WarnHistory',
  props: {
    widgetItemData: {
      type: Object,
      default: () => { }
    }
  },
  data () {
    return {
      disCacheKey: 0,
      moment,
      spin: {
        isLoading: false,
        tip: ''
      },
      minSize: { width: 330, height: 260 },

      selectedJh: '123',
      mode: 'many',

      chartLevel: 'Xs',
      containerId: 'warnHistoryContainer' + moment().unix(),
      config: {
        jh: '井号123',
        lastTime: moment(),
        queryDate: moment()
      },
      sizeInfo: {
        midOutRow: {
          height: 'auto'
        },
        midChart1: {
          span: 24,
          height: '200px'
        },
        midChart2: {
          span: 24,
          height: '200px'
        }
      },

      dataReady: false
    }
  },
  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
    },
    pushData () {

    },
    handleJhChange () {
      warnApi.startWarnHistoryTask({ jh: '', ltd: '1' })
        .then(res => {

        }).catch(e => {
          this.$message.info(e.message)
        })
    },
    handleDataReayChange () {
      this.dataReady = true
      const that = this
      setTimeout(function () {
        that.$nextTick(() => {
          that.debounceMediaQuery(that.$refs.container.$el.offsetWidth - 42)
          if (that.$refs.chartComponent.debounceResize) {
            that.$refs.chartComponent.debounceResize()
          }
        })
      }, 1200)
    }
  },
  created () {
    this.debounceResize = _.debounce((rec) => {
    }, 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 -------------------------------
      const that = this
      this.$nextTick(function () {
        if (!that.dataReady) {
          return
        }
        const lgIndex = keys.indexOf('lg')
        const mdIndex = keys.indexOf('md')
        if (fitIndex <= lgIndex && this.chartLevel.toLowerCase() !== 'lg') {
          that.disCacheKey++
          that.chartLevel = 'Lg'
        } else if (fitIndex > lgIndex && fitIndex <= mdIndex && this.chartLevel.toLowerCase() !== 'md') {
          that.disCacheKey++
          that.chartLevel = 'Md'
        } else if (fitIndex > mdIndex && this.chartLevel.toLowerCase() !== 'xs') {
          that.disCacheKey++
          that.chartLevel = 'Xs'
        }
      })
    }, 200)
  },
  mounted () {
    const that = this

    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)
        if (this.$refs.chartComponent.debounceResize) {
          this.$refs.chartComponent.debounceResize(w, h)
        }
      })
    })
  },
  computed: {
    ...mapState({
      jhRecord: state => state.topWellChoosen.wellRecord
    }),
    chartComponent: function () {
      if (!this.dataReady) {
        return () => import(`@/views/tools/sub/warnHistory/DataNotReady`)
      }
      if (!this.chartLevel) {
        return () => import(`@/views/tools/sub/warnHistory/Xs`)
      } else {
        return () => import(`@/views/tools/sub/warnHistory/${this.chartLevel}`)
      }
    }

  },
  watch: {}
}
</script>

<style lang="less" scoped>
.chart {
  min-height: 150px;
  width: 100%;
  height: 100%;
}
.fitHeight {
  /deep/ .ant-spin-container {
    height: 100%;
  }
}
</style>
