
<template>
  <div ref="page" :class="[warnTheme=='dark'?'page-dark':'page']">
    <div style="height:100%">
      <a-spin :spinning="spinning" style="height:100%" size="large">
      <splitpanes style="height: 100%;">
        <pane>
          <splitpanes horizontal class="backColor">
            <pane :size="topHeight">
              <div class="header-chart">
                <div class="headerOne">
                  <a-radio-group style="margin-top:13px" default-value="ltd" @change="goZjy" v-if="zjy==1">
                    <a-radio value="ltd" style="display:block" > 录井仪 </a-radio>
                    <a-radio value="zjy" style="display:block"> 钻井液 </a-radio>
                  </a-radio-group>
                  <div>时间</div>
                  <div style="color: #dc143c">实测井深</div>
                  <div style="color: #0000ff">(钻头位置)</div>
                  <!-- <a-date-picker @change="onTimeChange" :disabled-date="disabledDate" v-model="time"  size="small" style="width:118px;"/> -->
                  <div style="text-align: left;width:100%" >
                      <a-checkbox @change="onWarningChange" value="fzqk" style="margin-left:8px" :class="[warnTheme=='dark'?'foreColor-dark':'foreColor']">
                      邻井复杂
                      </a-checkbox>
                      <a-checkbox @change="onWarningChange" value="gcyj" style="margin-left:8px" :class="[warnTheme=='dark'?'foreColor-dark':'foreColor']">
                        工程预警
                      </a-checkbox>
                      <a-checkbox @change="onWarningChange" value="zx" style="margin-left:8px" :class="[warnTheme=='dark'?'foreColor-dark':'foreColor']">
                        钻屑
                      </a-checkbox>
                  </div>
                </div>
                <div
                  v-for="(item, index) in chartList"
                  :key="index"
                  :class="[item.fix==='1'?'header-content-fix':'header-content']"
                  :style="[{width:item.width+'px'}]"
                >
                  <draggable
                    class="slick-list"
                    group="site"
                    animation="300"
                    dragClass="dragClass"
                    ghostClass="ghostClass"
                    chosenClass="chosenClass"
                    v-model="item.children"
                    @end="draggableEnd"
                  >
                    <transition-group style="height: 100%;display: flex;flex-direction: column;">
                      <div
                        class="slick-item"
                        v-for="(item2, index2) in item.children"
                        :index="index2"
                        :key="index2"
                        :data-id="item.id"
                        @contextmenu.prevent="customClick($event,item.key,item2.key)"
                      >
                        <div
                          class="t-header"
                          :style="{ color: item2.color }"
                        >
                          <div style="text-align: center">
                            <a v-if="item2.opacity===0" @click="hideChart(item2.title+'('+item2.unit+')',item2.id,0)"><a-icon type="eye-invisible" theme="filled" style="font-size:15px;color:#d71345"/></a>
                            <a v-else @click="hideChart(item2.title+'('+item2.unit+')',item2.id,1)"><a-icon type="eye" theme="filled" style="font-size:15px;color:#009ad6"/></a>
                            {{ item2.title}}
                            {{ item2.val==undefined?'[]':item2.val }}
                          </div>
                          <a-divider
                            :style="{
                              margin: '0px',
                              background: item2.color,
                              height: '2px'
                            }"
                          />
                          <div style="display: flex">
                            <span style="flex: 1; text-align: left">
                              {{ item2.minNum }}
                            </span>
                            <span style="flex: 1; text-align: center" v-html="item2.unit"></span>
                            <span style="flex: 1; text-align: right">{{
                              item2.maxNum
                            }}</span>
                          </div>
                        </div>
                      </div>
                    </transition-group>
                  </draggable>
                </div>
                <div
                  v-for="(item, index) in warningList"
                  :key="index"
                  v-if="item.show"
                  class="warning-header"
                  :style="[{width:item.width+'px',height:'100%',textAlign:'center'}]"
                >
                <span>{{item.name}}</span>
                <span v-if="item.id=='fzqk'" style="width:70px;margin:10px auto 0">扫描范围:</span>
                <a-select default-value="5000" @change="fzqkRadiusChange" size="small" style="width:70px;margin:1px auto" v-if="item.id=='fzqk'">
                  <a-select-option value="3000">
                    3km
                  </a-select-option>
                  <a-select-option value="5000">
                    5km
                  </a-select-option>
                  <a-select-option value="8000">
                    8km
                  </a-select-option>
                  <a-select-option value="10000">
                    10km
                  </a-select-option>
                </a-select>
                </div>
              </div>
            </pane>
            <pane style="overflow: visible;" :size="bottomHeight">
              <div style="width:100%;height:100%;display:flex;">
                <div class="content">
                  <div class="chart" id="chartMain" ref="chartMain">
                    <div
                      id="chartContent"
                      class="chart-item"
                    >
                    </div>
                  </div>
                </div>
                <div style="width:2%;height:100%" id="dataZoomChart"></div>
              </div>
            </pane>
          </splitpanes>
        </pane>
      </splitpanes>
      </a-spin>
    </div>
    <a-modal title="新增曲线道" @ok="handleOk" width="1000px" v-model="addVisible">
      <AddOptions ref="addOptionsModel" :chartKey="newTrackKey" v-if="addVisible"/>
    </a-modal>
    <a-modal v-model="OpVisible" title="配置" @ok="handleOptionsOk" width="1000px">
      <ChartOptions ref="chartOptionsModel" :selectedKey="selectedKey" :configureKey="selectedConfigureKey" v-if="OpVisible"/>
    </a-modal>
    <a-menu class="menustyle" :style="menuStyle" v-if="menuVisible" id="menu" >
      <a-menu-item>
        <a @click="showOptionsModal">配置</a>
      </a-menu-item>
      <a-menu-item>
        <a @click="deleteChart">删除</a>
      </a-menu-item>
      <a-menu-item>
        <a @click="showModal('r')">右侧新增曲线道</a>
      </a-menu-item>
      <a-menu-item>
        <a @click="showModal('l')">左侧新增曲线道</a>
      </a-menu-item>
    </a-menu>
    <fzqk-form ref="fzqkForm"  />
  </div>
</template>
<script>
import * as echarts from 'echarts'
import { Splitpanes, Pane } from 'splitpanes'
import { mapState } from 'vuex'
import draggable from 'vuedraggable'
import elementResizeDetectorMaker from 'element-resize-detector'
import AddOptions from '@/views/form/addOptions'
import ChartOptions from '@/views/form/chartOptions'
import AddTemplate from '@/views/form/addTemplate'
import {getDateStr,randomNumber} from '@/utils/util'
import events from '@/views/top/events'
import moment from 'moment'
import {  scatterColors } from '@/views/tools/funcs/stratum'
import {
  getChartTreeList,
  deleteLine,moveLine,
  addByDirection,
  getTemplateList,
  getZjyData,
  getFzqkData,
  getJwssList,
  getAnalyse,
  getAllDate } from '@/api/api'
