<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="18" :min-size="18">
                <div class="header-chart" style="font-size: 12px">
                  <template v-for="vi in chartList.length + 1">
                    <div v-if="vi === depthTrackIndex" :key="vi" 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>
                    </div>

                    <template v-else-if="chartList.length > 0">
                      <div
                        :key="vi"
                        :class="[
                          chartList[vi < depthTrackIndex ? vi - 1 : vi - 2].fix === '1'
                            ? 'header-content-fix'
                            : 'header-content',
                        ]"
                        :style="[
                          {
                            width: chartList[vi < depthTrackIndex ? vi - 1 : vi - 2].width + 'px',
                            borderLeft: vi === 1 || (depthTrackIndex === 1 && vi === 2) ? '2px solid' : '1px',
                          },
                        ]"
                      >
                        <draggable
                          class="slick-list"
                          group="site"
                          animation="300"
                          dragClass="dragClass"
                          ghostClass="ghostClass"
                          chosenClass="chosenClass"
                          v-model="chartList[vi < depthTrackIndex ? vi - 1 : vi - 2].children"
                          @end="draggableEnd"
                        >
                          <transition-group style="height: 100%; display: flex; flex-direction: column">
                            <div
                              class="slick-item"
                              v-for="(item2, index2) in chartList[vi < depthTrackIndex ? vi - 1 : vi - 2].children"
                              :index="index2"
                              :key="item2.id"
                              :data-id="chartList[vi < depthTrackIndex ? vi - 1 : vi - 2].id"
                              @contextmenu.prevent="
                                customClick($event, chartList[vi < depthTrackIndex ? vi - 1 : vi - 2].key, item2.key)
                              "
                            >
                              <div
                                class="t-header"
                                :style="{ color: item2.color, fontWeight: item2.lineFat ? 'bolder' : 'normal' }"
                                @click="lineClickAndFat(item2)"
                              >
                                <div style="display: flex">
                                  <span style="flex: 40px 0 0; text-align: left">
                                    {{ item2.minNum }}
                                  </span>
                                  <div style="flex: auto; text-align: center; height: 20px; overflow: hidden">
                                    <a
                                      v-if="item2.opacity === 0"
                                      @click="hideChart(item2.title + '(' + item2.unit + ')', item2.id, 0)"
                                    >
                                      <a-icon
                                        v-show="false"
                                        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
                                        v-show="false"
                                        type="eye"
                                        theme="filled"
                                        style="font-size: 15px; color: #009ad6"
                                      />
                                    </a>
                                    {{ item2.title + '(' + item2.unit + ')' }}
                                    {{ item2.val == undefined ? '[]' : item2.val }}
                                  </div>
                                  <span style="flex: 40px 0 0; text-align: right">{{ item2.maxNumExtended }} </span>
                                </div>
                                <a-divider :style="{ margin: '0px', background: item2.color, height: '2px' }" />
                              </div>
                            </div>
                          </transition-group>
                        </draggable>
                      </div>
                    </template>
                  </template>

                  <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>
                    <template v-if="item.id == 'gcyj'">
                      <a-button type="link" style="font-size: 12px" @click="refreshMD" :disabled="isGettingWarnMsg">
                        重新计算
                      </a-button>
                      <span>{{ `合计：${gcyjTotalNum}` }}</span>
                      <a-button-group v-if="show_PrevOrNextGcyj" style="display: block">
                        <a-button size="small" type="default" @click="gotoPrevOrNextGcyj(-1)">
                          <a-icon type="left" />
                        </a-button>
                        <a-button size="small" type="default" @click="gotoPrevOrNextGcyj(1)">
                          <a-icon type="right" />
                        </a-button>
                      </a-button-group>
                    </template>
                    <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>
                    <template v-if="item.id == 'csyj'">
                      <!--                      trigger='hover'-->
                      <a-tooltip placement="topLeft" trigger="hover">
                        <template slot="title">
                          <i v-if="mathTime == ''" class="el-icon-loading" />
                          <span>{{ ' ' + mathTime }}</span>
                        </template>
                        <a-button type="link" style="font-size: 12px; margin-top: 4px" @click="doClick"
                          >计算监听
                        </a-button>
                      </a-tooltip>
                      <a-tooltip placement="bottomRight" trigger="hover">
                        <template slot="title">
                          <a-tag color="orangered">钩载</a-tag>
                          <a-tag color="cornflowerblue">泵压</a-tag>
                          <a-tag color="mediumslateblue">扭矩</a-tag>
                          <a-tag color="yellowgreen" style="margin-right: 0px">池体积</a-tag>
                        </template>
                        <a-button type="link" style="font-size: 12px">预警图例</a-button>
                      </a-tooltip>
                      <a-spin :spinning="csyjBtnLoading">
                        <a-button type="link" style="font-size: 12px" @click="switchCsyj">
                          {{ openCsyj ? '点击关闭预警' : '点击开启预警' }}
                        </a-button>
                      </a-spin>
                      <span>{{ `合计：${newWarnNum}` }}</span>
                      <a-button-group v-show="show_PrevOrNextGcyj" style="display: block; margin-top: 8px">
                        <a-button size="small" type="default" @click="gotoPrevOrNextCsyj(-1)">
                          <a-icon type="left" />
                        </a-button>
                        <a-button size="small" type="default" @click="gotoPrevOrNextCsyj(1)">
                          <a-icon type="right" />
                        </a-button>
                      </a-button-group>
                    </template>
                  </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>
              </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"
      :cancelButtonProps="{ style: { display: 'none' } }"
      :okButtonProps="{ style: { display: 'none' } }"
      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" />
    <a-modal v-model="showWarningRes" title="异常报表" :footer="false" :mask="false" :width="800">
      <div v-for="(item, index) in warningRespList" :key="index" style="width: 100%">{{ item.warnMsg }}</div>
    </a-modal>
    <floating :yjAlarm="yjLastRecord" isNearBorder @click="handleFabClicked" :rightMargin="0" :bottomMargin="20">
      <div class="floatingView" style="text-align: center">
        <span style="font-size: 26px; line-height: 50px; color: red; font-weight: bold">
          {{ yjRefreshResult.length }}
        </span>
      </div>
    </floating>
    <FloatingNew
      :newWarnContent="newWarnContent"
      :yjAlarmNew="yjLastRecord"
      isNearBorder
      @click="handleFabClickedNew"
      :rightMargin="0"
      :bottomMargin="120"
    >
      <div class="floatingView" style="text-align: center">
        <span style="font-size: 26px; line-height: 50px; color: cornflowerblue; font-weight: bold">
          {{ newWarnNum }}
        </span>
      </div>
    </FloatingNew>
  </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, calculateTimeIntervalPoints } from '@/utils/util'
import indexChartCompareUtil from './indexChartCompareUtil'
import moment from 'moment'
import { scatterColors } from '@/views/tools/funcs/stratum'
import {
  getChartTreeList,
  deleteLine, moveLine,
  addByDirection,
  getDataByTime,
  getTemplateList,
  getZjyData,
  getFzqkData,
  getAnalyse,
  getAllDate,
  getRecalculateList, getMotionByTime
} from '@/api/api'
import warnApi from '@/api/warnApi'
import { getAction } from '@/api/manage'
import FzqkForm from './FzqkForm'
import _ from 'lodash'
import { EVENT_SET_CUR_DOT, EVENT_SET_RIGHT_tOP_DOT, EVENT_WELL_WARN, sendMsg } from '../../WsMgr.js'
import vueBusEvents from '@/utils/vueBusEvents'
import Floating from '@/components/Floating'
import FloatingNew from '@/components/FloatingNew'
import newWarnApi from '@/api/newWarnApi'
import { getChcheData } from './cacheData'
import { Notification } from 'element-ui'
// let mainChart = null
let timer = null
let timer2 = null
let intervalId = null
let fzqkIntervalId = null
let gcyjIntervalId = null
let csyjIntervalId = null
let zjyTimeInterval = 1000 * 60
let fzqkTimeInterval = 1000 * 60 * 30
let gcyjTimeInterval = 1000 * 60 * 30
let csyjTimeInterval = 1000 * 60 * 30
const gcyjSeriesId = 'gcyjwarnings'
const csyjSeriesId = 'csyjwarnings'
const ls_ignoreChartZoomTipKey = 'IGNORECHARTZOOMTIP'
const chartColor = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc']
const xAxisSplitNumber = 10
const depthTrackWidthPx = 119
const hoursRangeOnScreen = 1

function calZoomRangeBottom() {
  const secondsInRange = hoursRangeOnScreen * 60 * 60
  const secondsAllDay = (24 + 2) * 60 * 60
  return secondsInRange / secondsAllDay * 100
}

function calYAxisOffset(perTrackWidth, depthTrackIndex) {
  return -1 * (perTrackWidth * (depthTrackIndex - 1) + depthTrackWidthPx)
}

