<template>
  <a-spin
    ref="container"
    :spinning="spin.isLoading"
    :tip="spin.tip"
    style="width: 100%; height: 100%"
    wrapperClassName="fitHeight"
  >
    <a-alert v-if="showLineEmpty" message="请点击右上配置按钮，选择显示的数据项" />
    <div :id="chartId" class="chart" style="width: 100%; height: 100%"></div>
    <div v-if="showLoading" style="position: absolute; top: 0px">
      <a-icon type="sync" spin theme="towTone" />
    </div>
    <a-modal
      title="数据项监测-配置项"
      :width="970"
      :visible="configVisible"
      @cancel="handleCancel"
      @ok="handleOk"
      :maskClosable="false"
      destroyOnClose
      :okButtonProps="{ style: { display: 'none' } }"
      cancelText="关闭"
    >
      <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="日期" v-if="false">
          <a-date-picker v-model="config.queryDate" style="width: 195px" />
        </a-form-model-item>
        <a-form-model-item v-if="false">
          <span slot="label">
            小时显示数&nbsp;
            <a-tooltip title="图表最多可以显示的小时间隔，最小可选2小时，最大24小时">
              <a-icon style="color: rgb(82, 196, 26)" type="question-circle" />
            </a-tooltip>
          </span>
          <a-slider
            v-model="config.hours.vals"
            @afterChange="handleHoursChanged"
            :min="0"
            :max="24"
            range
            :marks="config.hours.marks"
          />
        </a-form-model-item>
        <a-form-model-item :label-col="labelCol" :wrapper-col="{ span: 18 }">
          <span slot="label">
            数据项（已选{{ config.lines.selected.length }}）<br />
            <a-icon v-show="this.isLtd" type="filter" style="position: relative; bottom: 20px" />
            <a-checkbox-group v-show="this.isLtd" v-model="config.lines.kindSelected" @change="handleLineKindChanged">
              <a-checkbox style="color: blue; display: block" value="工程">工程</a-checkbox>
              <a-checkbox style="color: blue; display: block" value="气测">气测</a-checkbox>
              <a-checkbox style="color: blue; display: block" value="泥浆">泥浆</a-checkbox>
            </a-checkbox-group>
          </span>
          <a-checkbox-group
            class="fixAppend"
            :options="config.lines.configData"
            @change="handleLineNamesChanged"
            v-model="config.lines.selected"
          >
            <span
              slot="label"
              slot-scope="{ title, value }"
              :style="config.lines.highlightList.indexOf(value) > -1 ? { color: 'red' } : {}"
            >
              {{ title }}
            </span>
          </a-checkbox-group>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </a-spin>
</template>

<script>
// todo: 1.从配置信息加载 多个坐标轴范围
import * as echarts from 'echarts'
import elementResizeDetector from 'element-resize-detector'
import _ from 'lodash'
import moment from 'moment'
import { ajaxGetDictItems } from '@/api/api'
import { mergeOption, calLineProps } from './funcs/linesChartOption'
import warnApi from '@/api/warnApi'
import vue from 'vue'
import { emptyLtdRecord } from './funcs/emptyLtdRecord'
import { emptyZjyRecord } from './funcs/emptyZjyRecord'
import { zjyKeys } from './sub/valuesMoitorZjyKeys'

