<template>
  <a-spin
    :id="containerId"
    ref="container"
    :spinning="spin.isLoading"
    :tip="spin.tip"
    style="width: 100%; height: 100%"
    wrapperClassName="fitHeight"
  >
    <a-row :style="{ height: sizeInfo.midOutRow.height }">
      <a-col span="8" :style="{ height: '560px' }">
        <div :id="chartMain.id" class="chart"></div>
      </a-col>
      <a-col span="16" :style="{}">
        <a-form :form="form">
          <a-form-item class="halfRow" :labelCol="labelCol2" :wrapperCol="wrapperCol2" label="复杂名称">
            <a-input
              placeholder="请输入复杂名称"
              v-decorator="['SGMC', { rules: [{ required: true, message: '请输入复杂名称' }] }]"
            />
          </a-form-item>
          <a-form-item class="halfRow" :labelCol="labelCol2" :wrapperCol="wrapperCol2" label="井号">
            <a-input
              placeholder="请输入井号"
              v-decorator="['JH', { rules: [{ required: true, message: '不能为空' }] }]"
            />
          </a-form-item>
          <a-form-item class="halfRow" :labelCol="labelCol2" :wrapperCol="wrapperCol2" label="复杂等级">
            <a-select
              placeholder="复杂等级"
              v-decorator="['SGDJBH', { rules: [{ required: true, message: '不能为空' }] }]"
            >
              <a-select-option value="ad7ef1c8-6688-467d-abfc-c03cf248aa26">一般</a-select-option>
              <a-select-option value="cb14a481-962b-4d17-af3e-a6514de2016e">严重</a-select-option>
              <a-select-option value="92c7c26a-10a7-486e-94b8-b35d90606bc3">非常严重</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item class="halfRow" :labelCol="labelCol2" :wrapperCol="wrapperCol2" label="事故类别">
            <a-select
              placeholder="事故类别"
              v-decorator="['SGLBID', { rules: [{ required: true, message: '不能为空' }] }]"
            >
              <a-select-option value="33607e02-9405-4b1f-9f8c-726ae92e46a8">卡钻</a-select-option>
              <a-select-option value="8a19698a-5e73-4fbe-be59-5de01cbe126c">井涌</a-select-option>
              <a-select-option value="6e7dc841-0277-419a-81c4-281fa5757e68">井漏</a-select-option>
              <a-select-option value="54edd711-0522-48f6-9145-e21cac046037">断钻具</a-select-option>
              <a-select-option value="63b2f72d-23fa-41e6-94e7-6e5fd3e03949">井塌</a-select-option>
              <a-select-option value="145362bf-6b83-40cd-a7b9-eb57b152099e">钻井液污染</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item class="halfRow" :labelCol="labelCol2" :wrapperCol="wrapperCol2" label="发生日期">
            <a-date-picker
              placeholder="发生日期"
              v-decorator="['FSRQ', { rules: [{ required: true, message: '不能为空' }] }]"
            />
          </a-form-item>
          <a-form-item class="halfRow" :labelCol="labelCol2" :wrapperCol="wrapperCol2" label="发生时间">
            <a-time-picker format="HH:mm" placeholder="发生时间" v-decorator="['FSSJ']" />
          </a-form-item>
          <a-form-item class="halfRow" :labelCol="labelCol2" :wrapperCol="wrapperCol2" label="解除日期">
            <a-date-picker
              placeholder="解除日期"
              v-decorator="['JCRQ', { rules: [{ required: true, message: '不能为空' }] }]"
            />
          </a-form-item>
          <a-form-item class="halfRow" :labelCol="labelCol2" :wrapperCol="wrapperCol2" label="解除时间">
            <a-time-picker format="HH:mm" placeholder="解除时间" v-decorator="['JCSJ']" />
          </a-form-item>
          <a-form-item class="halfRow" :labelCol="labelCol2" :wrapperCol="wrapperCol2" label="损失时间">
            <a-input-number :min="1" placeholder="损失时间" v-decorator="['SSSJ']" />
          </a-form-item>
          <a-form-item class="halfRow" :labelCol="labelCol2" :wrapperCol="wrapperCol2" label="当时井深">
            <a-input-number
              placeholder="当时井深"
              :min="0"
              v-decorator="['DSJS', { rules: [{ required: true, message: '不能为空' }] }]"
            />
          </a-form-item>
          <a-form-item class="fullRow" :labelCol="labelCol" :wrapperCol="wrapperCol" label="钻具组合">
            <a-textarea :rows="2" placeholder="请输入钻具组合" v-decorator="['NYHBKZZ']" />
          </a-form-item>
          <a-form-item class="fullRow" :labelCol="labelCol" :wrapperCol="wrapperCol" label="发生经过及原因">
            <a-textarea :rows="2" placeholder="请输入发生经过及原因" v-decorator="['FSJGJYY']" />
          </a-form-item>
          <a-form-item class="fullRow" :labelCol="labelCol" :wrapperCol="wrapperCol" label="处理情况">
            <a-textarea :rows="2" placeholder="请输入处理情况" v-decorator="['SGCLGK']" />
          </a-form-item>
        </a-form>
      </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 warnApi from '@/api/warnApi'