export default {
  name: 'IndexEChats2Compare',
  components: {
    Splitpanes,
    Pane,
    draggable,
    AddOptions,
    ChartOptions,
    AddTemplate,
    FzqkForm,
    Floating,
    FloatingNew
  },
  props: {
    jhProp: {
      type: [String, String],
      default: '车古271'
    },
    zjy: {
      type: Number,
      default: 0
    },
    serchTime: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      mathKey: null,
      mathTime: '',
      chart: null,
      gcyjChecked: false,
      menuVisible: false,
      addVisible: false,
      OpVisible: false,
      topHeight: 37,
      bottomHeight: 63,
      menuStyle: {
        position: 'absolute',
        top: '0',
        left: '0',
        zIndex: 1,
        borderRadius: '5px',
        border: '1px solid #eee'
      },
      spinning: true,
      selectedKey: undefined,
      selectedPKey: undefined,
      selectedConfigureKey: '1590687621484916737',
      newTrackKey: undefined,
      direction: 'r',
      yType: 'time',
      jh: this.jhProp.split(',')[0],
      time: '',
      time1: '',
      time2: '',
      mainChart: null,
      choose: true,
      newWarnNum: 0,
      newWarnContent: '',
      newWarnType: '',
      realTime: '',
      timeAllDate: [],

      chartList: [],
      allRealTime: [],
      warningList: [
        {
          name: '新参数预警',
          width: '120',
          show: true,
          id: 'csyj',
          jh: '',
          loading: false
        },
        {
          name: '邻井复杂',
          width: '80',
          show: false,
          id: 'fzqk',
          jh: '',
          loading: false
        },
        {
          name: '工程预警',
          width: '80',
          show: false,
          id: 'gcyj',
          jh: '',
          loading: false,
          data: []
        },
        {
          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: {},
      deepthList: [],
      radius: '5000',
      chartFinished: false,
      inited: false,
      hasData: true,
      showWarningRes: false,
      warningRespList: [],
      isGettingWarnMsg: false,
      lastMoment: null,
      daoDataListTime: null,
      // 20221008
      singleLineWidth: 1,
      allAjaxDataLoaded: false,
      lastAllGcyjAjaxData: [],
      gcyjFocusIndex: 0,
      csyjFocusIndex: 0,
      depthTrackIndex: 2,
      yjRefreshResult: [],
      yjLastRecord: undefined,
      yjLastRecordNew: undefined,
      csyjRefreshResult: [],
      csyjLastRecord: undefined,
      csyjLastRecordNew: undefined,
      yAxisLabels: [undefined, undefined, undefined],
      yAxisLabelDiff: undefined,
      lastTim: '',
      setEnd: true,
      onesetInterval: true,
      jsonTimeLastTime: '',
      historyData_boolen: false,
      is_back_boolean: true,
      time_coose_boolen: false,
      unlocking: true,
      isup: false,
      start_timing: '',
      dataRome: '',
      show_PrevOrNextGcyj: false,
      yjlasttime: '',
      lastAllCsyjAjaxData: [],
      tipLastTime: '',
      NotiKey: '999',
      workCondition: new Map(),
      openCsyj: true,
      csyjBtnLoading: false,
      loadChartStartDate: '',
      //折线图间隔点时间
      chartPreSpacerTime: '',
      loadPreSpaceTime: '',
      loadNextSpaceTime: '',
      chartNextSpacerTime: '',
      //上一个间隔点数据
      preCatchChartData: [],
      //下一个间隔点数据
      nextCatchChartData: [],
      nowStart: 0,
      preStart: 0,
      warnNowPreList: {},
      warnLogPreList: {}
    }
  },
  created() {
    this.$bus.on(vueBusEvents.closeGCYJ, this.closeGCYJ)
    this.$bus.on(EVENT_SET_CUR_DOT, this.setCurrentDot)
    this.$bus.on(EVENT_WELL_WARN, this.setWebsocketWarn)
    this.$bus.on(vueBusEvents.chartTimeChanged, this.onTimeChange)
    this.$bus.on(vueBusEvents.warnTrackAdd, this.onWarningChange)
    this.$bus.on(vueBusEvents.warnTrackRemove, this.onWarningChange)
    this.$bus.on(vueBusEvents.chartDatazoomTimeChanged, this.onChartDatazoomTimeRangeChange) // test, can remove
    this.$bus.on(EVENT_SET_RIGHT_tOP_DOT, this.setCurrentDot2)

    // if(parse(window.location.href))
    // this.jh = parse()
  },
  mounted() {
    //firefox
    if (this.start_timing) {
      clearInterval(this.start_timing)
      this.start_timing = null
    }
    this.onesetInterval = true
    this.initAll()
    this.allAjaxDataLoaded2('csyj')
    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 = 120
      const pageHeight = this.$refs.page.offsetHeight
      this.topHeight = headerHeight / pageHeight * 100
      this.bottomHeight = 100 - this.topHeight
    })
    /*if (!this.$ls.get(ls_ignoreChartZoomTipKey)) {
      this.$notification['info']({
        message: '提示',
        description: function(h) {
          return h('div', {}, [
            h('div', '图表滚动： 鼠标滚轮'),
            h('div', '图表缩放： shift + 鼠标滚轮'),
            h('a-checkbox',
              { on: { change: (e) => _this.$ls.set(ls_ignoreChartZoomTipKey, true) } },
              '不再提示')
          ])
        }
      })
    }*/

  },
  beforeDestroy() {
    this.$bus.off(vueBusEvents.closeGCYJ, this.closeGCYJ)
    this.$bus.off(EVENT_SET_CUR_DOT, this.setCurrentDot)
    this.$bus.off(EVENT_WELL_WARN, this.setWebsocketWarn)
    this.$bus.off(vueBusEvents.chartTimeChanged, this.onTimeChange)
    this.$bus.off(vueBusEvents.warnTrackAdd, this.onWarningChange)
    this.$bus.off(vueBusEvents.warnTrackRemove, this.onWarningChange)
    this.$bus.off(vueBusEvents.chartDatazoomTimeChanged, this.onChartDatazoomTimeRangeChange) // test, can remove
    this.$bus.off(EVENT_SET_RIGHT_tOP_DOT, this.setCurrentDot2)

    this.historyData_boolen = false
    this.is_back_boolean = true
    this.time_coose_boolen = false
    this.runRecu = false
    this.unlocking = true
    if (intervalId != null) {
      clearInterval(intervalId)
      intervalId = null
    }
    if (fzqkIntervalId != null) {
      clearInterval(fzqkIntervalId)
      fzqkIntervalId = null
    }
    if (gcyjIntervalId != null) {
      clearInterval(gcyjIntervalId)
      gcyjIntervalId = null
    }
    if (csyjIntervalId != null) {
      clearInterval(csyjIntervalId)
      csyjIntervalId = null
    }
    if (this.mainChart != null) {
      this.mainChart.clear()
      this.mainChart.dispose()
      this.mainChart = null
    }
  },
  methods: {
    getMathTime() {
      let _this = this
      let params = {
        'jh': _this.jh,
        'pageNo': 1,
        'pageSize': 10
      }
      getRecalculateList(params).then(res => {
      })
    },
    calZoomRangeStart(timeStr) {
      const secondsAtTime = moment(timeStr).diff(moment(timeStr).startOf('day'), 'seconds')
      const secondsAllDay = (24 + 2) * 60 * 60
      return secondsAtTime / secondsAllDay * 100
      /*  const star = this.jsonTimeLastTime.substring(0,10)+" 00:00:00"
        const secondsAtTime = moment(timeStr).diff(moment(star), 'seconds')
        const secondsAllDay = (24 + 2) * 60 * 60
        return secondsAtTime / secondsAllDay * 100*/
    },
    async initAll() {
      this.historyData_boolen = false
      this.is_back_boolean = true
      this.time_coose_boolen = false
      this.unlocking = true
      if (this.templateId != undefined) {
        this.selectedConfigureKey = this.templateId
      } else {
        await this.loadTemplateListData()
      }
      await this.getData()
      await this.getTime(this.jh)

      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 === '综合v2.0')
          if (exist) {
            this.selectedConfigureKey = exist.id
          } else {
            this.selectedConfigureKey = res.result[0].id
          }
        } else {
          this.$message.error('获取可用模板数据时出错')
        }

      })
    },
    /* 获取最新时间 */
    async getTime(jh) {
      const params = { jh: jh }
      await getAllDate(params).then((res) => {
        if (res.success) {
          this.hasData = true
          this.time = res.result[0]
          if (res.result[res.result.length - 1]) {
            let jsonTime = JSON.parse(res.result[res.result.length - 1])
            //   this.jsonTimeLastTime = jsonTime[0].time.substring(0, 19)
            this.realTime = jsonTime[0].time.substring(0, 19)
            this.is_back_boolean = true
            res.result.splice(res.result.length - 1, 1)
          }
          if (this.serchTime) {
            this.time = this.serchTime
          }
          this.timeAllDate = [...res.result]
        } else {
          this.hasData = false
          this.time = ''
          this.$message.error(res.message)
          this.spinning = false
        }
      })
    },
    /* 不能被选中的时间 */
    disabledDate(current) {
      let result = true
      result = !this.timeAllDate.some(son => {
        return moment(current).isSame(son, 'day')
      })
      return result
    },


    /**
     * 获取录井数据
     */
    getLjData() { },
    async loadChartData() {
      /* this.spinning = true*/
      // this.openNotify()
      var _this = this;
      this.time1 = this.time.substring(0, 10) + ' 00:00:00'
      this.time2 = this.time.substring(0, 10) + ' 23:59:59'
      this.show_PrevOrNextGcyj = false
      var today = new Date()
      //判断数据加载日期是否为当天日期
      var dateCompare = indexChartCompareUtil.dateCompare(today, this.time)
      this.deepthList = []
      var todayDate = ''
      var startTime = ''
      var endTime = ''
      if (dateCompare) {
        todayDate = new Date(today)
      } else {
        todayDate = new Date(this.time + ' 23:59:59')
      }
      var startDate = calculateTimeIntervalPoints(todayDate, 4)
      startTime = getDateStr(startDate)
      endTime = getDateStr(todayDate)
      this.chartPreSpacerTime = startTime
      this.loadChartDataNew(startTime, endTime)
      //延迟获取上一个时间间隔点的数据
      setTimeout(async function () {
        //延迟获取当前点预警信息
        _this.getWanrCount(_this.jh, _this.time1, _this.time2)
        //获取上一个时间时间间隔点数据
        _this.loadPerData(startTime)

      }, 2000)
      //if (!this.historyData_boolen) {
      // this.time1 = this.getCutData(this.jsonTimeLastTime,2)
      // this.time2 = this.jsonTimeLastTime
      //this.getDataByTime(this.jh, this.selectedConfigureKey, this.getCutData(this.realTime, 2), this.realTime)
      // this.time = this.jsonTimeLastTime.substring(0, 10)
      // this.setChartTimeLoaded(this.time, '')
      //}
      //this.getHistoryDataByTIME(this.time)
    },
    /**
    * 获取当前时间点到上一个时间间隔点的数据
    */
    loadChartDataNew(startTime, endTime) {
      var _this = this
      this.historyData_boolen = false
      this.loadChartStartDate = startTime
      console.log('endTime', startTime + '/n' + endTime)
      let promises = []
      promises.push(_this.m_getDataByTime(this.jh, this.selectedConfigureKey, startTime, endTime))
      Promise.all(promises).then(async (results) => {
        const option = _this.mainChart.getOption()
        var endTimeNumber = indexChartCompareUtil.timeToDecimalTime(endTime)
        var endIndex = indexChartCompareUtil.getTimeToIndex(endTimeNumber)
        option.dataZoom[0].disabled = false
        option.dataZoom[0].start = endIndex - 3.5
        option.dataZoom[0].end = endIndex
        _this.mainChart.setOption(option)
        _this.unlocking = true
        _this.setChartTimeLoaded(startTime, endTime)
        _this.spinning = false
        setTimeout(async function () {
          //获取预警信息
          var warnLog = await _this.getWarnLog(_this.jh, startTime, endTime)
          this.warnNowPreList = warnLog
          _this.setNewWarnLogInfo(warnLog)
          _this.setWarnLogOption(warnLog)
          _this.unlocking = true
          _this.closeNotify()
        }, 2000)
      }).catch((error) => {
        console.error(error)
      })

    },
    /**
     * 获取上一个间隔时间点数据
     */
    async loadPerData(time) {
      var startDate = indexChartCompareUtil.timeSubtract(time, 4)
      var startDateStr = getDateStr(startDate)
      var endDateStr = time
      var params = {
        jh: this.jh,
        time1: startDateStr,
        time2: endDateStr,
        templateId: this.selectedConfigureKey
      }
      var res = await getDataByTime(params)
      this.preCatchChartData = res.result
      this.loadPreSpaceTime = startDateStr
      this.warnLogPreList = await this.getWarnLog(this.jh, startDateStr, endDateStr)
      // this.
      //this.setChartData(res.result)
    },
    async loadNextData(time) {
      var endDate = indexChartCompareUtil.timeSubtract(time, -4)
      var startDateStr = time
      var endDateStr = getDateStr(endDate)
      var params = {
        jh: this.jh,
        time1: startDateStr,
        time2: endDateStr,
        templateId: this.selectedConfigureKey
      }
      var res = await getDataByTime(params)
      console.log('下一个4小时前的数据', res)
      this.preCatchChartData = res.result
      //this.setChartData(res.result)
    },
    /**
     * 折线图插入数据
     */
    setChartData(dataList) {
      var _this = this
      var op = _this.mainChart.getOption()
      let resultList = []
      const updateRealTimeData = (realTimeNum, childItem) => {
        if (realTimeNum === undefined) {
          realTimeNum = ''
        }
        this.allRealTime.forEach((realTimeItem) => {
          if (realTimeItem.id === childItem.id) {
            realTimeItem.num = `[${realTimeNum}]`
          }
        })
      }
      resultList.push(...this.filterNegative(dataList))
      if (resultList[0].templateId === this.selectedConfigureKey) {
        const listLength = resultList.length - 1
        resultList.forEach((itemRes, index1) => {
          this.setWorkCondition(itemRes)
          this.chartList.forEach((chartItem, index2) => {
            chartItem.children.forEach((childItem, index3) => {
              const value = itemRes[childItem.dataSource.toLowerCase()]
              if (value !== '') {
                if (!childItem.data) {
                  childItem.data = []
                }
                childItem.data.push(value)
                if (listLength === index1) {
                  updateRealTimeData(value, childItem)
                  this.$set(this.chartList[index2].children[index3], 'val', `[${value}]`)
                }
              }
            })
          })
          op.series.forEach((item) => {
            if (!item.id.includes('warnings')) {
              const dataItem = []
              const dataSource = item.id.split('-')[0]
              const pointValue = itemRes[dataSource.toLowerCase()]
              if (pointValue !== '' || pointValue === 0) {
                dataItem.push(pointValue, itemRes.time)
                item.data.push(dataItem)
              }
            }
          })
        })
      }
      this.mainChart.setOption(op)
    },
    getWanrCount(jh, startTime, endTime) {
      var params = {
        jh: jh,
        starTime: startTime,
        endTime: endTime
      }
      newWarnApi.getWarnCount(params).then(res => {
        this.newWarnNum = res.result.warnCount
      })
    },
    async getWarnLog(jh, startTime, endTime) {
      let query = {
        jh: jh,
        startTime: startTime,
        endTime: endTime
      }
      let wanrLog = await newWarnApi.getGzWarning(query)
      return wanrLog.result
    },
    /**
     * 设置最新报警信息
     */
    setNewWarnLogInfo(wanrLog) {
      try {
        //  this.newWarnNum = hisRes2.result.count
        if (wanrLog.count > 0) {
          this.newWarnContent = wanrLog.zxdata.jh + '在' + wanrLog.zxdata.warnTime + '发生' + wanrLog.zxdata.warnType
          this.newWarnType = wanrLog.zxdata.warnType
        } else {
          this.newWarnContent = '暂无报警数据'
          this.newWarnType = '起下钻预警'
        }
      } catch (e) {
        console.warn(e)
      } finally {
      }
    },
    /**
     * 插入预警数据
     */
    setWarnLogOption(warnLogList) {
      this.lastAllCsyjAjaxData = []
      const dataKeys = ['gzdata', 'bydata', 'njdata', 'jlData']
      var warnlogLists = this.warnLogArryConcat(warnLogList)
      dataKeys.forEach(key => {
        if (warnlogLists[key] && warnlogLists[key].length > 0) {
          this.initCSYJChart2(warnlogLists[key])
        }
      })
    },
    warnLogArryConcat(warnLogList) {
      var _this = this
      var isEmpty = indexChartCompareUtil.isEmptyObject(_this.warnNowPreList)
      console.log()
      if (!isEmpty) {
        Object.keys(_this.warnNowPreList).forEach(key => {
          if (key != 'zxdata' && key != 'count') {
            console.log('key：' + key, _this.warnNowPreList[key])
            console.log('warnLogList[key]', warnLogList[key])
            _this.warnNowPreList[key] = _this.warnNowPreList[key].concat(warnLogList[key])
            console.log('_this.warnNowPreList[key]', _this.warnNowPreList[key])
          }
        })
      } else {
        this.warnNowPreList = warnLogList
      }
      console.log('this.warnNowPreList', this.warnNowPreList)
      var res = this.warnNowPreList
      return res
    },
    setChartTimeLoaded(time1, time2) {
      this.$bus.emit(vueBusEvents.chartTimeLoaded, { time: [time1, time2], timeAllDate: this.timeAllDate })
    },
    getHistoryDataByTIME(lastTime) {
      this.spinning = false
      let time1 = this.time1
      let last = this.time2
      let promises = []
      let startTime = new Date(time1)
      let endTime = new Date(last)
      let timeDiff = endTime.getTime() - startTime.getTime()
      let interval = timeDiff / 6
      for (let i = 0; i <= 6; i++) {
        let startTimeInterval = new Date(startTime.getTime() + i * interval)
        let endTimeInterval = new Date(startTimeInterval.getTime() + interval)
        let time1 = getDateStr(startTimeInterval)
        let time2 = getDateStr(endTimeInterval)
        promises.push(this.m_getDataByTime(this.jh, this.selectedConfigureKey, time1, time2))
      }
      Promise.all(promises).then(async (results) => {
        this.getWarningData()
      }).catch((error) => {
        console.error(error)
      })
    },
    getPlusDate(date, number) {
      return getDateStr(new Date(new Date(date).getTime() + 1000 * 60 * 60 * number))
    },
    getCutData(date, number) {
      return getDateStr(new Date(new Date(date).getTime() - 1000 * 60 * 60 * number))
    },
    getWarningData() {
      if (intervalId != null) {
        clearInterval(intervalId)
        intervalId = null
      }
      if (fzqkIntervalId != null) {
        clearInterval(fzqkIntervalId)
        fzqkIntervalId = null
      }
      if (gcyjIntervalId != null) {
        clearInterval(gcyjIntervalId)
        gcyjIntervalId = null
      }
      if (csyjIntervalId != null) {
        clearInterval(csyjIntervalId)
        csyjIntervalId = null
      }
      const _this = this
      const promises = []
      let looke = true
      this.warningList.forEach((item) => {
        if (item.show) {
          switch (item.id) {
            case 'zjy':
              looke = true
              // promises.push(_this.getZjyData(this.jh))
              break
            case 'fzqk':
              looke = true
              // promises.push(_this.getFzqkData(this.jh))
              break
            case 'gcyj':
              looke = true
              //promises.push(_this.getGcyjData(this.jh))
              break
            case 'csyj':
              looke = false
              // promises.push(_this.getCsyjData(this.jh))
              break
            default:
              break
          }
        }
      })
      if (looke) {
        Promise.all(promises).then(() => {
          setTimeout(function () {
            this.unlocking = true
            this.closeNotify()
          }, 2000)

        })
      }
      const option = this.mainChart.getOption()
      option.dataZoom[0].disabled = false
      this.mainChart.setOption(option)
      this.unlocking = true
      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 = false
      }
      this.warningList[2].loading = true
      const params = { jh: jh, time: this.time }
      /* const params = { jh: jh,   startTime: this.is_back_boolean ? this.getCutData(this.jsonTimeLastTime,24): this.jsonTimeLastTime,
         endTime: this.is_back_boolean ? this.jsonTimeLastTime : this.getPlusDate(this.jsonTimeLastTime,24) }*/
      try {
        getZjyData(params).then((res) => {
          if (res.success && res.result.length > 0 && res.result[0].jh === this.jh) {
            let op = this.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 }
            this.mainChart.setOption(options)
          }
          this.setDownLoading('zjy')
        })
      } catch (error) {
        this.setDownLoading('zjy')
      }
    },
    /* 获取复杂情况数据 */
    async getFzqkData(jh) {
      let op1 = this.mainChart.getOption()
      let deleteData = {}
      op1.series.forEach((item) => {
        if (item.id.indexOf('fzqkwarnings') >= 0) {
          deleteData.id = item.id
          deleteData.data = []
        }
      })
      this.mainChart.setOption({ series: deleteData })
      if (!this.spinning) {
        this.spinning = false
      }
      this.warningList[0].loading = true
      const caseLevels = ['一般', '严重', '非常严重']
      try {
        await warnApi.queryCaseInDistance({ jh: jh, distance: this.radius }).then(res => {
          const data = res.result.data
          let op = this.mainChart.getOption()
          let SeriesList = []
          let fzqkSeriesMap1 = {}
          op.series.forEach(opItem1 => {
            if (opItem1.id == 'fzqkwarnings') {
              fzqkSeriesMap1 = { ...opItem1 }
            }
          })
          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 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 {
                  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 }
          this.mainChart.setOption(options)
        })

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

    },
    /* 获取工程预警数据 */
    async getGcyjData(jh) {
      if (!this.spinning) {
        this.spinning = false
      }
      this.warningList[1].loading = true
      try {
        //    let hisRes = await warnApi.getGcyjList({ jh: jh, time: this.time, lastOne: 'N' })

        let hisRes = await warnApi.getGcyjList({
          jh: jh, startTime: this.is_back_boolean ? this.yjlasttime.substring(0, 10) + ' 00:00:00' : this.yjlasttime,
          endTime: this.is_back_boolean ? this.yjlasttime : this.getPlusDate(this.yjlasttime, 24), lastOne: 'N'
        })
        /*     let hisRes = await warnApi.getGcyjList({ jh: jh,   startTime: this.time1,
               endTime: this.time2, lastOne: 'N' })*/
        if (hisRes.success) {
          if (hisRes.result.length > 0 && jh === this.jh) {
            this.initGCYJChart2(hisRes.result)
          } else if (hisRes.result.length === 0) {
            this.lastAllGcyjAjaxData = []
          }
        } else {
          await getAnalyse({
            'jh': jh,
            'startTime': this.time
          }).then((res) => {
            if (res.success && jh === this.jh) {
              if (res.result.length > 0) {
                this.initGCYJChart2(res.result)
              } else {
                this.lastAllGcyjAjaxData = []
              }
            }
          })
        }
        this.setDownLoading('gcyj')
      } catch (error) {
        this.setDownLoading('gcyj')
      }


    },
    /* 获取参数预警数据 */
    async getCsyjData(jh) {
      if (!this.spinning) {
        this.spinning = false
      }

      this.warningList[1].loading = true

      try {

        let query = {
          jh: jh,
          startTime: this.time1,
          endTime: this.time2
        }
        /**
         * 当前方法返回报警数据总数，以及按照报警类别返回固定的两个类别数据:gzdata:起下钻预警数据 bydata:泵压变化预警数据
         */
        this.csyjBtnLoading = true
        let hisRes2 = await newWarnApi.getGzWarning(query)
        this.csyjBtnLoading = false
        console.log('compare compare compare')
        try {
          //  this.newWarnNum = hisRes2.result.count
          if (hisRes2.result.count > 0) {
            this.newWarnContent = hisRes2.result.zxdata.jh + '在' + hisRes2.result.zxdata.warnTime + '发生' + hisRes2.result.zxdata.warnType
            this.newWarnType = hisRes2.result.zxdata.warnType
          } else {
            this.newWarnContent = '暂无报警数据'
            this.newWarnType = '起下钻预警'
          }
        } catch (e) {
          console.warn(e)
        } finally {
        }


        if (hisRes2.success && jh === this.jh) {
          this.lastAllCsyjAjaxData = []
          const dataKeys = ['gzdata', 'bydata', 'njdata', 'jlData']

          dataKeys.forEach(key => {
            if (hisRes2.result[key] && hisRes2.result[key].length > 0) {
              this.initCSYJChart2(hisRes2.result[key])
            }
          })
        }
        const op = this.mainChart.getOption()
        this.show_PrevOrNextGcyj = true
        this.spinning = false
        this.unlocking = true
        this.setDownLoading('csyj')
      } catch (error) {
        this.setDownLoading('csyj')
        console.warn("setDownLoading")

        console.warn(error)
      }
    },
    // 2022 obsoluted method
    initGcyjChart(res, time) {
      let num = 0
      const sortList = _.reverse(res.result)
      let name = ''
      let warningMsg = ''
      // let lineColor = '#ee6666'  #FF0000
      let lineColor = '#FF0000'
      sortList.forEach((resItem, index) => {
        // todo 改色 取第一个的颜色
        if (index === 0 && !(resItem._curveColor === undefined || resItem._curveColor === null)) {
          lineColor = resItem._curveColor
        }
        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 = this.mainChart.getOption()
      let gcyjSeriesMap = {}
      op.series.forEach((item) => {
        if (item.id === gcyjSeriesId) {
          gcyjSeriesMap = { ...item }
        }
      })
      const dataItem = [0.5, time]
      let dataConf = {}
      dataConf.value = [...dataItem]
      dataConf.itemStyle = {
        // color: chartColor[num]
        color: lineColor

      }
      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 }
      this.mainChart.setOption(options)

    },
    initGCYJChart2(list) {
      this.warningList[1].data = list
      this.gcyjFocusIndex = 0
      list.map((k, i) => {
        i === 0 ? (this.lastAllGcyjAjaxData = k.children) : (this.lastAllGcyjAjaxData = [...this.lastAllGcyjAjaxData, ...k.children])
      })
      this.lastAllGcyjAjaxData = this.lastAllGcyjAjaxData // 202210
      this.yjRefreshResult = []
      list.forEach(k => {
        this.yjRefreshResult = _.concat(this.yjRefreshResult, k.children.map(c => {
          return {
            BJNR: c.description.replace(/\<br\/\>/g, ''),
            CATOGARY: k.groupName,
            JH: this.jh,
            WARN_TIME: c.endDate,
            SOURCE: '工程预警'
          }
        }))
      })
      this.yjRefreshResult = _.orderBy(this.yjRefreshResult, ['WARN_TIME'], ['desc'])
      this.yjLastRecord = this.yjRefreshResult[0]
      let op = this.mainChart.getOption()
      let gcyjSeriesMap = {}
      op.series.forEach((item) => {
        if (item.id === gcyjSeriesId) {
          gcyjSeriesMap = { ...item }
        }
      })

      gcyjSeriesMap.type = 'lines'
      gcyjSeriesMap.coordinateSystem = 'cartesian2d'
      gcyjSeriesMap.polyline = true
      // gcyjSeriesMap.colorBy = 'data'
      gcyjSeriesMap.lineStyle = {
        width: 6,
        color: (i) => {
          return i.data.itemStyle.color
        }
      }

      // 2022 fix
      function limitLineHeightMin2Px(startDate, endDate) {

        const { start, end } = op.dataZoom[0]
        const fullSecond = (24 + 2) * 60 * 60
        const chartHeightPx = this.mainChart.getHeight()
        const secondsInSinglePx = fullSecond * (end - start) / 100 / chartHeightPx
        const limitMinEnd = moment(startDate).add(secondsInSinglePx * 2, 'seconds').format('YYYY-MM-DD HH:mm:ss')

        return endDate > limitMinEnd ? endDate : limitMinEnd
      }

      list.forEach((type, i) => {
        let typeColor = type.modelColor
        let curveIndex = i + 1
        type.children.forEach((item) => {
          gcyjSeriesMap.data.push({
            // symbol: 'triangle',
            // symbolSize: 20,
            coords: [
              [curveIndex, item.startDate],
              [curveIndex, limitLineHeightMin2Px(item.endDate)]
            ],
            itemStyle: { color: typeColor },
            tooltip: {
              trigger: 'item',
              triggerOn: 'mousemove',
              formatter: function (params) {
                return item.description
              }
            }
          })
        })
      })
      const options = { series: gcyjSeriesMap }
      this.mainChart.setOption(options)
    },

    initCSYJChart2(list) {
      console.log('list', list)
      this.warningList[0].data = list
      this.warningList[0].show = true
      let _this = this
      this.csyjFocusIndex = 0
      this.lastAllCsyjAjaxData = this.lastAllCsyjAjaxData.concat(list)
      this.csyjRefreshResult = _.flatMap(list, k => k)
      this.csyjRefreshResult = _.orderBy(this.csyjRefreshResult, ['warnTime'], ['desc'])
      this.csyjLastRecord = this.csyjRefreshResult[0]
      let op = this.mainChart.getOption()
      let csyjSeriesMap = {}
      op.series.forEach((item) => {
        if (item.id === csyjSeriesId) {
          csyjSeriesMap = { ...item }
        }
      })
      csyjSeriesMap.type = 'lines'
      csyjSeriesMap.coordinateSystem = 'cartesian2d'
      csyjSeriesMap.polyline = true
      let typeColor = 'red'

      // 2022 fix
      function limitLineHeightMin2Px(startDate, endDate) {
        const { start, end } = op.dataZoom[0]
        const fullSecond = (24 + 2) * 60 * 60
        const chartHeightPx = _this.mainChart.getHeight()
        const secondsInSinglePx = fullSecond * (end - start) / 100 / chartHeightPx
        const limitMinEnd = moment(startDate).add(secondsInSinglePx * 2, 'seconds').format('YYYY-MM-DD HH:mm:ss')
        return endDate > limitMinEnd ? endDate : limitMinEnd
      }

      let that = this

      function getLabelAndConfig(item) {
        let ms = ''
        let warnName = ''
        let bjgk = item.motion

        let warnDesStr = item.warnDes;
        // that.insertBreaks()
        // if (item.warnCondition === 'DrillDown') {
        //   bjgk = '下钻'
        //   ms = '下钻遇阻'
        // } else if (item.warnCondition === 'Trip') {
        //   bjgk = '起钻'
        //   ms = '起钻遇卡'
        // }
        // if (item.wholeCondition === 'Drilling') {
        //   ms = '钻进预警'
        //   bjgk = '钻进'
        // } else if (item.wholeCondition === 'Circulate') {
        //   ms = '循环预警'
        //   bjgk = '循环'
        // }

        let desObj = {
          toolsStartTime: '',
          toolsEndTime: '',
          toolsMaxWoh: '',
          toolsMinWoh: '',
          toolsWoh: ''
        }
        if (item.workingConditionType === '起钻-活动钻具' || item.workingConditionType === '下钻-活动钻具') {
          //todo  item.workingConditionType ===起钻-活动钻具' || item.workingConditionType === '下钻-活动钻具'  warnTime= mobilDrillingToolsEndTime

          item.warnTime = item.mobilDrillingToolsEndTime

          desObj.toolsStartTime = item.mobilDrillingToolsStartTime
          desObj.toolsEndTime = item.mobilDrillingToolsEndTime
          desObj.toolsMaxWoh = item.mobilDrillingToolsMaxWoh
          desObj.toolsMinWoh = item.mobilDrillingToolsMinWoh
          desObj.toolsWoh = item.mobilDrillingToolsWoh
          //  console.log("desObj====", desObj)
        } else if (item.workingConditionType === '起钻' || item.workingConditionType === '下钻') {
          desObj.toolsStartTime = item.referenceStartTime
          desObj.toolsEndTime = item.referenceEndTime
          desObj.toolsMaxWoh = item.referenceMaxWoh
          desObj.toolsMinWoh = item.referenceMinWoh
          desObj.toolsWoh = item.referenceWoh
        }


        const warnTypeConfig = {
          '钩载变化异常': {
            index: 1,
            typeColor: 'orangered',
            curveIndex: 0.27,
            lname: '大钩负荷(kN)',
            lable: `[${item.jh} ${item.warnType}]<br/>时间：${item.warnTime}<br/>报警钩载(KN)：${item.warnWoh}<br/>报警工况：${item.workingConditionType}<br/>上一柱时间区间：${desObj.toolsStartTime} -> ${desObj.toolsEndTime}<br/>参考柱钩载最小值：${desObj.toolsMinWoh}<br/>参考柱钩载最大值：${desObj.toolsMaxWoh}<br/>上一柱钩载极值(KN)：${desObj.toolsWoh}<br/>异常描述：${warnDesStr}`
          },
          '泵压变化异常': {
            index: 2,
            typeColor: 'cornflowerblue',
            curveIndex: 0.77,
            lname: '立管压力(MPa)',
            lable: `[${item.jh} ${item.warnType}]<br/>报警点信息: 时间：${item.warnTime}; 报警立压(MPa)：${item.warnSpp}<br/>工况：${item.workingCondition}<br/>参考值信息：参考值时间：${item.referenceTime}; 参考值立压(MPa)：${item.referenceSpp}<br/>立管压力差值(MPa)：${item.sppSub}<br/>立管压力阈值(MPa)：${item.sppWarnValue}<br/>异常描述：${warnDesStr}`
          },
          '扭矩变化异常': {
            index: 3,
            typeColor: 'mediumslateblue',
            curveIndex: 1.27,
            lname: '扭矩(kN.m)',
            lable: `[${item.jh} ${item.warnType}]<br/>报警点信息: 时间：${item.warnTime}; <br/>预警扭矩值(kN.m)：${item.warnTorque}; 预警扭矩波动值(kN.m)：${item.warnFluctuatedValue} 预警扭均值(kN.m)：${item.warnMeanValue}<br/>报警工况：${item.workingCondition}-${item.motion}<br/>预警时间区间: ${item.warnStartTime}——${item.warnEndTime}<br/>参考值信息：波动值(kN.m)： ${item.referenceFluctuatedValue}；均值(kN.m)： ${item.referenceMeanValue}<br/>异常描述：${warnDesStr}`
          },
          '总池体积变化异常': {
            index: 4,
            typeColor: 'yellowgreen',
            curveIndex: 1.77,
            lname: '总池体积(m³)',
            lable: `[${item.jh} ${item.totalWarnType}]<br/>报警点信息: 时间：${item.warnTime}; 报警总池体积(m³)：${item.warnPittotal}<br/>工况：${item.workingCondition}-${item.motion}<br/>参考值信息: 参考值起点时间：${item.referenceStartTime}; 参考值结束时间：${item.referenceEndTime}; 参考值(m³): ${item.referenceValue}<br/>异常描述：${warnDesStr}`
          }
        }

        return warnTypeConfig[item.warnType] || {}
      }

      let data1 = []

      let lsymbol = 'image://data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAX1JREFUOE+lk71KQ0EQhc9MBItcf7C2uIJNboJ/jYKCKXwAfQN9AsUn8BF8A62ttLZRUAsb/3ZDCos0KcRGIblYzZENuZLIvSI65e7Md87szgj+GVJUH8fxZBRFR+G+0+nstFqtt7zcQkCtVjsAUDezERF59t5v/xoQ1Mvl8iPJcVWdMLO2ma01m83Wd0iug0yd5LqIwMyuVfXVObeVC6hUKpulUmmXZAzgHcAHyaqqRlkBySsAkYjMALgjeea9P+w5SJKkISJjAKYHFYJ6XphZEHlJ03S5l1GtVo9JzorIalHRICi0JCKR937hSyKDqOrqT6ORFXe73Xr42iGPfcicqi4WWL8VkdGsOOQMAfqPuQdgvQBwrqo3zrkwI70YAoTvM7ONojZIPgC4Hxyq7y2cAohFZL4vcAmAZrakquPZmXOuXuTgwsxC/08AplT1hGTYgX0RaQNYCXPinJvMBSRJsi0ieyQv0jQ9yBaov1jhfJPkYaPROM4F/GWzPwEcsLeBq7tlDgAAAABJRU5ErkJggg=='
      list.forEach((item, i) => {


        const { index, typeColor, curveIndex, lname, lable } = getLabelAndConfig(item)

        try {
          csyjSeriesMap.data.push({
            coords: [
              [curveIndex, item.warnTime],
              [curveIndex, limitLineHeightMin2Px(item.warnTime)]
            ],
            lineStyle: { color: typeColor },
            tooltip: {
              show: true,
              trigger: 'item',
              triggerOn: 'mousemove',
              formatter: function (params) {
                return lable
              }
            }
          })
        } catch (e) {
          console.warn(e)
        }
        csyjSeriesMap.lineStyle = {
          width: 18
        }
        let la = ''
        op.series.forEach(line => {
          const { yAxisIndex, type, name, data } = line
          if (yAxisIndex === index) {
            const itemData = data.find(x => x[1] === item.warnTime)
            if (itemData) {
              const value = itemData[0] !== undefined ? itemData[0] : '-'
              la += `${name}：${value}<br/>`
            }
          }

          if (type === 'line' && name === lname) {
            const markPointDataIndex = line.data.findIndex(p => p[1] === item.warnTime)
            if (markPointDataIndex !== -1) {
              const markData = line.data[markPointDataIndex]
              data1.push({
                label: { show: true, color: '#000' },
                yAxis: markData[1],
                xAxis: markData[0],
                coords: [
                  [curveIndex, item.warnTime],
                  [curveIndex, limitLineHeightMin2Px(item.warnTime)]
                ],
                tooltip: {
                  show: true,
                  trigger: 'item',
                  triggerOn: 'mousemove',
                  backgroundColor: 'rgba(255,255,255,1)',
                  formatter: function (params) {
                    return `<span style="color: red">${lable}</span>`

                    //   < br / > < span style = 'color: cornflowerblue' >${la} < /span>
                  }
                }
              })
              line.z = 100
              line.zlever = 100
              line.emphasis.scale = 0.01
              line.markPoint = {
                symbol: lsymbol,
                itemStyle: {
                  // opacity:0.3
                  // color: 'rgba(255, 0, 0, 0.9)' // 这里的 rgba 的第 4 个参数 0.5 表示 50% 的透明度
                },
                symbolSize: 20,
                symbolKeepAspect: true,
                symbolOffset: ['-5%', 0],
                data: data1,
                emphasis: {
                  scale: 2
                }
              }
            }
          }
        })
      })
      this.mainChart.setOption({ series: op.series })
      this.mainChart.setOption({ series: csyjSeriesMap })

      //this.closeNotify();
    },
    gotoPrevOrNextCsyj(direction) {
      const count = this.newWarnNum
      if (count === 0) {
        this.$notification({ message: '提示', content: '参数预警案例数量为0' })
      } else {
        const focusTo = this.lastAllCsyjAjaxData[this.csyjFocusIndex]
        let csyjTime = moment(focusTo.warnTime)
        csyjTime.startOf('hour')
        const chartZoomStart = this.calZoomRangeStart(csyjTime.format('YYYY-MM-DD HH:mm:ss'))
        const chartZoomEnd = chartZoomStart + calZoomRangeBottom()
        this.mainChart.setOption({ dataZoom: [{ start: chartZoomStart, end: chartZoomEnd }] })
        this.csyjFocusIndex = (this.csyjFocusIndex + (1 * direction) + this.lastAllCsyjAjaxData.length) % this.lastAllCsyjAjaxData.length
        this.$notification.open({
          message: focusTo.warnTime,
          description: function (h) {
            return h('div', { domProps: { innerHTML: '[' + focusTo.jh + ' ' + focusTo.warnType + ']<br/>时间：' + focusTo.warnTime } })
          },
          key: 'notifyCsyjOnChart',
          placement: 'bottomRight'
        })
      }
    },
    gotoPrevOrNextGcyj(direction) {
      const count = this.gcyjTotalNum
      if (count === 0) {
        this.$notification({ message: '提示', content: '工程预警案例数量为0' })
      } else {
        const focusTo = this.lastAllGcyjAjaxData[this.gcyjFocusIndex]
        let gcyjTime = moment(focusTo.startDate)
        gcyjTime.startOf('hour')
        const chartZoomStart = this.calZoomRangeStart(gcyjTime.format('YYYY-MM-DD HH:mm:ss'))
        const chartZoomEnd = chartZoomStart + calZoomRangeBottom()
        this.mainChart.setOption({ dataZoom: [{ start: chartZoomStart, end: chartZoomEnd }] })
        this.gcyjFocusIndex = (this.gcyjFocusIndex + (1 * direction) + this.lastAllGcyjAjaxData.length) % this.lastAllGcyjAjaxData.length
        this.$notification.open({
          message: focusTo.startDate,
          description: function (h) {
            return h('div', { domProps: { innerHTML: focusTo.description } })
          },
          key: 'notifyGcyjOnChart',
          placement: 'bottomRight'
        })
      }
    },
    /* 关闭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))
    },
    /* 接口获取最新俩小时数据图表数据 */
    getDataByTime(jh, selectedConfigureKey, time1, time2) {
      const params = { jh, time1, time2, templateId: selectedConfigureKey }
      const _this = this
      console.log('getDataByTime===111')
      getDataByTime(params).then((res) => {
        if (res.success && res.result.length > 0) {
          this.clearWorkConditions()


          const resultList = _this.filterNegative(res.result)

          if (resultList[0].templateId === this.selectedConfigureKey) {
            const op = _this.mainChart.getOption()
            const listLength = resultList.length - 1
            resultList.forEach((itemRes, index1) => {

              this.setWorkCondition(itemRes)

              _this.updateChartList(itemRes, index1, listLength)
              op.series = _this.updateOptionSeries(itemRes, op.series)
              _this.updateRealTimeAndDeepth(itemRes)
            })
            console.log('op↓')
            console.log(op)
            _this.mainChart.setOption(_this.updateDataZoom(op))
          }
        }
      })
    },
    updateChartList(itemRes, index1, listLength) {
      let _this = this
      _this.chartList.forEach((chartItem, index2) => {
        chartItem.children.forEach((childItem, index3) => {
          if (itemRes[childItem.dataSource.toLowerCase()] !== '') {
            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 + ']')
            }
          }
        })
      })
    },

    updateOptionSeries(itemRes, series) {
      // console.log("itemRes ↓")
      // console.log(itemRes)
      // console.log("series ↓")
      // console.log(series)

      series.forEach((item) => {
        if (item.id.indexOf('warnings') < 0) {
          const dataItem = []
          const dataSource = item.id.split('-')[0]
          const pointValue = itemRes[dataSource.toLowerCase()]
          if (pointValue != '' || pointValue === 0) {
            dataItem.push(pointValue)
            dataItem.push(itemRes.time)
            item.data.push(dataItem)
          }

        }
      })
      return series
    },

    updateRealTimeAndDeepth(itemRes) {
      let _this = this
      const FzqkDeepthItem = {}
      FzqkDeepthItem.time = itemRes.time
      FzqkDeepthItem.deepth = itemRes.depth
      const mNow = moment(itemRes.time)
      const timePart = mNow.format('HH:mm:ss')
      const datePart = mNow.format('YYYY-MM-DD')
      if (_this.deepthList.length === 0) {
        if (timePart >= '00:05:00') {
          const yDataDeepthItem = {}
          yDataDeepthItem.time = datePart + ' 00:05:00'
          yDataDeepthItem.deepth = itemRes.depth
          yDataDeepthItem.bitDepth = itemRes.bitdepth
          _this.deepthList.push(yDataDeepthItem)
        }
      } else {
        const lastDeepthTime = _.last(_this.deepthList).time
        const next5min = moment(lastDeepthTime).add(5, 'minutes').format('HH:mm:ss')
        if (timePart >= next5min) {
          const yDataDeepthItem = {}
          yDataDeepthItem.time = datePart + ' ' + next5min
          yDataDeepthItem.deepth = itemRes.depth
          yDataDeepthItem.bitDepth = itemRes.bitdepth
          _this.deepthList.push(yDataDeepthItem)
          // console.log('yDataDeepthItem')
          // console.log(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
          // console.log(FzqkDeepthItem.time+"!!??"+FzqkDeepthItem.deepth)

          _this.FzqkDeepth.push(FzqkDeepthItem)
        }
      } else {
        // console.log(FzqkDeepthItem.time+"!!??22"+FzqkDeepthItem.deepth)

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

    updateDataZoom(op) {
      if (this.time_coose_boolen) {
        op.dataZoom[0].start = 0
        op.dataZoom[0].end = op.dataZoom[0].start + calZoomRangeBottom()

      }
      if (!this.historyData_boolen && this.calZoomRangeStart(this.realTime) < 98) {
        op.dataZoom[0].start = this.calZoomRangeStart(this.getCutData(this.realTime, 0.5))
        op.dataZoom[0].end = op.dataZoom[0].start + calZoomRangeBottom()
      }
      return op
    },
    /* 接口分别获取当天数据图表数据 */
    async m_getDataByTime(jh, selectedConfigureKey, f_time, t_time) {
      let resultStatus = '1'
      let params = {
        jh: jh,
        time1: f_time,
        time2: t_time,
        templateId: selectedConfigureKey
      }
      // this.yjlasttime = this.jsonTimeLastTime;

      const updateRealTimeData = (realTimeNum, childItem) => {
        if (realTimeNum === undefined) {
          realTimeNum = ''
        }
        this.allRealTime.forEach((realTimeItem) => {
          if (realTimeItem.id === childItem.id) {
            realTimeItem.num = `[${realTimeNum}]`
          }
        })
      }
      sendMsg(JSON.stringify({ 'wellId': this.jh, 'isPull': true }))

      console.log('getDataByTime===222')
      console.log('this.allRealTime', this.allRealTime)
      await getDataByTime(params).then((res) => {
        if (res.success && res.result.length > 0) {
          let resultList = []
          resultList.push(...this.filterNegative(res.result))
          if (resultList[0].templateId === this.selectedConfigureKey) {
            let op = this.mainChart.getOption()
            const listLength = resultList.length - 1
            resultList.forEach((itemRes, index1) => {
              this.setWorkCondition(itemRes)

              this.chartList.forEach((chartItem, index2) => {
                chartItem.children.forEach((childItem, index3) => {
                  const value = itemRes[childItem.dataSource.toLowerCase()]
                  if (value !== '') {
                    if (!childItem.data) {
                      childItem.data = []
                    }
                    childItem.data.push(value)
                    if (listLength === index1) {
                      updateRealTimeData(value, childItem)
                      this.$set(this.chartList[index2].children[index3], 'val', `[${value}]`)
                    }
                  }
                })
              })
              op.series.forEach((item) => {
                if (!item.id.includes('warnings')) {
                  const dataItem = []
                  const dataSource = item.id.split('-')[0]
                  const pointValue = itemRes[dataSource.toLowerCase()]
                  if (pointValue !== '' || pointValue === 0) {
                    dataItem.push(pointValue, itemRes.time)
                    item.data.push(dataItem)
                  }
                }
              })
            })
            if (this.start_timing && !this.historyData_boolen) {
              const yidong = 0.018
              this.is_back_boolean = true
              op.dataZoom[0].start += yidong
              op.dataZoom[0].end += yidong
              op.series.forEach((series) => {
                series.data = series.data.filter(data => {
                  const dataDate = new Date(data[1])
                  const lastTimeDate = new Date(this.time2)
                  const startTime = new Date(this.time1)
                  return dataDate <= lastTimeDate && dataDate >= startTime
                })
              })
            }
            this.mainChart.setOption(op)
          }
        }
      })
    },
    setYDeepth() {
      const _this = this
      const yAxisItem = {
        id: 'y0',
        axisTick: {
          show: true,
          length: 200
        },
        axisLabel: {
          color: this.warnTheme == 'dark' ? '#b581f5' : '#000',
          verticalAlign: 'bottom',
          rich: {
            time: {
              color: '#000000'
            },
            deep: {
              color: '#dc143c'
            },
            location: {
              color: '#0000ff'
            }
          },
          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')
            // }
            if (index2 >= 0) {
              return '{time|' + moment(value).format('HH:mm') + '}' + '\n' + '{deep|' + _this.deepthList[index2].deepth + '}' + '\n' + '{location|' + _this.deepthList[index2].bitDepth + '}'
            } else {
              return '{time|' + moment(value).format('HH:mm') + '}'
            }
          }
        }
      }
      this.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) {
      if (this.lastMoment !== null) {
        if (this.lastMoment.diff(moment()) > -1000) {
          return
        }
        this.lastMoment = moment()
      } else {
        this.lastMoment = moment()
      }
      if (this.mainChart != null) {
        this.mainChart.clear()
        this.mainChart.dispose()
        this.mainChart = null
      }
      this.chartFinished = false
      this.FzqkDeepth = []
      this.gcyjAllTime = []
      this.chartList.forEach(chartItem => {
        chartItem.children.forEach(childItem => {
          childItem.data = []
        })
      })
      this.mainChart = echarts.init(document.getElementById('chartContent'), 'shine')
      const _this = this
      this.$nextTick(() => {
        _this.setOptions(_this.chartList)
      })

      this.mainChart.on('finished', () => {
        if (this.chartFinished == false) {
          this.chartFinished = true
          this.unlocking = true
        }
      })
      this.mainChart.on('click', 'series.scatter.lable', (parms) => {
        this.$refs.fzqkForm.edit(parms.data)
      })

      function clearGcyjMarkLine() {
        const { series } = _this.mainChart.getOption()
        if (series[0].markLine && series[0].markLine.showFlag) {
          series.forEach(line => {
            const { yAxisIndex, type } = line
            if (type === 'line') {
              if (line.markLine && line.markLine.showFlag) {
                line.markLine.showFlag = false
                line.markLine.data = []
              }
              if (line.markPoint.symbol == 'circle') {
                line.markPoint.data = []
              } else {
                //未测试
                line.markPoint.data.forEach((item, index) => {
                  line.markPoint.data[index].label.show = false
                })
              }
            }
          })
          _this.mainChart.setOption({ series: series })
        }
      }

      this.mainChart.on('click', (params) => {
        if (params.seriesId === gcyjSeriesId || params.seriesId === csyjSeriesId) {
          let str = '工程预警跟踪线'
          let str2 = '工程预警跟踪数据'
          if (params.seriesId === csyjSeriesId) {
            str = '参数预警跟踪线'
            str2 = '参数预警跟踪数据'
          }
          const startTime = params.data.coords[0][1]
          const options = _this.mainChart.getOption()
          const gridExist = []
          const textList = {}
          let markPointDataIndex = -2
          options.series.forEach(line => {
            const { yAxisIndex, type } = line
            if (type === 'line') {
              if (!gridExist.some(t => t === yAxisIndex)) {
                line.markLine = {
                  silent: true,
                  showFlag: true,
                  symbol: ['none', 'none'],
                  data: [{
                    position: 'middle',
                    yAxis: startTime,
                    lineStyle: { type: 'solid', color: 'red', width: 1 },
                    label: {
                      show: gridExist.length === 0,
                      position: 'insideStartTop',
                      color: 'red',
                      formatter: function () {
                        return str
                      }
                    }
                  }]
                }
                gridExist.push(yAxisIndex)
                textList[yAxisIndex] = []
              }
              markPointDataIndex = markPointDataIndex === -2 ? _.findIndex(line.data, p => p[1] === startTime) : markPointDataIndex
              if (markPointDataIndex !== -1) {
                const markData = line.data[markPointDataIndex]
                if (line.markPoint && line.markPoint.data && line.markPoint.data.length > 0) {
                  line.markPoint = {
                    symbol: line.markPoint.symbol,
                    symbolSize: 10,
                    label: {
                      color: line.itemStyle.color, position: [10, 10], rotate: -45, formatter: function () {
                        return `${line.name.substring(0, line.name.indexOf('('))}(${markData[0]})`
                      }
                    },
                    data: line.markPoint.data
                  }
                  line.markPoint.data.forEach((item, index) => {
                    if (item.yAxis == markData[1]) {
                      line.markPoint.data[index].label.show = true
                    } else {
                      line.markPoint.data[index].label.show = false
                    }
                  })
                } else {
                  line.markPoint = {
                    symbol: 'circle',
                    symbolSize: 10,
                    label: {
                      color: line.itemStyle.color, position: [10, 10], rotate: -45, formatter: function () {
                        return `${line.name.substring(0, line.name.indexOf('('))}(${markData[0]})`
                      }
                    },
                    data: [{
                      label: { show: true, color: line.itemStyle.color },
                      yAxis: markData[1],
                      xAxis: markData[0]
                    }]
                  }
                }
                textList[yAxisIndex].push({
                  title: line.name,
                  value: (!markData[0] && markData[0] !== 0 ? '无' : markData[0]),
                  color: line.itemStyle.color
                })
              }
            }
          })
          _this.mainChart.setOption({ series: options.series })
          const divWidth = 172
          const notificationWidth = divWidth * _.keys(textList).length + 48
          _this.$notification.open({
            message: str2,
            style: { width: notificationWidth + 'px' },
            placement: 'bottomLeft',
            key: 'gcyjTraceTextDetail',
            description: function (h) {
              return h('div',
                _.keys(textList).map(k => {
                  return h('div', { style: { float: 'left', width: divWidth - 4 + 'px' } },
                    textList[parseInt(k)].map(markData => {
                      return h('a-tag', {
                        props: { color: markData.color },
                        style: { display: 'block', width: '165px', marginBottom: '4px', height: '20px' }
                      }, [
                        h('div', { style: { float: 'left' } }, `${markData.title}`),
                        h('div', { style: { float: 'right' } }, `${markData.value}`)
                      ]
                      )
                    }
                    ))
                })
              )
            }
          })
        } else {
          clearGcyjMarkLine()
        }
      })
      this.mainChart.getZr().on('click', () => {
        clearGcyjMarkLine()
      })

      const debounceZoomReset = _.debounce((chart, options) => {

        chart.setOption(options, { notMerge: true, replaceMerge: ['yAxis'] })
      }, 150)
      this.lastTim = calZoomRangeBottom()
      this.mainChart.on('dataZoom', this.chartDataZoom)
      this.openNotify()
      // 4.18注释
      if (this.$route.query.serchTime) {
        this.time = this.$route.query.serchTime.substring(0, 10)
        this.is_back_boolean = false
        // this.historyData_boolen = true
        this.setChartTimeLoaded(this.time, this.getPlusDate(this.time, 24))
      }
      if (this.$route.query.time == 'getTime') {
        this.getTime(this.$route.query.jh)
        this.is_back_boolean = true
        this.historyData_boolen = false
      }
      this.loadChartData()
    },
    chartDataZoom(params) {
      var _this = this
      let lastdiff = 0
      function updateYAxisLabels(options, diff1) {
        options.yAxis.forEach((y, index) => {
          y.minorTick.splitNumber = diff1 < 5 ? diff1 - 1 : 5
        })
      }

      let diff1 = _this.yAxisLabels[1].diff(_this.yAxisLabels[0], 'minutes')
      if (_this.yAxisLabelDiff !== diff1) {
        const options = _this.mainChart.getOption()
        updateYAxisLabels(options, diff1)
      }
      _this.yAxisLabelDiff = diff1
      let start = params.batch[0].start
      let end = params.batch[0].end
      let diff = end - start
      let mircodiff = Math.abs(diff - lastdiff)
      lastdiff = diff
      /***************新滚动判断方法******************/
      var startTime = this.time + ' ' + indexChartCompareUtil.decimalTimeToTime(start)
      var endTime = this.time + ' ' + indexChartCompareUtil.decimalTimeToTime(end)
      // console.log('params.batch[0].start', start)
      // console.log('params.batch[0].end', end)
      if (this.chartPreSpacerTime != '') {
        var preTimeSub = indexChartCompareUtil.timeSubtractMin(this.chartPreSpacerTime, startTime)
        if (preTimeSub <= 30) {
          this.setChartData(this.preCatchChartData)
          this.chartPreSpacerTime = this.loadPreSpaceTime
          console.log('this.warnLogPreList', this.warnLogPreList)
          this.setWarnLogOption(this.warnLogPreList)
          this.loadPerData(this.chartPreSpacerTime)
        }
      }
      /*********************************************/
      if (_this.historyData_boolen && _this.dataRome == mircodiff) {
        _this.$route.query.serchTime = null
        _this.$route.query.time = null
        const num = (3 / 1080) * window.innerHeight + 1
        if (params.batch[0].start <= 0 && !_this.unlocking) {
          const op = _this.mainChart.getOption()
          op.dataZoom[0].start = params.batch[0].start + num
          op.dataZoom[0].end = params.batch[0].end + num
          _this.mainChart.setOption(op)
        }
        if (params.batch[0].end == 100 && !_this.unlocking) {
          const op = _this.mainChart.getOption()
          op.dataZoom[0].start = params.batch[0].start - num
          op.dataZoom[0].end = params.batch[0].end - num
          _this.mainChart.setOption(op)
        }

        if (params.batch[0].start <= 0 && _this.unlocking) {
          // _this.openNotify()
          _this.unlocking = false
          _this.is_back_boolean = true
          _this.historyData_boolen = true
          _this.time_coose_boolen = false
          // _this.chartList.forEach(chartList => {
          //   chartList.children.forEach(children => {
          //     children.data = []
          //   })
          // })
          _this.time = _this.getCutData(_this.time, 24)
          // await _this.loadChartData()
          // _this.setOptions2(_this.chartList)
          const op = _this.mainChart.getOption()
          op.dataZoom[0].start = 100 - diff
          op.dataZoom[0].end = 100
          op.series.forEach((series, index) => {
            series.data = []
          })
          _this.mainChart.setOption(op)
          _this.isup = false
        }
        if (params.batch[0].end == 100 && _this.unlocking) {
          _this.openNotify()
          _this.unlocking = false
          _this.isup = false
          _this.time = _this.getPlusDate(_this.time, 24)
          _this.is_back_boolean = false
          _this.historyData_boolen = true
          _this.time_coose_boolen = false
          _this.chartList.forEach(chartList => {
            chartList.children.forEach(children => {
              children.data = []
            })
          })

          const op = _this.mainChart.getOption()
          op.dataZoom[0].start = 0
          op.dataZoom[0].end = op.dataZoom[0].start + diff
          op.series.forEach((series, index) => {
            series.data = []
          })
          _this.mainChart.setOption(op)
          // await _this.loadChartData()
          // _this.setOptions2(_this.chartList)
          //   _this.setChartTimeLoaded(max,_this.getPlusDate(_this.jsonTimeLastTime,24))
        }
      } else {
        if (params.batch[0].start <= 0 && _this.dataRome == mircodiff) {
          _this.openNotify()
          _this.unlocking = false
          // console.log('_this.time11111', _this.time)
          _this.time = _this.getCutData(_this.time + ' 00:00:00', 24)
          // console.log('_this.time22222', _this.time)
          _this.is_back_boolean = true
          _this.historyData_boolen = true
          _this.time_coose_boolen = false
          // await _this.loadChartData()
          // _this.setOptions2(_this.chartList)
          const op = _this.mainChart.getOption()
          op.dataZoom[0].start = 100 - diff
          op.dataZoom[0].end = 100
          _this.mainChart.setOption(op)
        }
      }
      _this.dataRome = mircodiff
    },
    loadingMessage() {
      this.$message({
        dangerouslyUseHTMLString: true,
        showClose: true,
        duration: 0,
        message: '<strong>这是 <i>HTML</i> 片段</strong>'
      })
    },
    momentHouse(Time) {
      return moment(getDateStr(Time)).startOf('hour').format('YYYY-MM-DD HH:mm:ss')
    },
    /* 数据图表配置 */
    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 dataZoomYIndex = []
      for (let index = 0; index < this.chartList.length; index++) {
        dataZoomYIndex.push(index)
      }
      let warningWidth = 0
      let dataZoomIndex = 0
      this.warningList.forEach((item, index) => {
        if (item.show) {
          warningWidth += Number(item.width)
          dataZoomYIndex.push((dataZoomIndex + this.chartList.length))
          dataZoomIndex++
        }
      })

      function lineTipText(lineConfig, chartParams) {
        function pickValue(value) {
          if (value === undefined) {
            return '-.--'
          } else if (value.data[0] === undefined || value.data[0] === null) {
            return '-.--'
          }
          return value.data[0]
        }

        let marker = '<span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;'
        marker += `background-color:${lineConfig.color};"></span>`
        const html = []
        html.push('<div style="margin: 10px 0 0;line-height:1;">')
        html.push('<div style="margin: 10px 0 0;line-height:1;">')
        html.push(marker)
        html.push(`<span style="font-size:14px;color:#666;font-weight:400;margin-left:2px">${lineConfig.title}(${lineConfig.unit})</span>`)
        const value = _.find(chartParams, p => p.seriesName.indexOf(lineConfig.title) >= 0)
        html.push('<span style="float:right;margin-left:20px;font-size:14px;color:#666;')
        html.push(`font-weight:900">${pickValue(value)}</span>`)
        html.push('<div style="clear:both"></div>')
        html.push('</div>')
        html.push('</div>')
        return html.join(' ')
      }

      function lineWorkConditionText(title, val, color = 'red') {
        function pickValue(value) {
          if (value === undefined || value === null) {
            return '-.--'
          }
          return value
        }

        let marker = '<span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;'
        marker += `background-color:${color};"></span>`
        const html = []
        html.push('<div style="margin: 10px 0 0;line-height:1;">')
        html.push('<div style="margin: 10px 0 0;line-height:1;">')
        html.push(marker)
        html.push(`<span style="font-size:14px;color:#666;font-weight:400;margin-left:2px">${title}</span>`)
        html.push('<span style="float:right;margin-left:20px;font-size:14px;color:#666;')
        html.push(`font-weight:900">${pickValue(val)}</span>`)
        html.push('<div style="clear:both"></div>')
        html.push('</div>')
        html.push('</div>')
        return html.join(' ')
      }


      function tipsClick(lineConfig, chartParams) {
        let marker = '<span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;'
        marker += `background-color:${lineConfig.color};"></span>`
        const html = []
        html.push('<div style="margin: 10px 0 0;line-height:1;">')
        html.push('<div style="margin: 10px 0 0;line-height:1;">')
        html.push(marker)
        html.push(`<span style="font-size:14px;color:#666;font-weight:400;margin-left:2px">${lineConfig.title}(${lineConfig.unit})</span>`)
        const value = _.find(chartParams, p => p.seriesName.indexOf(lineConfig.title) >= 0)
        html.push('<span style="float:right;margin-left:20px;font-size:14px;color:#666;')
        html.push(`font-weight:900"></span>`)
        html.push('<div style="clear:both"></div>')
        html.push('</div>')
        html.push('</div>')
        return html.join(' ')
      }

      function clearGcyjMarkLine() {
        const { series } = _this.mainChart.getOption()
        if (series[0].markLine && series[0].markLine.showFlag) {
          series.forEach(line => {
            const { yAxisIndex, type } = line
            if (type === 'line') {
              if (line.markLine && line.markLine.showFlag) {
                line.markLine.showFlag = false
                line.markLine.data = []
              }
              if (line.markPoint.symbol == 'circle') {
                line.markPoint.data = []
              } else {
                //未测试
                line.markPoint.data.forEach((item, index) => {
                  line.markPoint.data[index].label.show = false
                })
              }
            }
          })
          _this.mainChart.setOption({ series: series })
        }
      }

      const options = {
        animation: false,
        tooltip: {
          show: true,
          // 20220914  找到你了
          formatter(params) {
            // const tips = [`<div >12321</div>`]
            const tips = []


            if (params && params.length > 0) {
              // console.log('chart[xAxisIndex]')
              // console.log(params[0].data[1])
              // console.log(params)


              // const now = Date.now(); // 获取当前时间
              //
              // if (now - _this.tipLastTime > 0.5*1000) { // 检查时间间隔是否大于一秒（1000毫秒）
              //   console.log("执行操作");
              //   // 在这里执行你的操作
              //   getMotionByTime({jh:_this.jh,time:params[0].data[1]}).then((res)=>{
              //
              //     if (res.result !== null) {
              //       _this.$notification.open({
              //         key:_this.NotiKey,
              //         message: params[0].data[1],
              //         description:
              //           res.result!==null?`${res.result.operatingMode}=>${res.result.motion}`:'暂无工况',
              //         duration: 3
              //       })
              //     }
              //   })
              //   _this.tipLastTime = now; // 更新上一次操作时间
              // }

              const xAxisIndex = params[0].axisIndex
              const linesConfig = chart[xAxisIndex].children
              tips.push(`<div style="float: left">`)
              tips.push(`<div style="font-size:14px;color:#666;font-weight:400;line-height:1;">${params[0].axisValueLabel}</div>`)
              tips.push('<div style="margin: 10px 0 0;line-height:1;">')
              // console.log(linesConfig)
              linesConfig.forEach(v => {
                // console.log("chart[xAxisIndex]")
                // console.log(v)
                tips.push(lineTipText(v, params))
              })


              tips.push(lineWorkConditionText('工况', _this.workCondition.get(params[0].data[1]).operatingMode))
              tips.push(lineWorkConditionText('动作', _this.workCondition.get(params[0].data[1]).motion))


              tips.push('</div>')
              tips.push('<div style="clear:both"></div>')
              tips.push('</div>')
            }
            return tips.join(' ')
          }
        },
        dataZoom: [
          {
            type: 'inside',
            throttle: 0,
            disabled: true,
            yAxisIndex: dataZoomYIndex,
            filterMode: 'empty',
            start: 0,
            end: calZoomRangeBottom(),
            zoomOnMouseWheel: 'shift',
            moveOnMouseWheel: true,
            moveOnMouseMove: true
          }
        ]
      }
      const series = []
      const grid = []
      const xAxis = []
      const yAxis = []
      if (!this.$refs.chartMain.offsetWidth) {
        return
      }
      const chartMainWidth = this.$refs.chartMain.offsetWidth - depthTrackWidthPx - 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 = this.depthTrackIndex === 1 ? depthTrackWidthPx : 0
      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'
              }
            }
          }
        }
        const appendDepthTrack = (index + 2) === this.depthTrackIndex
        preLeft += Number(width) + (appendDepthTrack ? depthTrackWidthPx : 0)
        let yAxisItem = {
          id: 'y' + index,
          gridIndex: index,
          animation: false,
          type: 'time',
          axisLine: {
            onZero: true,
            show: true,
            lineStyle: { color: this.warnTheme == 'dark' ? '#fbdc61' : '#000' }
          },
          axisTick: {
            show: false,
            lineStyle: { color: this.warnTheme == 'dark' ? '#fbdc61' : '#000' }
          },
          boundaryGap: false,
          // min: this.is_back_boolean ? this.jsonTimeLastTime.substring(0,10)+" 00:00:00": this.jsonTimeLastTime,
          min: this.time1,
          max: tomoStr,
          minInterval: 60 * 1000,
          maxInterval: 3600 * 24 * 1000,
          splitLine: {
            show: true,
            lineStyle: {
              color: '#aaa'
            }
          },
          minorTick: {
            splitNumber: 5
          },
          minorSplitLine: {
            show: true,
            lineStyle: { color: '#aaa' }
          },
          axisLabel: {
            color: this.warnTheme == 'dark' ? '#b581f5' : '#000',
            formatter: ''
          },
          data: [],
          inverse: true
        }
        if (index == 0) {
          yAxisItem = Object.assign(yAxisItem, {
            offset: calYAxisOffset(width, this.depthTrackIndex),
            maxInterval: 3600 * 24 * 1000,
            axisTick: {
              show: true,
              length: depthTrackWidthPx,
              lineStyle: { color: this.warnTheme == 'dark' ? '#fbdc61' : '#000' }
            },
            axisLabel: {
              color: this.warnTheme == 'dark' ? '#b581f5' : '#000',
              verticalAlign: 'bottom',
              rich: {
                time: {
                  color: '#000000'
                },
                deep: {
                  color: '#dc143c'
                },
                location: {
                  color: '#0000ff'
                }
              },
              formatter: function (value, index) {
                const mValue = moment(value)
                const Time = mValue.format('YYYY-MM-DD HH:mm:ss')
                const index2 = _this.deepthList.findIndex(x => x.time == Time)
                _this.yAxisLabels.push(mValue)
                _this.yAxisLabels.shift()

                if (index2 >= 0) {
                  return '{time|' + mValue.format('YYYY-MM-DD HH:mm') + '}' + '\n' + '{deep|' + _.round(_this.deepthList[index2].deepth, 2) + '}' + '\n' + '{location|' + _.round(_this.deepthList[index2].bitDepth, 2) + '}'
                } else {
                  return '{time|' + mValue.format('YYYY-MM-DD HH:mm') + '}'
                }
              }
            },
            minorTick: {
              splitNumber: 5
            },
            minorSplitLine: {
              show: true,
              lineStyle: { color: '#aaa' }
            }
          })
        }
        if (item.children === undefined || item.children.length === 0) {
          const xAxisItem = {
            gridIndex: index,
            type: 'value',
            splitNumber: xAxisSplitNumber,
            splitLine: {
              show: true,
              lineStyle: {
                color: '#aaa'
              }
            },
            axisLabel: {
              formatter: function () {
                return ''
              }
            }
          }
          xAxis.push(xAxisItem)
        }
        item.children.forEach((ele, index2) => {
          ele['maxNumExtended'] = ele.maxNum
          ele['minNumExtended'] = ele.minNum
          const serItem = {
            connectNulls: false,
            id: ele.dataSource + '-' + xIndex,
            name: ele.title + '(' + ele.unit + ')',
            yAxisIndex: index,
            type: 'line',
            symbolSize: 10,
            symbol: 'circle',
            //smooth: ele.lineStyle === 'smooth',
            smooth: false,
            hoverAnimation: false,
            step: ele.lineStyle === 'step',
            showSymbol: false,
            itemStyle: {
              width: 1,
              color: ele.color,
              style: 'solid'
            },
            lineStyle: {
              width: this.singleLineWidth
            },
            emphasis: {
              focus: 'series'
            },
            xAxisIndex: xAxis.length,
            z: 20 - index2,
            zlevel: 1,
            data: []
          }
          const xAxisItem = {
            gridIndex: index,
            min: function (value) {
              if (ele.spread === '1' && value.min < ele.minNum) {
                if (ele.minSpread === 'a') {
                  const newMin = Math.floor(Number(value.min) / 10) * 10
                  ele.minNumExtended = newMin
                  return newMin
                } else {
                  return value.min
                }
              } else {
                return ele.minNum
              }
            },
            max: function (value) {
              if (ele.spread === '1' && value.max > ele.maxNum) {
                if (ele.minSpread === 'a') {
                  const newMax = Math.ceil(Number(value.max) / 10) * 10
                  ele.maxNumExtended = newMax
                  return newMax
                } else {
                  return value.max
                }
              } else {
                return ele.maxNum
              }
            },
            splitNumber: xAxisSplitNumber,
            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.is_back_boolean ? this.jsonTimeLastTime.substring(0,10)+" 00:00:00": this.jsonTimeLastTime,
            min: this.time1,
            max: tomoStr,
            maxInterval: 3600 * 24 * 1000,
            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 = {
              zlevel: 1,
              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
      this.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 = _this.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 - depthTrackWidthPx - 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 = this.depthTrackIndex === 1 ? depthTrackWidthPx : 0
      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'
        }
        const appendDepthTrack = (index + 2) === this.depthTrackIndex
        preLeft += Number(width) + (appendDepthTrack ? depthTrackWidthPx : 0)
        let yAxisItem = {
          id: 'y' + index,
          gridIndex: index,
          animation: false,
          type: 'time',
          axisLine: {
            onZero: true, show: true,
            lineStyle: { color: this.warnTheme == 'dark' ? '#fbdc61' : '#000' }
          },
          axisTick: {
            show: false,
            lineStyle: { color: this.warnTheme == 'dark' ? '#fbdc61' : '#000' }
          },
          boundaryGap: false,
          // min: this.is_back_boolean ? this.jsonTimeLastTime.substring(0,10)+" 00:00:00": this.jsonTimeLastTime,
          min: this.time1,
          max: tomoStr,
          minInterval: 60 * 1000,
          maxInterval: 3600 * 24 * 1000,
          splitLine: {
            show: true,
            lineStyle: {
              color: '#aaa'
            }
          },
          minorTick: {
            splitNumber: 5
          },
          minorSplitLine: {
            show: true,
            lineStyle: { color: '#aaa' }
          },
          axisLabel: {
            color: this.warnTheme == 'dark' ? '#b581f5' : '#000',
            formatter: ''
          },
          data: [],
          inverse: true
        }
        if (index == 0) {
          yAxisItem = Object.assign(yAxisItem, {
            forceInterval: false,
            maxInterval: 3600 * 24 * 1000,
            offset: calYAxisOffset(width, this.depthTrackIndex),
            axisTick: {
              show: true,
              length: depthTrackWidthPx,
              lineStyle: { color: this.warnTheme == 'dark' ? '#fbdc61' : '#000' }
            },
            axisLabel: {
              color: this.warnTheme == 'dark' ? '#b581f5' : '#000',
              verticalAlign: 'bottom',
              rich: {
                time: {
                  color: '#000000'
                },
                deep: {
                  color: '#dc143c'
                },
                location: {
                  color: '#0000ff'
                }
              },
              formatter: function (value, index) {
                const mValue = moment(value)
                const Time = mValue.format('YYYY-MM-DD HH:mm:ss')
                _this.yAxisLabels.push(mValue)
                _this.yAxisLabels.shift()
                const index2 = _this.deepthList.findIndex(x => x.time == Time)
                if (index2 >= 0) {
                  return '{time|' + mValue.format('YYYY-MM-DD HH:mm') + '}' + '\n' + '{deep|' + _.round(_this.deepthList[index2].deepth, 2) + '}'
                    + '\n' + '{location|' + _.round(_this.deepthList[index2].bitDepth, 2) + '}'
                } else {
                  return '{time|' + mValue.format('YYYY-MM-DD HH:mm') + '}'
                }
              }
            },
            minorTick: {
              splitNumber: 5
            },
            minorSplitLine: {
              show: true,
              lineStyle: { color: '#aaa' }
            }
          })
        }
        if (item.children === undefined || item.children.length === 0) {
          const xAxisItem = {
            gridIndex: index,
            type: 'value',
            splitLine: {
              show: true,
              lineStyle: {
                color: '#aaa'
              }
            },
            splitNumber: xAxisSplitNumber,
            axisLabel: {
              formatter: function () {
                return ''
              }
            }
          }
          xAxis.push(xAxisItem)
        }
        item.children.forEach((ele, index2) => {
          ele['maxNumExtended'] = ele.maxNum
          ele['minNumExtended'] = ele.minNum
          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 = {
            connectNulls: false,
            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',
            itemStyle: {
              width: 1,
              color: ele.color,
              style: 'solid'
            },
            lineStyle: {
              opacity: ele.opacity === 0 ? 0 : 1,
              width: this.singleLineWidth
            },
            emphasis: {
              focus: 'series'
            },
            xAxisIndex: xAxis.length,
            z: 20 - index2,
            zlevel: 1,
            data: data
          }
          const xAxisItem = {
            gridIndex: index,
            min: function (value) {
              if (ele.spread === '1' && value.min < ele.minNum) {
                if (ele.minSpread === 'a') {
                  const minNum = Math.floor(Number(value.min) / 10) * 10
                  ele['minNumExtended'] = minNum
                  return minNum
                } else {
                  return value.min
                }
              } else {
                return ele.minNum
              }
            },
            max: function (value) {
              if (ele.spread === '1' && value.max > ele.maxNum) {
                if (ele.minSpread === 'a') {
                  const maxNum = Math.ceil(Number(value.max) / 10) * 10
                  ele['maxNumExtended'] = maxNum
                  return maxNum
                } else {
                  return value.max
                }
              } else {
                return ele.maxNum
              }
            },
            splitNumber: xAxisSplitNumber,
            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.is_back_boolean ? this.jsonTimeLastTime.substring(0,10)+" 00:00:00": this.jsonTimeLastTime,
            min: this.time1,
            max: tomoStr,
            maxInterval: 3600 * 24 * 1000,
            splitLine: { // 网格线
              show: true,
              lineStyle: {
                color: '#aaa'
              }
            },
            axisLabel: {
              formatter: ''
            },
            data: [],
            inverse: true
          }

          let xAxisItem = null
          if (item.id === 'gcyj') {
            // todo
            // xAxisItem = {
            //   id: item.id + 'x',
            //   gridIndex: grid.length,
            //   type: 'category',
            //   data: ['上提遇卡', '井漏'],
            //   show: true,
            //   splitLine: { //
            //     show: true,
            //     lineStyle: {
            //       color: '#aaa'
            //     }
            //   }
            // }
            xAxisItem = {
              id: item.id + 'x',
              gridIndex: grid.length,
              min: 0,
              max: 10,
              type: 'value',
              splitLine: {
                show: true,
                lineStyle: {
                  color: '#aaa'
                }
              }
            }
          } else {
            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
      this.mainChart.setOption(options, true)
    },
    lineClickAndFat(lineItem) {
      const nameKey = lineItem.title + '(' + lineItem.unit + ')'
      const series = {
        name: nameKey,
        lineStyle: {
          width: lineItem.lineFat ? 1 : 2
        }
      }
      this.mainChart.setOption({ series: [series] })
      this.$set(lineItem, 'lineFat', !lineItem.lineFat)
    },
    hideChart(name, id, opacity) {
      let newOPa = 1
      if (opacity === 0) {
        newOPa = 1
        const series = {
          name: name,
          lineStyle: {
            opacity: 1
          }
        }
        this.mainChart.setOption({ series: [series] })
      } else {
        newOPa = 0
        const series = {
          name: name,
          lineStyle: {
            opacity: 0
          }
        }
        this.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)
        }
      })
    },
    chartResize() {
      if (this.mainChart === null) {
        return
      }
      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 - depthTrackWidthPx - 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 = this.depthTrackIndex === 0 ? depthTrackWidthPx : 0
        const grid = []
        const yAxis = this.mainChart.getOption().yAxis
        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
          }
          const appendDepthTrack = (index + 2) === this.depthTrackIndex
          preLeft += Number(width) + (appendDepthTrack ? depthTrackWidthPx : 0)
          grid.push(gridItem)
          if (index === 0) {
            yAxis[0].offset = calYAxisOffset(width, this.depthTrackIndex)
          }
        })
        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)
          }
        })
        this.mainChart.setOption({ grid: grid, yAxis: yAxis })
      }
      this.mainChart.resize()
    },
    onTimeChange(src) {
      const { date, dateString } = src
      this.time = dateString
      this.time_coose_boolen = true
      this.historyData_boolen = true

      this.$route.query.serchTime = null
      this.$route.query.time = null
      this.allRealTime = []
      this.warningList.forEach((item) => {
        if (item.id === 'gcyj') {
          item.show = false
        }
      })
      this.gcyjChecked = false
      sendMsg(JSON.stringify({ 'wellId': this.jh, 'isPull': false }))

      this.initChart('time')
      this.$bus.emit(vueBusEvents.closeSideBar)
    },
    onWarningChange(src) {
      const { checked } = src
      const keys = this.$globle.warningValue
      const _this = this
      this.warningList.forEach((item, index) => {
        for (let key of keys) {
          if (key == 'gcyj') {
            this.gcyjChecked = checked
          }
          if (item.id === key) {
            if (item.id != 'zx') {
              item.loading = true
            }
            this.$set(this.warningList[index], 'show', checked)
            // this.setOptions2(this.chartList)
            if (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.warningList[index].show = true
                this.getGcyjData(this.jh)
              }
              if (item.id === 'csyj') {
                this.warningList[index].show = true
                if (csyjIntervalId != null) {
                  clearInterval(csyjIntervalId)
                  csyjIntervalId = null
                }
                this.getCsyjData(this.jh)
              }
            }
          }
        }
      })
    },

    closeGCYJ() {
      this.gcyjChecked = false
      this.warningList.forEach((item, index) => {
        if (item.id === 'gcyj') {
          item.loading = true
          this.$set(this.warningList[index], 'show', false)
          this.setOptions2(this.chartList)
        }
      })
      // todo
    },
    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 }
      this.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)
    },
    // obsoluted method 202210
    async refresh() {
      this.isGettingWarnMsg = true
      let timeList = []
      this.warningRespList = []
      for (let i = 1; i < 49; i++) {
        timeList.push(moment(this.time + ' 00:00:00').add(30 * i, 'm').format('YYYY-MM-DD HH:mm:ss'))
      }
      for (let index = 0; index < timeList.length; index++) {
        const param = { jh: this.jh, ltdTime: timeList[index] }
        await getAnalyse(param).then((res) => {
          this.warningRespList.push(...res.result)
        })
      }
      this.isGettingWarnMsg = false
    },
    async refreshMD(e, timeout = 30) {
      this.warningList[1].loading = true
      const options = this.mainChart.getOption()
      options.series.forEach((item) => {
        if (item.id == gcyjSeriesId) {
          item.data = []
        }
      })
      this.mainChart.setOption(options, true)
      this.setOptions2(this.chartList)
      const that = this
      await getAnalyse({
        'jh': this.jh,
        'startTime': this.time
      }, timeout).then((res) => {
        if (res.success) {
          if (res.result.length > 0) {
            this.initGCYJChart2(res.result)
          } else {
            this.lastAllGcyjAjaxData = []
          }
        }
      }).catch(e => {
        this.$confirm({
          title: '提示',
          content: '计算工程预警时超过了默认的超时时间30秒,您希望以更长的等待时间进行计算吗?（3分钟）',
          onOk() {
            that.refreshMD(e, 180)
          }
        })
      }).finally(e => {
        this.spinning = false
        this.warningList[1].loading = false
      })
      this.spinning = false
    },
    includeData(list, time) {
      let res = false
      list.forEach((item) => {
        item.data.forEach((data) => {
          return data[1] === time
        })
      })
      return res
    },
    setCurrentDot(data) {
      if (!this.historyData_boolen) {
        // this.getNewData()
      }
    },
    setCurrentDot2(data) {
      const updateRealTimeData = (realTimeNum, childItem) => {
        if (realTimeNum === undefined) {
          realTimeNum = ''
        }
        this.allRealTime.forEach((realTimeItem) => {
          if (realTimeItem.id === childItem.id) {
            realTimeItem.num = `[${realTimeNum}]`
          }
        })
      }

      console.warn("setCurrentDot2↓")

      console.warn(data)

      let resultList = []
      resultList.push(...this.filterNegative([data]))
      console.warn(resultList[0].templateId)
      // resultList[0].templateId === this.selectedConfigureKey
      if (true) {
        let op = this.mainChart.getOption()
        const listLength = resultList.length - 1
        resultList.forEach((itemRes, index1) => {
          this.setWorkCondition(itemRes)

          this.chartList.forEach((chartItem, index2) => {
            chartItem.children.forEach((childItem, index3) => {
              const value = itemRes[childItem.dataSource.toLowerCase()]
              if (value !== '') {
                if (!childItem.data) {
                  childItem.data = []
                }
                childItem.data.push(value)
                if (listLength === index1) {
                  updateRealTimeData(value, childItem)
                  this.$set(this.chartList[index2].children[index3], 'val', `[${value}]`)
                }
              }
            })
          })
          op.series.forEach((item) => {
            if (!item.id.includes('warnings')) {
              const dataItem = []
              const dataSource = item.id.split('-')[0]
              const pointValue = itemRes[dataSource.toLowerCase()]
              if (pointValue !== '' || pointValue === 0) {
                dataItem.push(pointValue, itemRes.time)
                item.data.push(dataItem)
              }
            }
          })
        })
        if (this.start_timing && !this.historyData_boolen) {
          const yidong = 0.018
          this.is_back_boolean = true
          op.dataZoom[0].start += yidong
          op.dataZoom[0].end += yidong
          op.series.forEach((series) => {
            series.data = series.data.filter(data => {
              const dataDate = new Date(data[1])
              const lastTimeDate = new Date(this.time2)
              const startTime = new Date(this.time1)
              return dataDate <= lastTimeDate && dataDate >= startTime
            })
          })
        }
        this.mainChart.setOption(op)
      }
    },

    filterNegative(list) {
      let cacheList = []
      const keys = [
        'actpittotal',
        'bitcost',
        'bitdepth',
        'bitdrilltime',
        'bitno',
        'bitoff',
        'bitrun',
        'bitsize',
        'bittime',
        'c1',
        'c2',
        'c3',
        'co2',
        'condin',
        'condout',
        'curpipe',
        'dc',
        'depth',
        'ec5',
        'ecd',
        'flowin',
        'flowout',
        'flowoutpercent',
        'gainlossvol',
        'h2',
        'h2S1',
        'h2S2',
        'h2S3',
        'h2S4',
        'h2S5',
        'h2S6',
        'h2S7',
        'h2S8',
        'hkh',
        'hks',
        'ic4',
        'ic5',
        'kellyin',
        'lagdepth',
        'lagstrokes',
        'lagtime',
        'mwin',
        'mwout',
        'nc4',
        'nc5',
        'nc6',
        'pit1',
        'pit2',
        'pit3',
        'pit4',
        'pit5',
        'pit6',
        'pit7',
        'pit8',
        'pit9',
        'pit10',
        'pit11',
        'pit12',
        'pittotal',
        'pump1',
        'pump2',
        'pump3',
        'pumptotal',
        'ropInst',
        'ropMavg',
        'rpm',
        'sigma',
        'spp',
        'standsdone',
        'standstogo',
        'stat',
        'stringlen',
        'strokes1',
        'strokes2',
        'strokes3',
        'strokestotal',
        'tdTorque',
        'tempin',
        'tempout',
        'tg',
        'torque',
        'totaldays',
        'tripoverpull',
        'triptandvol',
        'vdepth',
        'vopInst',
        'vopMavg',
        'whp',
        'wob',
        'woh',
        'wohCalc'
      ]

      list.forEach((item, index) => {
        keys.forEach((key) => {
          if (item[key] < 0) {
            item[key] = null
          }
        })
        cacheList.push(item)
      })

      return cacheList
    },
    onChartDatazoomTimeRangeChange(hour) {
      const zoomNow = this.mainChart.getOption().dataZoom

      let lastTimeEnd = moment(this.realTime).startOf('hour').add(1, 'hours')
      const beginTime = lastTimeEnd.clone()
      if (beginTime.day() !== moment(this.time).day()) {
        beginTime.add(-1 * hour, 'hours')
      } else {
        beginTime.add(-1 * (hour > lastTimeEnd.hour() ? lastTimeEnd.hour() : hour), 'hours')
      }
      const start = this.calZoomRangeStart(beginTime)
      const end = start + calZoomRangeBottom() * (lastTimeEnd.diff(beginTime, 'hours'))
      this.mainChart.setOption({ dataZoom: [{ start: start, end: end }] })
    },
    handleFabClicked() {
      this.$dialog(
        () => import('./YjTableDialog'),
        { tableData: this.yjRefreshResult },
        {
          title: `${this.jh} ${this.is_back_boolean ? this.getCutData(this.yjlasttime, 24) + '-' + this.yjlasttime : this.yjlasttime + '-' + this.getPlusDate(this.yjlasttime, 24)} 预警信息`,
          width: document.body.offsetWidth * 0.75,
          height: document.body.offsetHeight * 0.85,
          centered: true,
          maskClosable: false,
          okButtonProps: { style: { display: 'none' } },
          cancelText: '关闭'
        }
      )
      // }
    },
    handleFabClickedNew() {
      // console.log(this.mainChart.getOption())
      this.$dialog(
        () => import('./YjTableDialogNewCompare'),
        { jh: this.jh, date: moment(this.time).format('YYYY-MM-DD'), startime: this.time1, endTime: this.time2 },
        {
          title: `${this.jh}  ${this.time1 + '-' + this.time2}  预警信息`,
          width: document.body.offsetWidth * 0.75,
          height: document.body.offsetHeight * 0.85,
          centered: true,
          maskClosable: true,
          okButtonProps: { style: { display: 'none' } },
          cancelText: '关闭'
        }
      )
      // }
    },
    setWebsocketWarn(data) {
      if (this.warningList[1].show
        && data.length > 0
        && new Date().toDateString() === new Date(this.time).toDateString()) {

        const gcyjDataList = this.warningList[1].data
        const catogaryList = gcyjDataList.map(k => k.groupName)
        let newWarnCount = 0
        data.forEach(k => {
          k['endDate'] = moment(k.endTime).format('YYYY-MM-DD HH:mm:ss')
          k['startDate'] = moment(k.startTime).format('YYYY-MM-DD HH:mm:ss')
          k['description'] = k.des
          const catogaryIndex = catogaryList.findIndex(p => k.catogary === p)
          if (catogaryIndex >= 0) {
            const lastStartTime = _.last(gcyjDataList[catogaryIndex].children).startDate
            if (k.startDate > lastStartTime) {
              gcyjDataList[catogaryIndex].children.push(k)
              newWarnCount++
            }
          } else {
            const newWarnCatogary = { groupName: k.catogary, children: [k] }
            gcyjDataList.push(newWarnCatogary)
            catogaryList.push(k.catogary)
            newWarnCount++
          }
        })

        if (newWarnCount > 0) {
          this.initGCYJChart2(gcyjDataList)
          this.warningList[1].data = gcyjDataList
        }
      }
    },
    /**
     * 日期格式化
     */
    dateFormat(date, format) {
      format = format || 'yyyy-MM-dd hh:mm:ss'
      if (date !== 'Invalid Date') {
        let o = {
          'M+': date.getMonth() + 1, //month
          'd+': date.getDate(), //day
          'h+': date.getHours(), //hour
          'm+': date.getMinutes(), //minute
          's+': date.getSeconds(), //second
          'q+': Math.floor((date.getMonth() + 3) / 3), //quarter
          'S': date.getMilliseconds() //millisecond
        }
        if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
          (date.getFullYear() + '').substr(4 - RegExp.$1.length))
        for (let k in o)
          if (new RegExp('(' + k + ')').test(format))
            format = format.replace(RegExp.$1,
              RegExp.$1.length === 1 ? o[k] :
                ('00' + o[k]).substr(('' + o[k]).length))
        return format
      }
      return ''

    },
    allAjaxDataLoaded2(val) {
      if (val) {
        this.$bus.emit(vueBusEvents.topLeftYjListAsync, { key: val, type: 'add' })
        // this.onWarningChange({ checked: true })
      }
    },
    getNewData() {
      const params = { jh: this.jh }
      getAllDate(params).then((res) => {
        if (res.success) {
          let jsonTime = JSON.parse(res.result[res.result.length - 1])
          let newTime = jsonTime[0].time.substring(0, 19)
          if (this.realTime != newTime) {
            this.m_getDataByTime(this.jh, this.selectedConfigureKey, this.realTime, newTime).then((res) => {
              this.spinning = false
              this.realTime = newTime
              //  this.setChartTimeLoaded(this.jsonTimeLastTime,newTime)
              this.getWarningData()
            })
          }
        }
      })
    },
    openNotify() {
      Notification({
        title: '提示',
        dangerouslyUseHTMLString: true,
        message: '<i class="el-icon-loading"></i><span>数据渲染中</span>',
        showClose: false
      })
    },
    closeNotify() {
      Notification.closeAll()
    },
    setWorkCondition(item) {
      // console.log(item)
      this.workCondition.set(item.time, {
        operatingMode: item.operatingMode,
        motion: item.motion
      })
      // console.log(this.workCondition)

    },
    clearWorkConditions() {
      this.workCondition.clear()
    },
    insertBreaks(str) {
      if (str === null || str === undefined || str.length <= 0) {
        return ""
      }
      let len = 30
      let result = ''
      for (let i = 0; i < str.length; i += len) {
        result += str.slice(i, i + len) + '<br/>'
      }
      console.log('insertBreaks')
      console.log(result)
      return result
    },
    doClick() {
      let op = this.mainChart.getOption()
      op.series.forEach((item) => {
        if (item.id === csyjSeriesId) {
          console.log('csyjSeriesId ↓')
          console.log(item)
        }
      })
    },
    switchCsyj() {
      if (this.openCsyj) {
        let op = this.mainChart.getOption()
        console.warn(op)
        // lnamelnamelnamelname
        let arr = ['大钩负荷(kN)', '立管压力(MPa)', '扭矩(kN.m)', '总池体积(m³)']
        arr.forEach((lname) => {
          op.series.forEach(line => {
            const { yAxisIndex, type, name, data } = line

            if (type === 'line' && name === lname) {
              line.z = 100
              line.zlever = 100
              line.emphasis.scale = 0.01
              line.markPoint = {
                symbol: '',
                itemStyle: {
                  // opacity:0.3
                  // color: 'rgba(255, 0, 0, 0.9)' // 这里的 rgba 的第 4 个参数 0.5 表示 50% 的透明度
                },
                symbolSize: 20,
                symbolKeepAspect: true,
                symbolOffset: ['-5%', 0],
                data: [],
                emphasis: {
                  scale: 2
                }
              }
            }
          })
        })


        console.log('op')
        console.log(op)

        this.mainChart.setOption({ series: op.series })


        this.openCsyj = false
      } else {
        this.getCsyjData(this.jh)

        this.openCsyj = true
      }
    }
  },

  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
    }),
    gcyjTotalNum() {
      return this.lastAllGcyjAjaxData.length
    }
  },
  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) {
      let lastJH = this.jh
      const jh = val.split(',')[0]
      if (this.jh == jh || !this.inited) {
        if (this.serchTime) {

        } else {
          return
        }
      }

      this.runRecu = false
      this.jh = jh
      this.FzqkDeepth = []
      this.gcyjAllTime = []
      this.realTime = ''
      const _this = this
      this.getTime(jh).then(res => {
        if (this.serchTime) {
          this.time = this.serchTime
          this.allRealTime = []
        }
        console.warn("ie2c   sendMsg")
        sendMsg(JSON.stringify({ 'wellId': lastJH, 'isPull': false }))
        this.daoDataListTime = null
        this.yjRefreshResult = []
        this.yjLastRecord = undefined

        this.$nextTick(() => {
          setTimeout(() => {
            _this.initChart('jh')
          }, 500)
        })
      })
    },
    templateId(val) {
      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)
    },
    allAjaxDataLoaded(val) {
      if (val) {
        this.$bus.emit(vueBusEvents.topLeftYjListAsync, { key: val, type: 'add' })
        this.onWarningChange({ checked: true })
      }
    }
  }
}
</script>
<style>
.ant-tooltip {
  max-width: 1922px;
}
</style>
<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: 100%;
  border-left: 1px solid;
  border-right: 1px solid;
  background-color: #0a447d;
  height: 3px;
}

.header-chart {
  background: @darkColor;
  width: 100%;
  display: flex;
  height: 100%;
}

.headerOne {
  min-height: 175px;
  width: 120px;
  border: 1px solid;
  border-left: none;
  border-bottom: none;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
  flex: 0 0 120px;
}

.content {
  width: 100%;
  height: 100%;
  display: flex;
  background: @darkColor;
}

.header-content {
  flex: 1;
  border: 1px solid;
  margin-left: -1px;
  border-bottom: none;
}

.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: 0px solid;
}

.slick-item:hover {
  transform: scale(1.2);
  background: #d3d7d4;
  cursor: move;
}

.t-header {
  width: 100%;
  min-height: 20px;
  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 {
  width: 100%;
  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;
}

.floatingView {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}
</style>
