<template>
  <div class="capacityCurve">
    <div class="out" v-if='isShow'>
      <span>
        水位 <input type="text" v-model='swVal' class="inp inbk" :disabled='calculateWater'/>
      </span>
      <img class="chage" src="~public/lwt-vue-components/default/assets/curve/switch.png" @click='changeDisable' />
      <span>
        {{typeTitle}} <input type="text" v-model='krVal' class="inp inbk" :disabled='!calculateWater'/>
      </span>
      <span class="inbk sec" @click='calculate'>计算</span>
      <span>
        当前水位：{{curSw}}{{curSwUnit}}  当前{{typeTitle}}：{{curKr}}{{curKrUnit}}  时间：{{curTm}}
      </span>
    </div>
    <div :id='canId' :style='{"width":wid + "px", "height":heig + "px", "display": isData ? "" : "none"}'></div>
    <div v-if='!isData' class='conted'>
      <img src="~public/lwt-vue-components/default/assets/profiles/noData.png" />
    </div>
  </div>
</template>
<script>
/**
 * module:库容曲线-组件
 * author:lwt
 */
import quick from '../../utils/quick'
export default {
  name: 'capacityCurve',
  components: {
  },
  props: {
    txt: Object,
    count: Object,
    chat: Object,
    othAttr: Object
  },
  data () {
    return {
      calculateWater: false,
      swVal: '',
      krVal: '',
      curSw: '',
      curSwUnit: '',
      curKr: '',
      curKrUnit: '',
      curTm: '',
      max: 0,
      min: 0,
      sers: [],
      wid: 0,
      heig: 0,
      // countPath: '',
      // krvalPath: '',
      isData: true,
      countInf: {}, // 配置水位-库容计算信息
      chatInf: {}, //  配置库容曲线信息
      othAttrInf: {}, // 配置其它信息
      canId: '',
      isShow: true, // 是否显示头部计算工具，false：是，true或不设置：否
      typeTitle: ''
    }
  },
  created: function () {
    // console.log('实例初始化完成调用')
    this.canId = 'curve' + Math.random() * 10
    // this.curSw = this.$props.txt.sw
    // this.curKr = this.$props.txt.kr
    // this.curTm = this.$props.txt.tm
    // this.krvalPath = this.$props.txt.krvalPath
    // this.countPath = this.$props.txt.countPath
    this.crefun()
  },
  activated: function () {
    // console.log('keep-alive组件激活时调用')
    this.actfun()
  },
  methods: {
    crefun: function () { // 数据初始化
      this.countInf = this.$props.count
      this.chatInf = this.$props.chat
      this.othAttrInf = this.$props.othAttr
      this.typeTitle = this.othAttrInf.typeTitle || '库容'
      this.heig = this.othAttrInf.height
      this.wid = this.othAttrInf.width
      let { dataSource, valParams } = this.othAttrInf
      this.curSw = Number(quick.templateValue(valParams['sw'], dataSource))
      this.curSwUnit = valParams['swUnit'] === undefined ? 'm' : quick.templateValue(valParams['swUnit'], dataSource)
      this.curKr = quick.templateValue(valParams['kr'], dataSource)
      this.curKrUnit = valParams['krUnit'] === undefined ? '万m³' : quick.templateValue(valParams['krUnit'], dataSource)
      this.curKrUnit = this.curKr === '0' ? '' : this.curKrUnit
      this.curTm = quick.templateValue(valParams['tm'], dataSource) || ''
      this.swVal = ''
      this.krVal = ''
      this.isShow = this.$props.count.isShow === undefined ? true : this.$props.count.isShow
    },
    actfun: function () { // 请求库容曲线数据及绘制库容曲线
      let { krvalPath, dataSourceParams, DataKey, xDataKey, yDataKey } = this.chatInf
      let { dataSource, lineParams } = this.othAttrInf
      var params = {}
      for (let key in dataSourceParams) {
        params[key] = quick.templateValue(dataSourceParams[key], dataSource) || ''
      }
      var that = this
      this.$api({ url: krvalPath, 'params': params }).then(ret => {
        var data = quick.datasourByStr(DataKey, ret.data)
        // var data = ret.data.data
        if (data.length === 0) {
          that.isData = false
        } else {
          that.isData = true
        }
        var max, min
        lineParams.map(v => {
          var num = Number(quick.templateValue(v.key, dataSource)) || ''
          if (num !== '') {
            max = max === undefined ? num : max < num ? num : max
            min = min === undefined ? num : min > num ? num : min
          }
        })
        // for (let ite in lineParams) {
        //   var num = Number(quick.templateValue(lineParams[ite].key, dataSource)) || ''
        //   if (num !== '') {
        //     max = max === undefined ? num : max < num ? num : max
        //     min = min === undefined ? num : min > num ? num : min
        //   }
        // }
        var sers = []
        data.map(s => {
          max = max === undefined ? Number(quick.templateValue(yDataKey, s)) : max
          // max = max === undefined ? Number(quick.templateValue(yDataKey, s)) : max < num ? num : max
          min = min === undefined ? Number(quick.templateValue(yDataKey, s)) : min
          // min = min === undefined ? Number(quick.templateValue(yDataKey, s)) : min > num ? num : min
          max = Number(quick.templateValue(yDataKey, s)) > max ? Number(quick.templateValue(yDataKey, s)) : max
          min = Number(quick.templateValue(yDataKey, s)) < min ? Number(quick.templateValue(yDataKey, s)) : min
          sers.push([Number(quick.templateValue(xDataKey, s)), Number(quick.templateValue(yDataKey, s))])
        })
        // for (var s in data) {
        //   max = max === undefined ? Number(quick.templateValue(yDataKey, data[s])) : max < num ? num : max
        //   min = min === undefined ? Number(quick.templateValue(yDataKey, data[s])) : min > num ? num : min
        //   max = Number(quick.templateValue(yDataKey, data[s])) > max ? Number(quick.templateValue(yDataKey, data[s])) : max
        //   min = Number(quick.templateValue(yDataKey, data[s])) < min ? Number(quick.templateValue(yDataKey, data[s])) : min
        //   sers.push([Number(quick.templateValue(xDataKey, data[s])), Number(quick.templateValue(yDataKey, data[s]))])
        // }
        var limite = (max - min) / 6
        limite = limite < 0.1 ? 0.1 : limite
        min = (min - limite) < 0 ? 0 : (min - limite).toFixed(1)
        max = (max + limite).toFixed(1)
        this.min = min
        this.max = max
        this.sers = sers
        that.drawLine()
      }).catch(ret => {})
    },
    changeDisable: function () {
      this.calculateWater = !this.calculateWater
    },
    calculate: function () {
      // var params = {
      //   'stcd': this.$props.txt.stcd
      // }
      var params = {}
      var vals = { 'w': this.krVal, 'rz': this.swVal }
      let { dataSourceParamsSW, dataSourceParamsKR, swDataKey, krDataKey, countPath } = this.countInf
      let { dataSource } = this.othAttrInf
      var dataSourceParams = {}
      if (this.calculateWater) {
        dataSourceParams = dataSourceParamsSW
        // params['w'] = this.krVal
      } else {
        dataSourceParams = dataSourceParamsKR
        // params['rz'] = this.swVal
      }
      vals = quick.deepMerge(dataSource, vals)
      for (let key in dataSourceParams) {
        params[key] = quick.templateValue(dataSourceParams[key], vals) || ''
      }
      var that = this
      this.$api({ url: countPath, 'params': params }).then(ret => {
        if (that.calculateWater) {
          that.swVal = quick.datasourByStr(swDataKey, ret.data)
          // that.swVal = ret.data.data.val
        } else {
          that.krVal = quick.datasourByStr(krDataKey, ret.data)
          // that.krVal = ret.data.data.w
        }
      }
      ).catch(ret => {})
    },
    drawLine: function () { // 加载报图
      // 基于准备好的dom，初始化echarts实例
      var that = this
      var option = {
        title: { text: '' },
        tooltip: {
          trigger: 'axis',
          textStyle: {
            align: 'left'
          },
          formatter: function (params) {
            var str
            for (var i = 0, len = params.length, item; i < len; i++) {
              item = params[i]
              str = '库容:' + (item.data)[0] + that.curKrUnit + ';<br/>水位：' + (item.data)[1] + that.curSwUnit
            }
            return str
          }
        },
        legend: {
          data: ['水位'],
          show: false
        },
        grid: {
          left: '3%',
          bottom: '3%',
          right: '140',
          top: '40',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          name: '库容(万m³)',
          axisTick: {
            alignWithLabel: true
          },
          min: 0,
          splitLine: {
            show: true
          }
          // data: [30, 32.5, 33, 33.5, 34, 34.5, 35]
        },
        color: ['#0066cc'],
        yAxis: {
          name: '水位(m)',
          type: 'value',
          boundaryGap: [0, '100%'],
          min: this.min,
          max: this.max,
          splitLine: {
            show: true
          }
        },
        series: [{
          name: '水位',
          type: 'line',
          yAxisIndex: 0,
          showSymbol: false,
          hoverAnimation: true,
          data: this.sers,
          markPoint: this.getMarkPoint(),
          markLine: this.getMarkLine()
        }]
      }
      option = quick.deepMerge(option, this.othAttrInf.option)
      var myChart = this.$echarts.init(document.getElementById(this.canId))
      myChart.setOption(option)
    },
    getMarkLine: function () {
      var data = []
      var that = this
      let { dataSource, lineParams } = this.othAttrInf
      lineParams.map(v => {
        var num = Number(quick.templateValue(v.key, dataSource)) || ''
        if (num !== '') {
          data.push({
            name: v.name,
            yAxis: num,
            lineStyle: {
              color: v.lineColor || '#0066cc'
            },
            label: {
              normal: {
                position: 'end',
                formatter: v.name + num + that.curSwUnit
              }
            }
          })
        }
      })
      // for (let ite in lineParams) {
      //   var num = Number(quick.templateValue(lineParams[ite].key, dataSource)) || ''
      //   if (num !== '') {
      //     data.push({
      //       name: lineParams[ite].name,
      //       yAxis: num,
      //       lineStyle: {
      //         color: lineParams[ite].lineColor || '#0066cc'
      //       },
      //       label: {
      //         normal: {
      //           position: 'end',
      //           formatter: lineParams[ite].name + num + that.curSwUnit
      //         }
      //       }
      //     })
      //   }
      // }
      if (data.length < 1) {
        return {}
      } else {
        return { data: data }
      }
    },
    getMarkPoint: function () {
      var data = []
      var that = this
      // if (this.baseData.capacity != undefined && this.baseData.val != undefined) {
      data.push({
        name: '当前水位',
        // xAxis: this.$props.txt.kr,
        // yAxis: this.$props.txt.sw,
        xAxis: this.curKr,
        yAxis: this.curSw,
        symbolSize: [20, 20]
      })
      // }
      return {
        data: data,
        symbol: 'triangle',
        symbolOffset: [0, 10],
        itemStyle: {
          normal: {
            color: '#ff0000',
            label: {
              // position:'insideTop',
              position: [-40, -30],
              show: true,
              formatter: function (param) {
                return '当前水位' + that.curSw + that.curSwUnit
              }
            }
          }
        }
      }
    }
  },
  computed: {
  },
  directives: {
  },
  filters: {
  },
  watch: {
    count: function (val, oldVal) {
      this.crefun()
      this.actfun()
    },
    chat: function (val, oldVal) {
      this.crefun()
      this.actfun()
    },
    othAttr: function (val, oldVal) {
      this.crefun()
      this.actfun()
    }
  },
  beforeCreate: function () {
    // console.log('实例初始化前调用')
  },
  beforeMount: function () {
    // console.log('挂载到页面前调用')
  },
  mounted: function () {
    // console.log('挂载到页面完成调用')
  },
  beforeUpdate: function () {
    // console.log('更新前调用')
  },
  updated: function () {
    // console.log('更新完成调用')
  },
  deactivated: function () {
    // console.log('keep-alive组件停用时调用')
  },
  beforeDestroy: function () {
    // console.log('销毁之间调用')
  },
  destroyed: function () {
    // console.log('实例销毁后调用')
  },
  errorCaptured: function () {
    // console.log('异常发生处理')
  }
}
</script>
<style>
@import './capacityCurve.css';
</style>