import { defaultColors, scatterColors, lineOptions, chartOption } from './funcs/stratum'

const breakPoints = { xxl: 1600, xl: 1200, lg: 992, md: 768, sm: 458, xs: -1 }
const sizeInfoBreaks = {
  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' }
  }
}
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: 'Stratum',
  props: {
    widgetItemData: {
      type: Object,
      default: () => { }
    }
  },
  data () {
    return {
      moment,
      spin: {
        isLoading: false,
        tip: ''
      },
      minSize: { width: 330, height: 260 },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 10 },
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 14 },
      },

      containerId: 'stratumContainer' + moment().unix(),
      chartMain: { id: 'stratumChart' + moment().unix(), chart: {} },
      config: {
        jh: '',
        lastTime: moment(),
        queryDate: moment()
      },
      sizeInfo: {
        midOutRow: {
          height: 'auto'
        },
        midChart1: {
          span: 24,
          height: '200px'
        },
        midChart2: {
          span: 24,
          height: '200px'
        }
      },
      form: this.$form.createForm(this),
      viewable: true,
      list: {
        yData: [],
        secondYData: [],
        stratumData: [],
        caseData: [],
        types: []
      }
    }
  },
  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
    },
    getStratum () {
      const jh = this.widgetItemData.jhRecord.JH
      warnApi.queryStratum({ jh: jh, distance: '5000' })
        .then(res => {
          if (res.error) {
            this.viewable = false
            this.$notification.warning({ message: '提示', description: res.msg })
          } else {
            const data = res.result.cw
            if (data.length == 0) {
              this.viewable = false
              this.$notification.warning({ message: '提示', description: '没有可显示的地层数据' })
            } else {
              const b = res.result.bottom
              lineOptions.wellBottom = (parseFloat(b) / 1000 + 1) * 1000
              var first = data[0]
              this.pushStratumInfo(first.CW, first.SJDJSD - first.SJHD, first.SJHD, 0, first.SL);
              for (var i = 1; i < data.length; i++) {
                var item = data[i]
                this.pushStratumInfo(item.CW, item.SJDJSD - item.SJHD, item.SJDJSD, i, item.SL);
              }
              for (var i = 0; i <= 15000; i++) {
                this.list.yData.push(i.toString())
              }
              const option = chartOption(this.chartMain.chart, lineOptions, this.list.yData, this.list.stratumData, this.list.caseData)
              this.chartMain.chart.setOption(option)
              this.debounceResize()
              this.loadCaseData()
            }
          }
        }).catch(e => {
          this.$message.info(e.message)
        })
    },
    pushStratumInfo (name, begin, end, index, caseCount) {
      var color = defaultColors[index % defaultColors.length]
      this.list.stratumData.push({
        name: name,
        value: [
          index,
          begin,
          end,
          end - begin,
          caseCount
        ],
        itemStyle: {
          color: color
        }
      })
    },
    loadCaseData () {
      warnApi.queryCaseInDistance({ jh: this.widgetItemData.jhRecord.JH, distance: '5000' })
        .then(res => {
          const data = res.result.data
          var caseLevels = ['一般', '严重', '非常严重'];
          var horizoneOffset = 0;
          for (var i = 0; i < data.length; i++) {
            var item = data[i], xValue = 0.9;
            if (i != 0 && data[i - 1].DSJS == item.DSJS) {
              horizoneOffset++;
            } else {
              horizoneOffset = 0;
            }
            xValue += horizoneOffset * 0.035;
            xValue = xValue > 1 ? 1 : xValue;
            var caseIndex = caseLevels.indexOf(item.CASELEVEL);
            if (caseIndex == -1) {
              caseIndex = 0;
            }
            this.list.caseData.push({
              name: '案例' + i,
              value: [xValue, parseFloat(item.DSJS)],
              itemStyle: {
                color: scatterColors[caseIndex]
              },
              labelText: item.SGMC + '(' + item.JH + ')',
              caseId: item.ID
            })
          }

          this.chartMain.chart.setOption({ series: [{}, { data: this.list.caseData }, { data: this.list.caseData }] });
        }).catch(e => {
          this.$message.info(e.message)
        })
    }
  },
  created () {
    this.debounceResize = _.debounce((rec) => {
      const { chartMain } = this
      chartMain.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 ------------------------------- 
    }, 200)
  },
  mounted () {
    this.form.setFieldsValue({})
    this.chartMain.chart = echarts.init(document.getElementById(this.chartMain.id))
    const that = this

    this.getStratum()

    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)
      })
    })


    this.chartMain.chart.on('click', function (params) {
      if (params.seriesIndex == 0) {

      } else if (params.seriesIndex == 1) {
        const caseId = params.data.caseId, title = params.data.labelText
        warnApi.queryCase(caseId)
          .then(res => {
            that.form.setFieldsValue(res.result.data[0])
          }).catch(e => {
            this.$message.info(e.message)
          })
      }

    })
  },
  computed: {},
  watch: {}
}
</script>

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