const lsLinesKey = 'VALUESMONITOR_LINENAME_CHOOSED'
const transLineProps = (list, titles) => {
  const lineProps = []
  list.forEach(k => {
    const dict = _.find(titles, v => {
      return v.value === k
    })
    if (dict) {
      lineProps.push({
        key: k,
        datasetId: 'dateset_raw',
        name: dict.text,
        encode: {
          x: 'TIME',
          y: k,
          tooltip: [k],
        },
        hasAloneDataset: false,
        dataRules: {}
      })
    }
  })
  return lineProps
}
export default {
  name: 'ValuesMonitor',
  components: {},
  props: {
    widgetItemData: {
      type: Object,
      default: () => { }
    }
  },
  data () {
    return {
      moment,
      showLineEmpty: false,
      showLoading: false,
      spin: {
        isLoading: false,
        tip: ''
      },
      minSize: { width: 330, height: 260 },

      myChart: {},
      chartId: 'valuesChart' + moment().unix(),

      configVisible: false,
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
      config: {
        jh: '井号123',
        lastTime: moment(),
        queryDate: moment(),
        hours: {
          min: 0,
          max: 24,
          marks: { 0: '0', 24: '24' },
          vals: [0, 24]
        },
        lines: {
          configData: [],
          selected: [],
          kindList: ['工程', '气测', '泥浆'],
          kindSelected: undefined,
          highlightList: [],
          maxCount: 5
        },
        refreshProps: {
          canRefresh: true,
          interval: 10 * 1000,
          lastRecord: undefined,
          mid: -1,
          stopLog: []
        }
      },
      isLtd: false
    }
  },
  methods: {
    executeFromParent (which, paras) {
      switch (which) {
        case 'SHOWCONFIG':
          this.configVisible = true
          break
        default:
          break
      }
    },
    handleOk () {
      this.configVisible = false
      this.$emit('configChanged')
    },
    handleCancel () {
      // this.config = this.$options.data().config
      this.configVisible = false
    },
    loadLineNames (after) {
      if (this.isLtd) {
        ajaxGetDictItems('data_source')
          .then(res => {
            if (res.success) {
              this.config.lines.configData = res.result
              after()
              this.$nextTick(function () {
                this.chartInit()
              })
            } else {
              this.$message.error('加载曲线可选项时出错，请重试')
            }
          }).catch(e => {

          })
      } else {
        this.config.lines.configData = zjyKeys
        after()
        this.$nextTick(function () {
          this.chartInit()
        })
      }
    },
    handleHoursChanged (values) {
      if (values.length === 2 && Math.abs(values[1] - values[0]) < 2) {
        if (values[0] <= 22) {
          this.config.hours.vals = [values[0], values[0] + 2]
        } else {
          this.config.hours.vals = [values[0] - 2, values[0]]
        }
        this.$message.warning('时间间隔最小为2小时，已自动调整')
      }
      const valObj = {}
      this.config.hours.vals.forEach(p => valObj[p] = p.toString())
      this.config.hours.marks = { 0: '0', 24: '24', ...valObj }
    },
    handleLineKindChanged (values) {
      const project = ['FLOWIN', 'FLOWOUTPERCENT', 'SPP', 'TORQUE', 'ROP_INST', 'RPM', 'WOB', 'HKH', 'WOH']
      const gas = ['TG', 'C1', 'C2', 'C3', 'IC4', 'NC4', 'IC5', 'NC5', 'HKH', 'SPP', 'WOB', 'CONDIN', 'CO2', 'H2S1', 'MWOUT']
      const mud = ['PIT8', 'MWIN', 'PITTOTAL', 'MWOUT', 'FLOWIN', 'FLOWOUTPERCENT', 'CONDIN', 'CONDOUT', 'TEMPIN', 'TEMPOUT', 'PITTOTAL', 'PIT1', 'PIT2', 'PIT3', 'PIT4', 'PIT5', 'PIT6', 'PIT7']
      let dst = []
      values.forEach(k => {
        if (k === '工程') dst = dst.concat(project)
        if (k === '气测') dst = dst.concat(gas)
        if (k === '泥浆') dst = dst.concat(mud)
      })
      this.config.lines.highlightList = dst
    },
    handleLineNamesChanged (values) {
      if (values.length > this.config.lines.maxCount) {
      }
      this.showLineEmpty = values.length === 0
      vue.ls.set(lsLinesKey, this.config.lines.selected)
      this.$nextTick(() => {
        const lineProps = transLineProps(values, this.config.lines.configData)
        const newChart = calLineProps(lineProps)
        const chartOption = this.myChart.getOption()
        var rawDs = chartOption.dataset[0]
        if (chartOption.series.length === 0) {
          this.myChart = echarts.init(document.getElementById(this.chartId), 'shine')
          this.chartInit()
        } else {
          this.myChart.setOption({
            dataset: [rawDs, ...newChart.datasetAppend],
            series: newChart.series
          }, { replaceMerge: 'series' })

        }
      })
    },

    chartInit () {
      this.spin.isLoading = true
      warnApi.getValueMonitorLastHour({ jh: this.widgetItemData.wellRecord.JH, ltd: this.isLtd ? '1' : '0' })
        .then(res => {
          const total = res.result.ltd.length
          if (total < 450) {
            const firstTime = moment(res.result.ltd[0].TIME).add((450 - total + 1) * -10, 's')
            const ahead = []
            for (var i = 0; i < 450 - total; i++) {
              const tr = this.isLtd ? emptyLtdRecord() : emptyZjyRecord()
              tr.TIME = firstTime.add(5, 's').format('YYYY-MM-DD HH:mm:ss')
              ahead.push(tr)
            }
            res.result.ltd = ahead.concat(res.result.ltd)
          }

          const last = _.last(res.result.ltd)
          let lsValue = vue.ls.get(lsLinesKey)
          lsValue = !lsValue ? [] : lsValue
          const lineProps = lsValue.length > 0 ? transLineProps(lsValue, this.config.lines.configData) : []
          this.showLineEmpty = lineProps.length === 0
          const testOption = mergeOption({}, lineProps)
          testOption.dataset[0].source = res.result.ltd
          testOption.title.text = last.TIME.split('.')[0]
          this.myChart.setOption(testOption)
          this.spin.isLoading = false
          this.config.refreshProps.lastRecord = res.result.ltd.length > 0 ? _.last(res.result.ltd) : {}
          this.config.refreshProps.canRefresh = moment().format('YYYY-MM-DD') === last.TIME.split(' ')[0]
          this.refreshNewest(this.config.refreshProps.mid)
        }).catch(e => {
          this.spin.isLoading = false
        })
    },
    refreshNewest (seqId) {
      if (this._isDestroyed) return
      const that = this
      function doNext () {
        that.showLoading = false
        that.config.refreshProps.mid++
        setTimeout(() => {
          that.refreshNewest(that.config.refreshProps.mid)
        }, that.config.refreshProps.interval)
      }
      if (seqId === this.config.refreshProps.mid) {
        if (this.config.refreshProps.canRefresh) {
          this.showLoading = true
          // rule time > last And day is last.day
          warnApi.getValueMonitorNew({
            jh: this.widgetItemData.wellRecord.JH,
            lastTime: this.config.refreshProps.lastRecord.TIME,
            ltd: this.isLtd ? '1' : '0'
          })
            .then(ajax => {
              const res = ajax.result.ltd
              const total = res.length
              if (total > 0) {
                this.config.refreshProps.lastRecord = res[total - 1]
                const ltdData = this.myChart.getOption().dataset[0].source
                res.forEach(d => {
                  ltdData.shift()
                  ltdData.push(d)
                })

                this.myChart.setOption({
                  title: {
                    text: res[total - 1].TIME.split('.')[0]
                  },
                  dataset: [{
                    source: ltdData
                  }]
                })
              }
              doNext()
            }).catch(e => {
              this.$message.error('获取最新数据时出错')
              doNext()
            })
        } else {
          doNext()
        }
      }
    },
    stopRefresh () {
      stopLog.push({
        tid: moment().unix(),
        midValue: this.config.refreshProps.mid
      })
      this.config.refreshProps.mid += 10
    }
  },
  created () {
    this.debounceResize = _.debounce((rec) => {
      const { myChart, chartId } = this
      myChart.resize()
    }, 200)
  },
  mounted () {
    this.myChart = echarts.init(document.getElementById(this.chartId), 'shine')
    this.isLtd = this.widgetItemData.wellRecord.ltd === 1

    this.loadLineNames(() => {
      const lsValue = vue.ls.get(lsLinesKey)
      if (lsValue) {
        this.config.lines.selected = lsValue
      }
      this.showLineEmpty = this.config.lines.selected === undefined || this.config.lines.selected.length === 0
    })
    this.config.jh = this.widgetItemData.wellRecord.JH
    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 })
      })
    })
  },
  watch: {
  }
}
</script>

<style lang="less" scoped>
.chart {
  min-height: 150px;
}
.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);
}

.fixAppend {
  /deep/ .ant-checkbox-wrapper {
    width: 120px;
  }
}
</style>