import warnApi from '@/api/warnApi'
import FzqkForm from './FzqkForm'
import _ from 'lodash'
let mainChart=null//主图表实例
let timer=null//防抖的计时器
let timer2=null//监听防抖
let intervalId=null
let fzqkIntervalId=null//复杂情况的定时器id
let gcyjIntervalId=null//工程预警的定时器id
let zjyTimeInterval=1000*60//钻井液获取数据时间间隔
let fzqkTimeInterval=1000*60*30//复杂情况获取数据时间间隔
let gcyjTimeInterval=1000*60*60//工程预警获取数据的时间间隔
let fzqkList=[]//复杂情况数据
const chartColor=['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc']
export default ({
  name: 'IndexEChatsJwss',
  components: {
    Splitpanes,
    Pane,
    draggable,
    AddOptions,
    ChartOptions,
    AddTemplate,
    FzqkForm
  },
  props:{
    jhProp:{
      type: [String, String],
      default: '车古271'
    },
    zjy:{
      type: Number,
      default: 1
    }
  },
  data () {
    return {
      chart: null,
      menuVisible: false,//右键菜单弹窗
      addVisible: false,//新增曲线道弹窗
      OpVisible: false,//配置弹窗
      topHeight:37,//顶部pane高度
      bottomHeight:63,//底部pane高度
      menuStyle: {
        position: 'absolute',
        top: '0',
        left: '0',
        zIndex: 1,
        borderRadius: '5px',
        border: '1px solid #eee'
      },
      spinning:false,//loading
      selectedKey: undefined,// 选中的曲线
      selectedPKey: undefined,// 选中的曲线道
      selectedConfigureKey: '1', // 选中的配置项key
      newTrackKey: undefined,// 新增时新的曲线道key
      direction: 'r',// 新增曲线道方向
      yType: 'time', // 当前显示深度还是时间
      jh:this.jhProp,//井号
      time:'',//时间select
      time1:'2017-04-19 00:00:00',
      time2:'2017-04-19 02:00:00',
      realTime:'',//即时时间
      timeAllDate:[],//所有的时间数据
      // 当前图表数据
      chartList: [
      ],
      allRealTime:[],//缓存实时数据
      warningList:[
        {
          name:'邻井复杂',
          width:'80',
          show:false,
          id:'fzqk',
          jh:'',
          loading:false
        },
         {
          name:'工程预警',
          width:'80',
          show:false,
          id:'gcyj',
          jh:'',
          loading:false
        },
         {
          name:'钻井液',
          width:'80',
          show:false,
          id:'zjy',
          jh:'',
          loading:false
        },
        {
          name:'钻屑',
          width:'160',
          show:false,
          id:'zx',
          jh:'',
          loading:false
        }
      ],//预警列表数据
      FzqkDeepth:[],//复杂情况预警需要的井深数据
      gcyjAllTime:[],//工程预警需要的时间参数
      runRecu:false,//是否运行递归
      config:{},//复杂情况x与y坐标
      deepthList:[],//整点的井深和钻头位置
      radius:'5000',//复杂情况半径
      chartFinished:false,//图表是否加载完成
      inited:false//是否初始化完毕
    }
  },
  created () {
    this.time=moment().format("YYYY-MM-DD")
  },
  mounted () {
    this.initAll()
    const _this = this
    const erd = elementResizeDetectorMaker()
    erd.listenTo(document.getElementById('chartMain'), element => {
      _this.$nextTick(() => {
        if (timer) {
          clearTimeout(timer)
        }
        timer = setTimeout(() => {
          _this.chartResize()
        }, 100)
      })
    })
    this.$nextTick(()=>{
       let headerHeight=160
          // this.chartList.forEach((item)=>{
          //   if(item.children.length>headerHeight){
          //     headerHeight=item.children.length
          //   }
          // })
          // if(headerHeight*43<176){
          //   headerHeight=176
          // }else{
          //   headerHeight=headerHeight*43
          // }
          const pageHeight=this.$refs.page.offsetHeight
          this.topHeight= headerHeight/pageHeight*100
          this.bottomHeight=100-this.topHeight
    })
  },
  beforeDestroy () {
    this.runRecu=false
    if(intervalId!=null){
      clearInterval(intervalId)
      intervalId=null
    }
    if(fzqkIntervalId!=null){
      clearInterval(fzqkIntervalId)
      fzqkIntervalId=null
    }
    if(gcyjIntervalId!=null){
      clearInterval(gcyjIntervalId)
      gcyjIntervalId=null
    }
    if(mainChart!=null){
        mainChart.clear()
        mainChart.dispose()
        this.chart.dispose()
        this.chart=null
        mainChart=null
      }
  },
  methods: {
   async initAll(){
        if(this.templateId!=undefined)
        {
          this.selectedConfigureKey=this.templateId
        }else{
          await this.loadTemplateListData()
        }
        await this.getData()
        if(this.jh=='车古271'){this.inited=true; return}
        this.$nextTick(() => {
          this.initChart('init')
        })
        this.inited=true
    },
    //获取模板
    async loadTemplateListData () {
      await getTemplateList().then(res => {
        if (res.success) {
          const exist = res.result.find(p => p.title === '综合')
          if (exist) {
            this.selectedConfigureKey = exist.id
          } else {
            this.selectedConfigureKey = res.result[0].id
          }
        } else {
          this.$message.error('获取可用模板数据时出错')
        }

      })
    },
    /* 获取最新时间 */
    async getTime(){
      const params={jh:this.jh}
      await getAllDate(params).then((res)=>{
         if(res.success){
           this.time=res.result[0]
           this.timeAllDate=[...res.result]
         }else{
           this.time=''
           this.$message.error(res.message)
         }
      })
    },
    /* 不能被选中的时间 */
    disabledDate(current){
      let result=true
      result=!this.timeAllDate.some(son=>{
        return moment(current).isSame(son,'day')
      })
      return result
    },
    /* 循环加载图表数据以及预警数据 */
    async loadChartData(){
       this.spinning=false
        this.deepthList=[]
        this.time1=this.time+' 00:00:00'
        this.time2=this.time+' 02:00:00'
        this.spinning=true
        this.runRecu=true
        const jh=this.jh
        const selectedConfigureKey=this.selectedConfigureKey
        await this.getInterval(false,jh,selectedConfigureKey)//生产数据的递归获取
    },
    /* 预警chart数据获取 */
    getWarningData(){
      if(intervalId!=null){
        clearInterval(intervalId)
        intervalId=null
      }
      if(fzqkIntervalId!=null){
        clearInterval(fzqkIntervalId)
        fzqkIntervalId=null
      }
      if(gcyjIntervalId!=null){
         clearInterval(gcyjIntervalId)
         gcyjIntervalId=null
      }
      const _this=this
      this.warningList.forEach((item)=>{
        if(item.show){
          if(item.id==='zjy'){
             _this.getZjyData(this.jh)
          }else if(item.id==='fzqk'){
             _this.getFzqkData(this.jh)
          }else if(item.id==='gcyj'){
            _this.getGcyjData(this.jh)
          }
        }
      })
      if(new Date().toDateString()===new Date(this.time).toDateString()){
        intervalId=setInterval(() => {
           this.warningList.forEach((item)=>{
              if(item.show){
                if(item.id==='zjy'){
                  _this.getZjyData(this.jh)
                }
              }
            })
        }, zjyTimeInterval)
      }
    },
    /* 获取图表配置数据 */
   async getData () {
      const _this=this
      await getChartTreeList({id:this.selectedConfigureKey}).then((res)=>{
        if(res.success){
           _this.chartList=[...res.result[0].children]
           _this.yType=res.result[0].yType
           if(_this.allRealTime.length===0){
             _this.chartList.forEach((chartItem)=>{
               chartItem.children.forEach((childItem)=>{
                 const realTimeItem={id:childItem.id,num:'[]'}
                 _this.allRealTime.push(realTimeItem)
               })
             })
           }
           if(_this.allRealTime.length>0)
           {
             _this.allRealTime.forEach((realTimeItem)=>{
                _this.chartList.forEach((chartItem,index1)=>{
                  chartItem.children.forEach((childItem,index2)=>{
                    if(realTimeItem.id===childItem.id){
                       _this.$set(_this.chartList[index1].children[index2],'val',realTimeItem.num)
                    }
                  })
                })
             })
           }
        }
      })
    },
     /* 获取钻井液数据 */
    getZjyData(jh){
      if(!this.spinning){
        this.spinning=true
      }
      this.warningList[2].loading=true
      const params={jh:jh,time:this.time}
      try{
        getZjyData(params).then((res)=>{
         if(res.success&&res.result.length>0&&res.result[0].jh===this.jh)
         {
            let op=mainChart.getOption()
            let zjySeriesMap={}
            op.series.forEach((item)=>{
              if(item.id==='zjywarnings')
              {
                zjySeriesMap={...item}
              }
            })
            const zjySeriesAll=[]
            res.result.forEach((resItem,index)=>{
              let myZjySeriesMa={}
              myZjySeriesMa={...zjySeriesMap}
              const dataItem=[0.5]
              let bjlxStr=''
              if(resItem.bjlx==='0'){bjlxStr='门限报警'}
              if(resItem.bjlx==='1'){bjlxStr='溢流报警'}
              if(resItem.bjlx==='2'){bjlxStr='井漏报警'}
              if(resItem.bjlx==='3'){bjlxStr='异常报警'}
              dataItem.push(resItem.sj)
              let dataConf={}
              dataConf.value=[...dataItem]
              dataConf.tooltip={
                show:true,
                formatter: '时间:'+resItem.sj+'</br>类型:'+bjlxStr+'</br>信息:'+resItem.bjxx
              }
              const sIndex=zjySeriesAll.findIndex(n=>n.id=='zjywarnings'+resItem.bjlx)
              if(sIndex>=0){
                 zjySeriesAll[sIndex].data.push(dataConf)
              }
              else{
                 myZjySeriesMa.label={
                  show:true,
                  position: 'right',
                  formatter: bjlxStr,
                  borderColor:'#000',
                  borderRadius:5,
                  padding:[1,3],
                  borderWidth:1
                }
                 myZjySeriesMa.id='zjywarnings'+resItem.bjlx
                 myZjySeriesMa.data=[]
                 myZjySeriesMa.data.push(dataConf)
                 myZjySeriesMa.itemStyle={}
                 myZjySeriesMa.itemStyle.color=chartColor[Number(resItem.bjlx)]
                 zjySeriesAll.push(myZjySeriesMa)
              }
            })
            const options={series:zjySeriesAll}
            mainChart.setOption(options)
         }
         this.setDownLoading('zjy')
        })
      }catch(error){
        this.setDownLoading('zjy')
      }
    },
    /* 获取复杂情况数据 */
    async getFzqkData(jh){
      let op1=mainChart.getOption()
      let deleteData={}
      op1.series.forEach((item)=>{
          if(item.id.indexOf('fzqkwarnings')>=0)
          {
            deleteData.id=item.id
            deleteData.data=[]
          }
      })
      mainChart.setOption({series:deleteData})
      if(!this.spinning){
        this.spinning=true
      }
      this.warningList[0].loading=true
      let isRun=true
       //const alfzqk=["井涌", "卡钻", "井漏", "断钻具", "井塌", "钻井液污染","粘吸卡钻","盐水侵","缩径卡钻"]
       const caseLevels = ['一般', '严重', '非常严重']
       try{
        await warnApi.queryCaseInDistance({jh:jh,distance:this.radius}).then(res=>{
           const data = res.result.data
           let op=mainChart.getOption()
           let SeriesList=[]
           let fzqkSeriesMap1={}
           op.series.forEach(opItem1=>{
             if(opItem1.id=='fzqkwarnings'){
                fzqkSeriesMap1={...opItem1}
             }
           })
           console.log('2'+fzqkSeriesMap1)
           SeriesList.push(fzqkSeriesMap1)

           for(let index = 0; index < this.FzqkDeepth.length; index++){
            data.forEach((resItem)=>{
              if((Number(resItem.DSJS)-Number(this.FzqkDeepth[index].deepth)<1)&&(Number(resItem.DSJS)-Number(this.FzqkDeepth[index].deepth)>-1)){
                let caseIndex = caseLevels.indexOf(resItem.CASELEVEL)
                if (caseIndex == -1) {
                  caseIndex = 0
                }
                //const fzmcIndex=alfzqk.findIndex(n=>n===resItem.SGMC)
                const dataItem=[0.1,this.FzqkDeepth[index].time,resItem.SGMC+'('+resItem.JH+')',resItem.ID,resItem.JH]
                const idIndex=SeriesList.findIndex(n=>n.id=='fzqkwarnings'+caseIndex)
                if(idIndex>=0){
                    SeriesList[idIndex].data.push(dataItem)
                }else{
                  //console.log(caseIndex)
                  let unitData=SeriesList.find(n=>n.id=='fzqkwarnings')
                  let fzqkSeriesMap2=_.cloneDeep(unitData)
                    const normal={
                    color:scatterColors[caseIndex],
                    barBorderRadius: 5
                    }
                    fzqkSeriesMap2.data.push(dataItem)
                    fzqkSeriesMap2.id='fzqkwarnings'+caseIndex
                    fzqkSeriesMap2.itemStyle.normal=normal
                    fzqkSeriesMap2.itemStyle.color=scatterColors[caseIndex]
                    SeriesList.push(fzqkSeriesMap2)
                }
              }
            })
           }
            const options={series:SeriesList}
            mainChart.setOption(options)
        })

        this.setDownLoading('fzqk')
       }catch(error){
         this.setDownLoading('fzqk')
       }

    },
    /* 获取工程预警数据 */
    async getGcyjData(jh){
      if(!this.spinning){
        this.spinning=true
      }
      this.warningList[1].loading=true
      try{
        for (let index = 0; index < this.gcyjAllTime.length; index++) {
          const param={jh:jh,ltdTime:this.gcyjAllTime[index]}
          await getAnalyse(param).then((res)=>{
            if(res.success&&res.result.length>0&&jh===this.jh)
              {
                let num=0
                const sortList=_.reverse(res.result)
                let name=''
                let warningMsg=''
                sortList.forEach((resItem)=>{
                  if(name.indexOf(resItem._name)==-1){
                    num++
                    const msgWarnStr=resItem.warnMsg.replace(/(\r\n)/g,'<br/>')
                    if(warningMsg===''){warningMsg=msgWarnStr}
                    else{warningMsg=warningMsg+'<br/>'+msgWarnStr}
                  }
                  if(name===''){
                    name=resItem._name
                  }
                  else{
                    if(name.indexOf(resItem._name)==-1){
                      name=name+','+resItem._name
                    }
                  }
                })
                let op=mainChart.getOption()
                let gcyjSeriesMap={}
                op.series.forEach((item)=>{
                    if(item.id==='gcyjwarnings')
                    {
                      gcyjSeriesMap={...item}
                    }
                })
                const dataItem=[0.5,this.gcyjAllTime[index]]
                let dataConf={}
                dataConf.value=[...dataItem]
                dataConf.itemStyle={
                  color:chartColor[num]
                }
                dataConf.tooltip={
                  show:true,
                  formatter: warningMsg
                }
                dataConf.label={
                  show:true,
                  position: 'right',
                  formatter: name,
                  borderColor:'#000',
                  borderRadius:5,
                  padding:[1,3],
                  borderWidth:1
                }
                gcyjSeriesMap.data.push(dataConf)
                const options={series:gcyjSeriesMap}
                mainChart.setOption(options)
              }
          })
        }
        this.setDownLoading('gcyj')
      }catch(error){
        this.setDownLoading('gcyj')
      }
      if(new Date().toDateString()===new Date(this.time).toDateString()){
          const _this=this
          gcyjIntervalId=setInterval(() => {
            if(_this.warningList[1].show&&new Date().toDateString()===new Date(_this.time).toDateString()){
              let realTime=this.realTime
              const param={jh:jh,ltdTime:realTime}
              getAnalyse(param).then((res)=>{
                if(res.success&&res.result.length>0&&jh===this.jh&&new Date().toDateString()===new Date(_this.time).toDateString())
                  {
                    let num=0
                    const sortList=_.reverse(res.result)
                    let name=''
                    let warningMsg=''
                    sortList.forEach((resItem)=>{
                      if(name.indexOf(resItem._name)==-1){
                        num++
                        const msgWarnStr=resItem.warnMsg.replace(/(\r\n)/g,'<br/>')
                        if(warningMsg===''){warningMsg=msgWarnStr}
                        else{warningMsg=warningMsg+'<br/>'+msgWarnStr}
                      }
                      if(name===''){
                        name=resItem._name
                      }
                      else{
                         if(name.indexOf(resItem._name)==-1){
                            name=name+','+resItem._name
                          }
                      }
                    })
                    let op=mainChart.getOption()
                    let gcyjSeriesMap={}
                    op.series.forEach((item)=>{
                        if(item.id==='gcyjwarnings')
                        {
                          gcyjSeriesMap={...item}
                        }
                    })
                    const dataItem=[0.5,realTime]
                    let dataConf={}
                    dataConf.value=[...dataItem]
                    dataConf.tooltip={
                      show:true,
                      formatter: warningMsg
                    }
                    dataConf.itemStyle={
                      color:chartColor[num]
                    }
                    dataConf.label={
                      show:true,
                      position: 'right',
                      formatter: name,
                      borderColor:'#000',
                      borderRadius:5,
                      padding:[1,3],
                      borderWidth:1
                    }
                    gcyjSeriesMap.data.push(dataConf)
                    const options={series:gcyjSeriesMap}
                    mainChart.setOption(options)
                  }
              })
            }else{
              clearInterval(gcyjIntervalId)
              gcyjIntervalId=null
            }
          }, gcyjTimeInterval);
      }
    },
    /* 关闭loading */
    setDownLoading(id){
      let setDown=true
      for (let index = 0; index < this.warningList.length; index++) {
        const item = this.warningList[index];
         if(item.id===id){
          item.loading=false
        }
        if(item.id!=id&&item.show&&item.loading){
          setDown=false
          break
        }
      }
      if(setDown){
        this.spinning=false
      }
    },
    /* 线程休眠 */
    sleep (time) {
      return new Promise((resolve) => setTimeout(resolve, time));
    },
    /*新接口递归 */
    async getInterval(isRealTime,jh,selectedConfigureKey){
        let resultStatus='1'
        if(this.runRecu){
           await this.getDataNew(isRealTime,jh,selectedConfigureKey).then((res)=>{
            resultStatus=res
          })
          console.log(resultStatus)
          if(resultStatus==='1'||resultStatus==='4'){
            this.setDownLoading('')
            if(!isRealTime){
              this.getWarningData()//预警部分的数据获取
            }
            await this.sleep(3000)
            //递归
            await this.getInterval(true,jh,selectedConfigureKey)
          }

        }


    },
     /*新 接口获取图表数据 */
    async getDataNew(isRealTime,jh,selectedConfigureKey){
      let resultStatus='1'
      let params={}
      const _this=this
      if(isRealTime){
           params={jh:jh,type:'',templateId:selectedConfigureKey}
        }else{
          params={jh:jh,type:'h',templateId:selectedConfigureKey}
        }
        if(this.runRecu){
          await getJwssList(params).then((res)=>{
            if(res.success&&res.result.length>0){
              if(res.result[0].templateId===this.selectedConfigureKey&&res.result[0].jh===this.jh){
                 if(res.result[0].time!=this.realTime){

                      let op=mainChart.getOption()
                      const listLength=res.result.length-1
                      res.result.forEach((itemRes,index1)=>{
                        _this.chartList.forEach((chartItem,index2)=>{
                          chartItem.children.forEach((childItem,index3)=>{
                            if(itemRes[childItem.dataSource.toLowerCase()]!=''
                              &&itemRes[childItem.dataSource.toLowerCase()]!=undefined
                              &&itemRes[childItem.dataSource.toLowerCase()]!=null
                              &&Number(itemRes[childItem.dataSource.toLowerCase()])>-999
                              ){
                                    if(childItem.data===undefined||childItem.data===null){
                                      childItem.data=[]
                                    }
                                    childItem.data.push(itemRes[childItem.dataSource.toLowerCase()])
                                    if(listLength===index1){
                                      let realTimeNum=itemRes[childItem.dataSource.toLowerCase()]
                                      if(realTimeNum==undefined)
                                      {
                                          realTimeNum=''
                                      }
                                      _this.allRealTime.forEach((realTimeItem)=>{
                                          if(realTimeItem.id===childItem.id){
                                            realTimeItem.num='['+realTimeNum+']'
                                          }
                                      })
                                      _this.$set(_this.chartList[index2].children[index3],'val','['+realTimeNum+']')
                                    }
                                }
                          })
                        })

                      op.series.forEach((item)=>{
                        if(item.id.indexOf('warnings')<0)
                        {
                            const dataItem=[]
                            const dataSource=item.id.split('-')[0]
                            if(itemRes[dataSource.toLowerCase()]!=''
                              &&itemRes[dataSource.toLowerCase()]!=undefined
                              &&itemRes[dataSource.toLowerCase()]!=null
                              &&Number(itemRes[dataSource.toLowerCase()])>-999
                              ){
                              dataItem.push(itemRes[dataSource.toLowerCase()])
                              dataItem.push(itemRes.time)
                              item.data.push(dataItem)
                            }

                        }
                      })
                      //获取刷新到此处的时间,用于当天实时刷新数据
                      _this.realTime=itemRes.time
                      //保存井深,用于获取复杂情况数据
                      const FzqkDeepthItem={}
                      FzqkDeepthItem.time=itemRes.time
                      FzqkDeepthItem.deepth=itemRes.depth
                      //用于y坐标轴显示井深和钻井位置(整点数据)
                      const wholeTime= moment(itemRes.time).set({'minute':'00','second':'00'}).format('YYYY-MM-DD HH:mm:ss')
                      if(!_this.deepthList.some(x=>{return x.time==wholeTime})){
                        const yDataDeepthItem={}
                        yDataDeepthItem.time=wholeTime
                        yDataDeepthItem.deepth=itemRes.depth
                        yDataDeepthItem.bitDepth=itemRes.bitdepth
                        _this.deepthList.push(yDataDeepthItem)
                      }
                      if(_this.FzqkDeepth.length>0){
                        const lastTime=_this.FzqkDeepth[_this.FzqkDeepth.length-1]
                        const futureTime= new Date(lastTime.time).getTime()+fzqkTimeInterval//获取未来五分钟后的时间戳（复杂情况）
                        const deepthIndex= _this.FzqkDeepth.findIndex(n=>n.deepth==itemRes.depth)//剔除重复的井深
                        if(new Date(itemRes.time).getTime()>=futureTime&&deepthIndex==-1){
                          FzqkDeepthItem.time=itemRes.time
                          FzqkDeepthItem.deepth=itemRes.depth
                          _this.FzqkDeepth.push(FzqkDeepthItem)
                        }
                      }else{
                        _this.FzqkDeepth.push(FzqkDeepthItem)
                      }
                      const gcyjLastTime=_this.gcyjAllTime.length>0?_this.gcyjAllTime[_this.gcyjAllTime.length-1]:_this.time+' 00:00:00'
                      const gcyjFutureTime=new Date(gcyjLastTime).getTime()+gcyjTimeInterval//获取未来五分钟时间戳(工程预警)
                      if(new Date(itemRes.time).getTime()>=gcyjFutureTime){
                          _this.gcyjAllTime.push(itemRes.time)
                        }
                    })
                      mainChart.setOption(op)
                      if(isRealTime){
                        resultStatus='4'
                      }else{
                        resultStatus='1'
                      }
                 }else{
                   resultStatus='4'
                 }

              }else{
                resultStatus='2'
              }
            }
            if(res.result==null||res.result.length==0){
              const templateId=res.message.split(',')[0]
              const jh=res.message.split(',')[1]
              if(templateId===this.selectedConfigureKey&&jh===this.jh)
              {
                resultStatus='4'
              }else{
                resultStatus='2'
              }
            }
          })
        }else{
          resultStatus='3'
        }
        return new Promise((resolve, reject)=>{
                resolve(resultStatus)
              })
    },
    //设置y轴井深和钻头位置
    setYDeepth(){
      const _this=this
      const yAxisItem={
        id:'y0',
        axisTick:{
          show:true,
          length:200
        },
        axisLabel:{
           color:this.warnTheme=='dark'?'#b581f5':'#000',
           verticalAlign:'bottom',
           formatter:function (value,index){
             const Time= moment(value).format('YYYY-MM-DD HH:mm:ss')
             const index2=_this.deepthList.findIndex(x=>x.time==Time)
             if(index2>=0){
               return _this.deepthList[index2].deepth+'\n('+_this.deepthList[index2].bitDepth+')\n'+moment(value).format('HH:mm')
             }else{
               return moment(value).format('HH:mm')
             }
           }
        }
      }
      mainChart.setOption({yAxis:yAxisItem})
    },
    /* 删除曲线 */
    deleteChart () {
       const _this = this
       this.$confirm({
        title: '是否确认删除此曲线?',
        onOk () {
           const chartIndex = _this.chartList.findIndex(n => n.key === _this.selectedPKey)
           const newChartData = _this.chartList[chartIndex].children.filter(item => {
           if (item.key === _this.selectedKey) {

            } else {
              return item
            }
           })
           _this.chartList[chartIndex].children=[...newChartData]
           _this.setOptions2(_this.chartList)
           deleteLine({id:_this.selectedKey.split('-')[2]}).then((res)=>{
                 if (res.success) {
                    _this.$message.success(res.message);
                  } else {
                    _this.$message.warning(res.message);
                  }
            })
        },
        onCancel () {}
      })
    },
    /* 显示曲线配置 */
    showOptionsModal () {
      this.OpVisible = true
    },
    handleOptionsOk (e) {
      this.OpVisible = false
    },
    /* 新增曲线道 */
    showModal (direction) {
      this.direction = direction
      this.newTrackKey = this.selectedConfigureKey + '-' + this.chartList.length
      this.addVisible = true
    },
    /* 新增曲线道 */
    handleOk (e) {
      if (this.$refs.addOptionsModel.treeData[0].children.length === 0) {
        this.$message.warning('请添加曲线')
        return
      }
      const parms={
        direction:this.direction,
        tempId:this.selectedConfigureKey,
        trackId:this.selectedPKey,
        newTrack:this.$refs.addOptionsModel.treeData[0]
      }
      const _this=this
      addByDirection(parms).then((res)=>{
         if(res.success){
            _this.getData().then((res)=>{
              _this.$nextTick(() => {
                _this.initChart()
              })
            })
        }else{
           _this.$message.warning(res.message);
        }
      })
      this.addVisible = false
    },
    /* 初始化图表 */
    initChart (from) {
      console.log(from)
      if(mainChart!=null){
        mainChart.clear()
        mainChart.dispose()
        this.chart.dispose()
        this.chart=null
        mainChart=null
      }
      this.chartFinished=false
      this.FzqkDeepth=[]
      this.gcyjAllTime=[]
      this.chartList.forEach(chartItem=>{
        chartItem.children.forEach(childItem=>{
          childItem.data=[]
        })
      })
      const chartsList = []
      mainChart = echarts.init(document.getElementById("chartContent"),'shine')
      this.chart = echarts.init(document.getElementById('dataZoomChart'),'shine')
      const _this=this
      this.$nextTick(() => {
            _this.dataZoomSetOptions(_this.chart)
            _this.setOptions(_this.chartList)
      })
      chartsList.push(mainChart)
      chartsList.push(this.chart)
      echarts.connect(chartsList)

      mainChart.on('finished',()=>{
        if(this.chartFinished==false){
          this.chartFinished=true
        }
      })
      mainChart.on('click','series.scatter.lable',(parms)=>{
        console.log(parms)
        this.$refs.fzqkForm.edit(parms.data)
      })
      while(true){
        if(this.chartFinished=true){
          this.loadChartData()
          break
        }
      }
    },
    /* 数据图表配置 */
    setOptions (chart) {
      const _this=this
      const timeDate=new Date(this.time)
      const tomorDay=new Date(new Date(timeDate.setDate(timeDate.getDate()+1)).setHours(2,0,0))
      const tomoStr= getDateStr(tomorDay)
      //const tomoStr= ''
      const dataZoomYIndex=[]
      for (let index = 0; index < this.chartList.length; index++) {
        dataZoomYIndex.push(index)
      }
      let warningWidth=0//预警部分图表的宽度
      this.warningList.forEach((item,index)=>{
        if(item.show){
          warningWidth+=Number(item.width)
          dataZoomYIndex.push((index+this.chartList.length))
        }
      })
      const options = {
        animation:false,
        tooltip: {
          show: true
        },
         dataZoom: [
          {
            type: 'inside',
            throttle:0,
            yAxisIndex: dataZoomYIndex,
            filterMode: 'none',
            start: 0,
            end: 100
          },
          {
            type: 'slider',
            yAxisIndex: 0,
            show: false,
            filterMode: 'none',
            handleSize: '100%',
            handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
            handleStyle: {
              color: '#0B3C6F',
              shadowBlur: 3,
              shadowColor: 'rgba(0, 0, 0, 0.6)',
              shadowOffsetX: 2,
              shadowOffsetY: 2
            },
            width: '7px',
            bottom: '10px',
            top: '5px'
          }
        ]
      }
      const series = []
      const grid = []
      const xAxis = []
      const yAxis = []
      if(!this.$refs.chartMain.offsetWidth){
          return
      }
      const chartMainWidth=this.$refs.chartMain.offsetWidth-120-warningWidth
      let fixWidth=0
      let rate = chart.length
      chart.forEach((item,index)=>{
        if(item.fix==='1')
        {
          fixWidth+=Number(item.width)
          rate--
        }
      })
      let chartWidth = (chartMainWidth-fixWidth) / rate
      let preLeft=117
      //一个grid多个x轴
      let xIndex=0
      chart.forEach((item, index) => {
        const width=item.fix==='1'?item.width:chartWidth
        const gridItem = {
          left: preLeft+'',
          right: '0',
          bottom: '0',
          top: '0',
          width: width+'',
          containLabel: false,
          tooltip: {
            show: true,
            trigger: 'axis',
            backgroundColor: 'rgba(255,255,255,0.6)',
            axisPointer: {
              label: {
                formatter: this.yType === 'time' ? '时间：{value}' : '深度：{value}',
                backgroundColor: '#777'
              }
            }
          },
          backgroundColor: 'transparent',
        }
        preLeft+=Number(width)
        let yAxisItem = {
          id:'y'+index,
          gridIndex: index,
          type: 'time',
          axisLine: { onZero: false, show: true,
          lineStyle:{color:this.warnTheme=='dark'?'#fbdc61':'#000'}
          },
          axisTick: { show: false,
          lineStyle:{color:this.warnTheme=='dark'?'#fbdc61':'#000'}
          },
          boundaryGap: false,
          min:this.time+' 00:00:00',
          max:tomoStr,
          //maxInterval: 3600 * 24 * 1000,
          splitNumber:10,
          splitLine: { // 网格线
            show: true,
            lineStyle:{
              color:'#aaa'
            }
          },
          axisLabel: {
           color:this.warnTheme=='dark'?'#b581f5':'#000',
           formatter: ''
          },
          data: [],
          inverse: true
        }
         if(index==0){
          yAxisItem={
            id:'y0',
            gridIndex: index,
            type: 'time',
            axisLine: { onZero: false, show: true,
            lineStyle:{color:this.warnTheme=='dark'?'#fbdc61':'#000'}
            },
            axisTick: { show: true,
            length:200,
            lineStyle:{color:this.warnTheme=='dark'?'#fbdc61':'#000'}
            },
            boundaryGap: false,
            min:this.time+' 00:00:00',
            max:tomoStr,
            //maxInterval: 3600 * 24 * 1000,
            splitNumber:10,
            splitLine: { // 网格线
              show: true,
              lineStyle:{
                color:'#aaa'
              }
            },
            axisLabel:{
              color:this.warnTheme=='dark'?'#b581f5':'#000',
              verticalAlign:'bottom',
              formatter:function (value,index){
                const Time= moment(value).format('YYYY-MM-DD HH:mm:ss')
                const index2=_this.deepthList.findIndex(x=>x.time==Time)
                if(index2>=0){
                  return moment(value).format('HH:mm')+'\n'+ _this.deepthList[index2].deepth+'\n('+_this.deepthList[index2].bitDepth+')'
                }else{
                  return moment(value).format('HH:mm')
                }
              }
            },
            data: [],
            inverse: true
          }
        }
        if(item.children===undefined||item.children.length===0)
        {
          const xAxisItem = {
            gridIndex: index,
            type: 'value',
            splitLine: { // 网格线
             show: true,
             lineStyle:{
              color:'#aaa'
            }
            },
            axisLabel: {
              formatter: function () {
                return ''
              }
            }
          }
          xAxis.push(xAxisItem)
        }
        item.children.forEach((ele,index2) => {
          const serItem = {
            id:ele.dataSource+'-'+xIndex,
            name: ele.title+'('+ele.unit+")",
            yAxisIndex: index,
            type: 'line',
            symbolSize: 10,
            symbol: 'circle',
            //smooth: ele.lineStyle === 'smooth',
            smooth: false,
            showSymbol: false,
            hoverAnimation: false,
            step: ele.lineStyle === 'step', // 阶梯线
            showSymbol: false,
            itemStyle: {
             width: 1,
             color: ele.color,
             style: 'solid'
            },
            emphasis: {
             focus: 'series'
            },
            xAxisIndex:xAxis.length,
            z:20-index2,
            data: []
          }
          const xAxisItem = {
            gridIndex: index,
            min:function (value) {
              if(ele.spread==='1'){
                if(ele.minSpread==='a')
                {
                  return  Math.floor(Number(value.min) / 10) * 10
                }else{
                  return value.min
                }
              }else{
                return ele.minNum
              }
            },
            max:function (value) {
              if(ele.spread==='1'){
                if(ele.minSpread==='a')
                {
                  return  Math.ceil(Number(value.max) / 10) * 10
                }else{
                  return value.max
                }
              }else{
                return ele.maxNum
              }
            },
            type: ele.background,
            splitLine: { // 网格线
             show: index2===0?true:false,
             lineStyle:{
              color:'#aaa'
            }
            },
            minorSplitLine:{
              show:ele.background=='log'?true:false,
              lineStyle:{
                color:'#aaa'
              }
            },
            axisLabel: {
              formatter: function () {
                return ''
              }
            }
          }
          series.push(serItem)
          xAxis.push(xAxisItem)
          xIndex++
        })
        grid.push(gridItem)
        yAxis.push(yAxisItem)
      })
      //预警部分图表
      let warningLeft=preLeft
      this.warningList.forEach((item,index)=>{
        if(item.show){
          let gridItem = {
            id:item.id+'grid',
            left: warningLeft+'',
            backgroundColor: 'transparent',
            right: '0',
            bottom: '0',
            top: '0',
            width: item.width,
            containLabel: false,
            tooltip:{show:false}
          }
          warningLeft+=Number(item.width)
          let yAxisItem = {
            id:item.id+'y',
            gridIndex: grid.length,
            type: 'time',
            axisLine: { onZero: false, show: true,
            lineStyle:{color:'#000'}
            },
            axisTick: { show:false },
            boundaryGap: false,
            min:this.time+' 00:00:00',
            max:tomoStr,
            maxInterval: 3600 * 24 * 1000,
            splitNumber:11,
            splitLine: { // 网格线
              show: true,
              lineStyle:{
              color:'#aaa'
            }
            },
            axisLabel: {
            formatter: ''
            },
            data: [],
            inverse: true
          }
          const xAxisItem = {
              id:item.id+'x',
              gridIndex: grid.length,
              min:0,
              max:3,
              type: 'value',
              splitLine: { // 网格线
              show: true,
               lineStyle:{
                color:'#aaa'
              }
              }
            }
          let serItem={
            id:item.id+'warnings',
            yAxisIndex: yAxis.length,
            xAxisIndex:xAxis.length,
            type: 'scatter',
            symbolSize: 20,
            data:[]
          }
          if(item.id==='fzqk'){
            serItem={
              id:item.id+'warnings',
              yAxisIndex: yAxis.length,
              xAxisIndex:xAxis.length,
              type: 'scatter',
              symbolSize: 0,
              data:[],
              tooltip:{show:false},
              label:{
                show:true,
                position: 'right',
                formatter: function (param) {
                  return param.data[2]
                },
                backgroundColor:'inherit',
                offset:[35,0],
                align: 'center',
                width:70,
                height:30,
                fontSize:10
              },
               labelLine: {
                show: true,
                length2: 5,
                lineStyle: {
                  color: '#bbb'
                }
              },
              itemStyle:{
  　　　　　　　　normal:{
  　　　　　　　　},　　　　
　　　　       }
            }
          }
          if(item.id==='zx')
          {
            yAxisItem = {
                id:item.id+'y',
                gridIndex: grid.length,
                type: 'category',
                axisLine: { onZero: false, show: true },
                axisTick: { show:false },
                boundaryGap: false,
                splitLine: { // 网格线
                  show: true,
                  lineStyle:{
                  color:'#aaa'
                }
                },
                axisLabel: {
                formatter: ''
                },
                data: [
                  '00:00',
                  '02:00',
                  '04:00',
                  '06:00',
                  '08:00',
                  '10:00',
                  '12:00',
                  '14:00',
                  '16:00',
                  '18:00',
                  '20:00',
                  '22:00',
                  '24:00'
                ],
            }
            serItem={
              id:item.id+'warnings',
              yAxisIndex: yAxis.length,
              xAxisIndex:xAxis.length,
              showSymbol: false,
              type: 'line',
              data:[1.4,1.2,0.5,0.6,0.9,1,2,2.1,2.2,2.3,2.4,2.5,2.7]
            }
            const serItem2={
              id:item.id+'warnings2',
              yAxisIndex: yAxis.length,
              xAxisIndex:xAxis.length,
              showSymbol: false,
              type: 'line',
              data:[2.4,2.2,2.5,2.6,2.9,2,2,2.1,2.0,2.0,2.0,2.1,2.7]
            }
            series.push(serItem2)
          }
          grid.push(gridItem)
          yAxis.push(yAxisItem)
          xAxis.push(xAxisItem)
          series.push(serItem)
        }
      })
      options.grid = grid
      options.xAxis = xAxis
      options.yAxis = yAxis
      options.series = series
      mainChart.setOption(options)
    },
     /* 数据图表配置2 */
    setOptions2 (chart) {
      const _this=this
      const timeDate=new Date(this.time)
      const tomorDay=new Date(new Date(timeDate.setDate(timeDate.getDate()+1)).setHours(2,0,0))
      const tomoStr= getDateStr(tomorDay)
      const options = mainChart.getOption()
      let warningWidth=0//预警部分图表的宽度
      const dataZoomYIndex=[]
      for (let index = 0; index < this.chartList.length; index++) {
        dataZoomYIndex.push(index)
      }
      let dataZoomIndex=0
      this.warningList.forEach((item,index)=>{
        if(item.show){
          warningWidth+=Number(item.width)
          dataZoomYIndex.push((dataZoomIndex+this.chartList.length))
          dataZoomIndex++
        }
      })
      options.dataZoom[0].yAxisIndex=dataZoomYIndex
      const series = []
      const grid = []
      const xAxis = []
      const yAxis = []
      const chartMainWidth=this.$refs.chartMain.offsetWidth-119-warningWidth
      let fixWidth=0
      let rate = chart.length
      chart.forEach((item,index)=>{
        if(item.fix==='1')
        {
          fixWidth+=Number(item.width)
          rate--
        }
      })
      let chartWidth = (chartMainWidth-fixWidth) / rate
      let preLeft=117
      //一个grid多个x轴
      let xIndex=0
      chart.forEach((item, index) => {
        const width=item.fix==='1'?item.width:chartWidth
        const gridItem = {
          left: preLeft+'',
          right: '0',
          bottom: '0',
          top: '0',
          width: width+'',
          containLabel: false,
          tooltip: {
            show: true,
            trigger: 'axis',
            backgroundColor: 'rgba(255,255,255,0.6)',
            axisPointer: {
              label: {
                formatter: this.yType === 'time' ? '时间：{value}' : '深度：{value}',
                backgroundColor: '#777'
              }
            }
          },
          backgroundColor: 'transparent',
        }
        preLeft+=Number(width)
         let yAxisItem = {
          id:'y'+index,
          gridIndex: index,
          type: 'time',
          axisLine: { onZero: false, show: true,
          lineStyle:{color:this.warnTheme=='dark'?'#fbdc61':'#000'}
          },
          axisTick: { show: false,
          lineStyle:{color:this.warnTheme=='dark'?'#fbdc61':'#000'}
          },
          boundaryGap: false,
          min:this.time+' 00:00:00',
          max:tomoStr,
          //maxInterval: 3600 * 24 * 1000,
          splitNumber:10,
          splitLine: { // 网格线
            show: true,
            lineStyle:{
              color:'#aaa'
            }
          },
          axisLabel: {
           color:this.warnTheme=='dark'?'#b581f5':'#000',
           formatter: ''
          },
          data: [],
          inverse: true
        }
         if(index==0){
          yAxisItem={
            id:'y0',
            gridIndex: index,
            type: 'time',
            axisLine: { onZero: false, show: true,
            lineStyle:{color:this.warnTheme=='dark'?'#fbdc61':'#000'}
            },
            axisTick: { show: true,
            length:200,
            lineStyle:{color:this.warnTheme=='dark'?'#fbdc61':'#000'}
            },
            boundaryGap: false,
            min:this.time+' 00:00:00',
            max:tomoStr,
            //maxInterval: 3600 * 24 * 1000,
            splitNumber:10,
            splitLine: { // 网格线
              show: true,
              lineStyle:{
                color:'#aaa'
              }
            },
            axisLabel:{
              color:this.warnTheme=='dark'?'#b581f5':'#000',
              verticalAlign:'bottom',
              formatter:function (value,index){
                const Time= moment(value).format('YYYY-MM-DD HH:mm:ss')
                const index2=_this.deepthList.findIndex(x=>x.time==Time)
                if(index2>=0){
                  return moment(value).format('HH:mm')+'\n'+ _this.deepthList[index2].deepth+'\n('+_this.deepthList[index2].bitDepth+')'
                }else{
                  return moment(value).format('HH:mm')
                }
              }
            },
            data: [],
            inverse: true
          }
        }
        if(item.children===undefined||item.children.length===0)
        {
          const xAxisItem = {
            gridIndex: index,
            type: 'value',
            splitLine: { // 网格线
             show: true,
             lineStyle:{
              color:'#aaa'
            }
            },
            axisLabel: {
              formatter: function () {
                return ''
              }
            }
          }
          xAxis.push(xAxisItem)
        }
        item.children.forEach((ele,index2) => {
           let data=[]
           options.series.forEach((sItem)=>{
            let name=ele.title+'('+ele.unit+")"
            if(sItem.name===name){
              data=sItem.data
              if(ele.data===undefined||ele.data===null||ele.data.length===0){
                ele.data=[]
                ele.data.push(...data)
              }
            }
          })
          if(data.length===0){
            data=ele.data
          }
          const serItem = {
            id:ele.dataSource+'-'+xIndex,
            name: ele.title+'('+ele.unit+")",
            yAxisIndex: index,
            type: 'line',
            symbolSize: 10,
            symbol: 'circle',
            //smooth: ele.lineStyle === 'smooth',
            smooth: false,
            showSymbol: false,
            hoverAnimation: false,
            step: ele.lineStyle === 'step', // 阶梯线
            showSymbol: false,
            itemStyle: {
             width: 1,
             color: ele.color,
             style: 'solid'
            },
            lineStyle:{
              opacity:ele.opacity===0?0:1
            },
            emphasis: {
             focus: 'series'
            },
            xAxisIndex:xAxis.length,
            z:20-index2,
            data: data
          }
          const xAxisItem = {
            gridIndex: index,
            min:function (value) {
              if(ele.spread==='1'){
                if(ele.minSpread==='a')
                {
                  return  Math.floor(Number(value.min) / 10) * 10
                }else{
                  return value.min
                }
              }else{
                return ele.minNum
              }
            },
            max:function (value) {
              if(ele.spread==='1'){
                if(ele.minSpread==='a')
                {
                  return  Math.ceil(Number(value.max) / 10) * 10
                }else{
                  return value.max
                }
              }else{
                return ele.maxNum
              }
            },
            type: ele.background,
            splitLine: { // 网格线
             show: index2===0?true:false,
             lineStyle:{
              color:'#aaa'
            }
            },
            minorSplitLine:{
              show:ele.background=='log'?true:false,
              lineStyle:{
                color:'#aaa'
              }
            },
            axisLabel: {
              formatter: function () {
                return ''
              }
            }
          }
          series.push(serItem)
          xAxis.push(xAxisItem)
          xIndex++
        })
        grid.push(gridItem)
         yAxis.push(yAxisItem)
      })
      //预警部分图表
      let warningLeft=preLeft
      this.warningList.forEach((item,index)=>{
        if(item.show){
          let gridItem = {
            id:item.id+'grid',
            left: warningLeft+'',
            backgroundColor: 'transparent',
            right: '0',
            bottom: '0',
            top: '0',
            width: item.width,
            containLabel: false,
            tooltip:{show:true}
          }
          warningLeft+=Number(item.width)
          let yAxisItem = {
            id:item.id+'y',
            gridIndex: grid.length,
            type: 'time',
            axisLine: { onZero: false, show: true ,
            lineStyle:{color:'#000'}
            },
            axisTick: { show:false },
            boundaryGap: false,
            min:this.time+' 08:00:00',
            max:this.time+' 18:00:00',
            //maxInterval: 3600 * 24 * 1000,
            //splitNumber:11,
            splitLine: { // 网格线
              show: true,
              lineStyle:{
              color:'#aaa'
            }
            },
            axisLabel: {
            formatter: ''
            },
            data: [],
            inverse: true
          }
          const xAxisItem = {
              id:item.id+'x',
              gridIndex: grid.length,
              min:0,
              max:3,
              type: 'value',
              splitLine: { // 网格线
               show: true,
               lineStyle:{
                color:'#aaa'
              }
              }
          }
          const warningSeries=[]
           options.series.forEach((sItem)=>{
              const sId=item.id+'warnings'
              if(sItem.id.indexOf(sId)>=0){
                sItem.yAxisIndex=yAxis.length
                sItem.xAxisIndex=xAxis.length
                warningSeries.push(sItem)
              }
           })
           if(warningSeries.length>0){
             series.push(...warningSeries)
           }
           else{
              let serItem={
                id:item.id+'warnings',
                yAxisIndex: yAxis.length,
                xAxisIndex:xAxis.length,
                type: 'scatter',
                symbolSize: 20,
                data:[]
              }
              if(item.id==='fzqk'){
                serItem={
                  id:item.id+'warnings',
                  yAxisIndex: yAxis.length,
                  xAxisIndex:xAxis.length,
                  type: 'scatter',
                  symbolSize: 0,
                  tooltip:{show:false},
                  data:[],
                  label:{
                    show:true,
                    position: 'right',
                    formatter: function (param) {
                      return param.data[2]
                    },
                    backgroundColor:'inherit',
                    offset:[35,0],
                    align: 'center',
                    width:70,
                    height:30,
                    fontSize:10
                  },
                  labelLine: {
                    show: true,
                    length2: 5,
                    lineStyle: {
                      color: '#bbb'
                    }
                  },
                  itemStyle:{
      　　　　　　　　normal:{
      　　　　　　　　},　　　　
    　　　　       }
                }
              }
              if(item.id==='zx'){
                 serItem={
                    id:item.id+'warnings',
                    yAxisIndex: yAxis.length,
                    xAxisIndex:xAxis.length,
                    showSymbol: false,
                    type: 'line',
                    data:[1.4,1.2,0.5,0.6,0.9,1,2,2.1,2.2,2.3,2.4,2.5,2.7]
                  }
                  const serItem2={
                    id:item.id+'warnings2',
                    yAxisIndex: yAxis.length,
                    xAxisIndex:xAxis.length,
                    showSymbol: false,
                    type: 'line',
                    data:[2.4,2.2,2.5,2.6,2.9,2,2,2.1,2.0,2.0,2.0,2.1,2.7]
                  }
                series.push(serItem2)
              }
              series.push(serItem)
           }
          if(item.id==='zx')
          {
            yAxisItem = {
                id:item.id+'y',
                gridIndex: grid.length,
                type: 'category',
                axisLine: { onZero: false, show: true ,
                lineStyle:{color:'#000'}
                },
                axisTick: { show:false },
                boundaryGap: false,
                splitLine: { // 网格线
                  show: true,
                  lineStyle:{
                  color:'#aaa'
                }
                },
                axisLabel: {
                formatter: ''
                },
                data: [
                  '00:00',
                  '02:00',
                  '04:00',
                  '06:00',
                  '08:00',
                  '10:00',
                  '12:00',
                  '14:00',
                  '16:00',
                  '18:00',
                  '20:00',
                  '22:00',
                  '24:00'
                ],
            }
          }
          grid.push(gridItem)
          yAxis.push(yAxisItem)
          xAxis.push(xAxisItem)
        }
      })
      options.grid = grid
      options.xAxis = xAxis
      options.series = series
      options.yAxis = yAxis
      mainChart.setOption(options, true)
    },
    hideChart(name,id,opacity){
      let newOPa=1
      if(opacity===0){
        newOPa=1
        const series={
          name:name,
          lineStyle:{
            opacity:1
          }
        }
        mainChart.setOption({series:[series]})
      }else{
        newOPa=0
        const series={
        name:name,
        lineStyle:{
          opacity:0
        }
      }
      mainChart.setOption({series:[series]})
      }
      this.chartList.forEach((item,index)=>{
        item.children.forEach((item2,index2)=>{
          if(item2.id===id){
            this.$set(this.chartList[index].children[index2],'opacity',newOPa)
          }
        })
      })
    },
    /* 拖拽之后的处理 */
    draggableEnd (e) {
      const oldIndex = this.chartList.findIndex(n => n.id === e.from.firstChild.dataset.id)
      const oldTrack=this.chartList[oldIndex]
      const newIndex=this.chartList.findIndex(n => n.id === e.to.firstChild.dataset.id)
      const newTrack=this.chartList[newIndex]
      const prms={
        oldTrack:oldTrack,
        newTrack:newTrack
      }
        const _this=this
        moveLine(prms).then((res)=>{
          if(res.success){
            getChartTreeList({id:this.selectedConfigureKey}).then((res)=>{
              if(res.success){
                setTimeout(() => {
                  _this.setOptions2(_this.chartList)
                }, 100);
                _this.chartList[oldIndex].children.forEach((item,i)=>{
                   item.key= res.result[0].children[oldIndex].children[i].key
                   item.id=res.result[0].children[oldIndex].children[i].id
                })
                _this.chartList[newIndex].children.forEach((item,i)=>{
                   item.key= res.result[0].children[newIndex].children[i].key
                   item.id=res.result[0].children[newIndex].children[i].id
                })
              }
            })
          } else {
            _this.$message.warning(res.message);
          }
      })
    },
    /* 伸缩条配置 */
    dataZoomSetOptions (chart) {
      const timeDate=new Date(this.time)
      const tomorDay=new Date(new Date(timeDate.setDate(timeDate.getDate()+1)).setHours(2,0,0))
      const tomoStr= getDateStr(tomorDay)
      const options = {
        animation:false,
         grid: {
          left: '0',
          right: '0',
          bottom: '-3%',
          top: '0',
          containLabel: true
        },
         dataZoom: [
          {
            type: 'inside',
            throttle:0,
            yAxisIndex: 0,
            filterMode: 'none',
            start: 0,
            end: 100
          },
          {
            type: 'slider',
            yAxisIndex: 0,
            show: true,
            filterMode: 'none',
            handleSize: '100%',
            handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
            handleStyle: {
              color: '#0B3C6F',
              shadowBlur: 3,
              shadowColor: 'rgba(0, 0, 0, 0.6)',
              shadowOffsetX: 2,
              shadowOffsetY: 2
            },
            right: '12px',
            width: '13px',
            bottom: '10px',
            top: '5px'
            // eslint-disable-next-line
          },
        ],
         xAxis: {
          type: 'value',
          axisLabel: {
            formatter: function () {
              return ''
            }
          }
        },
        yAxis: {
          type: 'time',
          axisLine: { onZero: false, show: false },
          axisTick: { show: false },
          boundaryGap: false,
          min:this.time+' 00:00:00',
          max:tomoStr,
          //maxInterval: 3600 * 24 * 1000,
          splitNumber:10,
          splitLine: { // 网格线
            show: false,
            lineStyle:{
                  color:'#aaa'
                }
          },
          axisLabel: {
            formatter: function () {
              return ''
            }
          },
          inverse: true
        },
        tooltip: {
          show: false
        }
      }
      chart.setOption(options)
    },
    chartResize () {
      if(mainChart===null){
        return
      }
     this.chart.resize()
     if(this.$refs.chartMain)
     {
      let warningWidth=0
      this.warningList.forEach((item,index)=>{
        if(item.show){
          warningWidth+=Number(item.width)
        }
      })
       const chartMainWidth=this.$refs.chartMain.offsetWidth-120-warningWidth
          let fixWidth=0
          let rate = this.chartList.length
          this.chartList.forEach((item,index)=>{
            if(item.fix==='1')
            {
              fixWidth+=Number(item.width)
              rate--
            }
          })
          let chartWidth = (chartMainWidth-fixWidth) / rate
          let preLeft=118
          const grid = []
          this.chartList.forEach((item,index)=>{
            const width=item.fix==='1'?item.width:chartWidth
            const gridItem = {
              left: preLeft+'',
              right: '0',
              bottom: '0',
              top: '0',
              width: width+'',
              containLabel: false
            }
            preLeft+=Number(width)
            grid.push(gridItem)
          })
          let warningLeft=preLeft
          this.warningList.forEach((item,index)=>{
            if(item.show){
              let gridItem = {
                id:item.id+'grid',
                left: warningLeft+''
              }
              warningLeft+=Number(item.width)
              grid.push(gridItem)
            }
          })
        mainChart.setOption({grid:grid})
     }
     mainChart.resize()
    },
    onTimeChange(date, dateString){
      this.time=dateString
      this.allRealTime=[]
      // const _this=this
      // this.getData().then((res)=>{
      //     _this.$nextTick(() => {
      //       setTimeout(() => {
      //         _this.initChart()
      //       }, 500)
      //     })
      // })
      this.initChart('time')
    },
    //预警多选框
    onWarningChange(e){
      const _this=this
      this.warningList.forEach((item,index)=>{
        if(item.id===e.target.value){
          if(item.id!='zx'){
            item.loading=true
          }
          this.$set(this.warningList[index],'show',e.target.checked)
          this.setOptions2(this.chartList)
           if(e.target.checked){
            if(item.id==='zjy'){
              this.getZjyData(this.jh)
              item.jh=this.jh
            }
            if(item.id==='fzqk'){
              if(fzqkIntervalId!=null){
                clearInterval(fzqkIntervalId)
                fzqkIntervalId=null
              }
              this.getFzqkData(this.jh)
              item.jh=this.jh
            }
            if(item.id==='gcyj')
            {
              if(gcyjIntervalId!=null){
                clearInterval(gcyjIntervalId)
                gcyjIntervalId=null
              }
              this.getGcyjData(this.jh)
            }
          }
        }
      })
    },
    /* 右键点击 */
    customClick (MouseEvent, pKey, key) {
      this.selectedPKey = pKey
      this.selectedKey = key
      this.menuVisible = false
      this.menuVisible = true
      document.addEventListener('click', this.foo)
      this.menuStyle.top = MouseEvent.clientY + 'px'
      this.menuStyle.left = MouseEvent.clientX + 'px'
      return false
    },
    foo () {
      this.menuVisible = false
      document.removeEventListener('click', this.foo)
    },
    /* 修改图表主题颜色 */
    chartThene(theme){
      const yitem={
        id:'y0',
        axisLine: { onZero: false, show: true ,
          lineStyle:{color:this.warnTheme=='dark'?'#fbdc61':'#000'}
        },
         axisTick: {
          lineStyle:{color:this.warnTheme=='dark'?'#469f92':'#000'}
          },
         axisLabel: {
            color:this.warnTheme=='dark'?'#b581f5':'#000'
          }
      }
      const op={yAxis:yitem}
      mainChart.setOption(op)
    },
    goZjy(){
      this.$emit('goZjy')
    },
    /* 修改复杂情况半径 */
    fzqkRadiusChange(value){
      if(fzqkIntervalId!=null){
        clearInterval(fzqkIntervalId)
        fzqkIntervalId=null
      }
      this.radius=value
      this.getFzqkData(this.jh)
      this.$store.commit('RadiusSet', value)
    }
  },
  computed: {
    ...mapState({
    lineConfigSelected: state => state.lineConfig.lineConfigSelected
    }),
     ...mapState({
    chartOptions: state => state.lineConfig.chartData
    }),
    ...mapState({
    configureKey: state => state.lineConfig.configureKey
    }),
     ...mapState({
    warnTheme: state => state.app.warnTheme
    }),
    ...mapState({
    templateId: state => state.lineConfig.templateId
    })
   },
  watch: {
    chartOptions(value) {
      if(value!=undefined){
         const type=value.split('_')[0]
         const _this=this
          if(type==='update'){
            if (this.configureKey === this.selectedConfigureKey) {
              this.getData().then((res)=>{
                _this.setOptions2(_this.chartList)
              })
            }
          }
          if(type==='init'){
             if(this.configureKey === this.selectedConfigureKey){
                _this.allRealTime=[]
                _this.getData().then((res)=>{
                _this.$nextTick(() => {
                  _this.initChart('option')
                })
              })
             }
          }
      }
   },
   warnTheme(val){
     this.chartThene(val)
   },
   jhProp(val){
     console.log(val)
     if(this.jh==val||!this.inited){return}
      // warnApi.queryWellCoordinate({ jh: val })
      //   .then(res => {
      //     if (res.result.exist) {
      //       this.config.coordinate = res.result.coor
      //     }
      //   }).catch(e => {
      //     this.message.info(e.message)
      //   })
      this.runRecu=false
      this.jh=val
      this.FzqkDeepth=[]
      this.gcyjAllTime=[]
      fzqkList=[]//清除复杂情况预警的数据
      const _this=this
      this.getTime().then(res=>{
      this.$nextTick(() => {
            setTimeout(() => {
              _this.initChart('jh')
            }, 500)
          })
      })
   },
   templateId(val){
     console.log(val+'---'+this.selectedConfigureKey)
     if(val==this.selectedConfigureKey||!this.inited){return}
     const _this=this
      if (timer2) {
        clearTimeout(timer2)
      }
      timer2= setTimeout(() => {
          _this.allRealTime=[]
          _this.runRecu=false
          _this.selectedConfigureKey = val
          _this.getData().then((res)=>{
            _this.$nextTick(() => {
              setTimeout(() => {
                _this.initChart('tem')
              }, 500)
            })
        })
      }, 1000)
   }
  }
})
</script>
<style lang="less" scoped>
@darkColor: transparent;
@foreColor:#b581f5;
@lightForeColor:#000;
.page {
  background: @darkColor;
  color: @lightForeColor;
  font-size: 5px;
  font-weight: 500;
  height: 100%;
}
.page-dark{
  background: @darkColor;
  color: @foreColor;
  font-size: 5px;
  font-weight: 500;
  height: 100%;
}
.backColor{
  background-color: @darkColor;
}
.foreColor{
  color: @lightForeColor;
}
.foreColor-dark{
  color: @foreColor;
}
.splitpanes /deep/ .splitpanes__pane
{
  background-color: @darkColor;
}
.ghostClass {
    background-color: #d3d7d4 !important;
    border: 1px solid #74787c;
}
.ant-spin-nested-loading /deep/ .ant-spin-container{
  height: 100%;
}
.chosenClass {
    background-color: #d3d7d4 !important;
    opacity: 1 !important;
    border: 1px solid #74787c;
}
.dragClass {
    background-color: #d3d7d4 !important;
    opacity: 1 !important;
    box-shadow: none !important;
    outline: none !important;
    background-image: none !important;
    border: 1px solid #74787c;
}
.splitpanes /deep/ .splitpanes__splitter{
  width: 98%;
  border-left: 1px solid;
  border-right: 1px solid;
  background-color: #0a447d;
  height: 3px;
}
.header-chart {
  background: @darkColor;
  width: 98%;
  display: flex;
  height: 100%;
}
.headerOne {
  min-height: 175px;
  width: 120px;
  border: 1px solid;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
}
.content {
  width: 100%;
  height: 100%;
  display: flex;
  background: @darkColor;
}
.header-content {
  flex: 1;
  border: 1px solid;
  margin-left: -1px;
}
.header-content-fix {
  border: 1px solid;
  margin-left: -1px;
}
.slick-list {
  background: @darkColor;
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}
.slick-item:nth-last-child(1) {
  border-bottom: 0px;
}
.slick-item {
  background: @darkColor;
  flex: 1;
  transform:scale(1);
  border-bottom: 1px solid;
}
.slick-item:hover{
  transform: scale(1.2);
  background: #d3d7d4;
  cursor: move;
}
.t-header {
  width: 100%;
  min-height: 37px;
  height: 100%;
  padding: 1px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.time-content {
  width: 120px;
  height: 16.7%;
  text-align: center;
  border-bottom: 1px solid @foreColor;
  position: relative;
}
.time-list {
  width: 120px;
  height: 100%;
  border-left: 1px solid @foreColor;
  border-right: 1px solid @foreColor;
  border-bottom: 1px solid @foreColor;
}
.time {
  position: absolute;
  bottom: 0px;
  width: 100%;
  text-align: center;
}
.chart {
  flex: 1;
  border-left: 1px solid @foreColor;
  border-right: 1px solid @foreColor;
  border-bottom: 1px solid @foreColor;
  display: flex;
}
.chart-item {
  flex: 1;
  border-right: 1px solid @foreColor;
}
.chart-item-fix {
  border-right: 1px solid @foreColor;
}
.chart-item:nth-last-child(1) {
  border-right: 0;
}
.warning-header{
  display: flex;
  flex-direction: column;
  justify-content: center;
  border-right: 1px solid;
  border-bottom:  1px solid;
  border-top: 1px solid;
}
</style>
