<template>
 <div class="curve_statistical_box">
  <div v-show="show_org" class="station_tree">
   <div style="padding:5px;">
    <el-input
     size="small"
     v-model="search_data"
     prefix-icon="el-icon-search"
     placeholder="请输入关键字搜索"
    >
    </el-input>
   </div>
   <el-tree
    node-key="id"
    ref="zzj_tree"
    :data="station_tree"
    :default-expanded-keys="defaultShowNodes"
    :props="defaultProps"
    :highlight-current="isHighlight"
    :expand-on-click-node="true"
    :filter-node-method="filterNode"
   >
    <span slot-scope="{ node, data }">
     <span
      :class="{
       is_disabled: computed_is_disabled(data),
      }"
      :style="{ backgroundColor: data.id == click_id ? '#304156' : '' }"
      @click="handle_node_click(data, node)"
      >{{ data.name }}</span
     >
    </span>
   </el-tree>
  </div>
  <div class="charts">
   <div class="times">
    <i
     :class="[show_org ? 'el-icon-s-fold' : 'el-icon-s-unfold', 'show_org']"
     @click="show_org = !show_org"
    ></i>
    <el-date-picker
     v-model="times"
     size="small"
     :clearable="false"
     type="datetimerange"
     style="width:280px;margin:0px 5px;"
     value-format="timestamp"
     format="yyyy-MM-dd"
     @change="get_has_records"
     range-separator="至"
     start-placeholder="开始日期"
     end-placeholder="结束日期"
    >
    </el-date-picker>
    <el-button
     style="margin-left:8px;"
     icon="el-icon-search"
     type="primary"
     size="small"
     @click="get_has_records"
     >查询</el-button>
     <el-button
     style="margin-left:8px;"
     type="primary"
     size="small"
     @click="alarm_warn_setting('dw_alarm_low_drop')"
     >保持力报警设置</el-button
    >
    <el-button
     style="margin-left:8px;"
     icon="el-icon-download"
     type="primary"
     size="small"
     v-debounce="export_img"
     >导出图片</el-button
    >
    <el-button style="margin-left: 5px;" type="primary" size="mini" @click="localtion_history">历史数据</el-button>
   </div>
   <div
    v-loading="loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(31, 31, 31, 0.6)"
    class="charts_box"
    id="export_img"
   >
    <div ref="one" id="one" class="curve"></div>
   </div>
  </div>
   <!-- 转换阻力设置 -->
   <div class="dw_alarm_low_drop">
   <el-dialog
    width="400px"
    title="保持力报警配置"
    :lock-scroll="true"
    :show-close="true"
    @close="val => cancel_setting(val, 'dw_alarm_low_drop')"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :visible.sync="dialogVisible"
   >
   <div class=" position_left" style="text-align: left;">
      <span class="mark"></span>状态&nbsp;&nbsp;&nbsp; 
      <el-radio-group  v-model="retension_enable">
      <el-radio :label=true>启用</el-radio>
      <el-radio :label=false>未启用</el-radio>
     </el-radio-group>
     </div>
     <div class="position_top_20 position_left" style="text-align: left;">
      <span class="mark"></span>位置&nbsp;&nbsp;&nbsp;
      <el-radio-group  v-model="retension_posi" @change="posi_change()">
      <el-radio :label="100">定位</el-radio>
       <el-radio :label="101">反位</el-radio>
      </el-radio-group>
     </div>

     <div class="position_top_20 position_left" style="text-align: left;">
      <span class="mark">*</span>最低报警值:
      <!-- <el-input style="width:200px;margin-left: 58px;" v-model="dw_alarm_low_drop" oninput="value=value.replace(/^0|[^0-9]/g,'')" size="small" maxlength="5" placeholder="请输入0~40000之间的数字" ></el-input> -->
      <el-input style="width:180px;" v-model="dw_alarm_low_drop"  size="small" maxlength="7" placeholder="请输入-100000~100000之间的数字" ></el-input>
     </div>
     <!-- <div class="position_top_20">
      <span class="mark">*</span>下降超限百分比(%):
     <el-input style="width:200px" v-model="alarm_low_percent" oninput="value=value.replace(/^0|[^0-9]/g,'')" size="small" maxlength="2" placeholder="请输入5~95之间的数字"></el-input>
     </div>

     <div class="position_top_20">
      <span class="mark">*</span>上升超限百分比(%):
     <el-input style="width:200px" v-model="alarm_high_percent" oninput="value=value.replace(/^0|[^0-9]/g,'')" size="small" maxlength="2"  placeholder="请输入5~95之间的数字"></el-input>
     </div> -->
    <span slot="footer" class="dialog-footer">
     <el-button size="small" @click="cancel_setting('convert_resist')">关 闭</el-button>
     <el-button
      v-if="$store.state.admin && $store.state.backend_type == 1"
      size="small"
      type="primary"
      @click="save_settting()"
      >保 存</el-button
     >
    </span>
   </el-dialog>
  </div>
 </div>
</template>

<script>
/**
 * 增加温度
 */
import { retension_curve, commit_record } from '../api'
import curveRetentivityOption from '../chart/curve-retentivity'
import { today } from '../utils/time'
import { exportImage } from '../plugin/html2canvas' // 引入
import { treeCorrelation } from '../mixins/treeCorrelation'
import {get_retension_force,set_retension_force} from '../api'
export default {
 name: 'CurveRetentivity',
 mixins: [treeCorrelation],
 data() {
  return {
   send_data: {
    type: 1,
    mo: '',
    mp: '',
    name: '',
    time: '',
    end_time: '',
   }, //获取阻力曲线图
   dialogVisible:false,
   retension_enable: true, // 保持力是否启用
   retension_posi: 100,
   dw_alarm_low_drop: '', // 最低报警值
   alarm_low_percent: '', // 下降超限百分比
   alarm_high_percent: '', // 上升超限百分比
   times: [],
   click_id: '', //确认是否激活
   curve_data: new Object(), // 曲线数据
   loading: false,
   myCharts: null,
   show_org: true, //是否显示机构
   /**曲线数据*/
   one_curve: {},
   has_data: false, // 当天是否有数据
   // 浏览记录
   commit_data: {
    module: 9,
    dura: '', // 必传
    analyze_type: 1, // 必传
    station: '', // 必传
    station_name: '', // 必传
    mo: '', // 必传
    mo_name: '', // 必传
    mp: '', // 必传
    mp_name: '', // 必传
    start_time: '', // 必传
    end_time: '',
    time: '', // 必传
    name: this.$store.state.name, // 必传
    username: this.$store.state.user_name, // 必传
   },
   res_time: null,
  }
 },
 methods: {
  // 位置变化
  posi_change() {
    if (!this.click_id) return this.$message.warning('请先选择设备...')
     let [mo, mp] = this.click_id.split('.')
     let send_data = { mo, mp, posi: this.retension_posi }
     get_retension_force(send_data)
      .then(res => {
       this.retension_enable = res.enable;
       this.dw_alarm_low_drop = res.dw_alarm_low_drop;
       this.alarm_high_percent = res.alarm_high_percent;
       this.alarm_low_percent = res.alarm_low_percent;
      })
      .catch(e => {
       console.log(e)
      })
  },
  // 导出Image
  export_img() {
   if (!this.send_data.mo || !this.send_data.mp)
    return this.$message({
     type: 'warning',
     showClose: true,
     duration: 1500,
     message: '请选择重要信息',
    })
   if (!this.has_data)
    return this.$message({
     type: 'warning',
     showClose: true,
     duration: 1500,
     message: '无数据，无法导出...',
    })
   let self_node = this.$refs.zzj_tree.getNode(`${this.send_data.mo}.${this.send_data.mp}`) // 自身所在的node
   let parent_name = self_node.parent.data.name || self_node.parent.data.id // 上级node的name或id
   let file_name = `${parent_name}_${this.send_data.name.replace('.', '')}-${this.$dayjs(
    this.one_curve.time * 1000
   ).format('YYYY_MM_DD')}` // 文件名
   let target_dom = document.getElementById('export_img') // 需要导出的dom元素
   exportImage(file_name, target_dom) // 调用导出Image方法
   return this.$message({
    type: 'success',
    showClose: true,
    duration: 1500,
    message: '导出成功!',
   })
  },
  // 前往历史数据
  localtion_history() {
   if (!this.send_data.mo || !this.send_data.mp)
    return this.$message({
     type: 'warning',
     showClose: true,
     duration: 1500,
     message: '请选择重要信息',
    })
   let route_data = {
    name: 'force',
    query: {
     tag: this.click_id,
     time: this.times[0] / 1000,
     endtime: this.times[1] / 1000 + 24 * 60 * 60 - 1,
     title: this.send_data.name,
    },
   }
   this.$router.push(route_data)
   this.$store.state.defaultActive = '/layout/force'
   this.$store.commit('handle_save_defaultActive', '/layout/force')
  },
  // 点击树结构
  handle_node_click(data, node) {
   if (data.type != 'mo.mp') return
   if (!data['IMEI'] && this.$store.state.backend_type == 1)
    return this.$message({
     type: 'warning',
     showClose: true,
     duration: 1500,
     message: '未绑定设备...',
    })
   /**浏览记录*/
   if (this.res_time) {
    this.commit_data.dura = +new Date() - this.res_time
    let copy_data = _.cloneDeep(this.commit_data)
    this.send_record(copy_data)
   }
   this.res_time = +new Date()
   this.commit_data.station = node.parent.data.id
   this.commit_data.station_name = node.parent.data.name
   let mo_mp = data.id.split('.')
   let mo_mp_name = data.name.split('.')
   this.commit_data.mo = mo_mp[0]
   this.commit_data.mp = mo_mp[1]
   this.commit_data.mo_name = mo_mp_name[0]
   this.commit_data.mp_name = mo_mp_name[1]
   this.commit_data.time = +new Date()
   this.commit_data.start_time = this.times[0]
   this.commit_data.end_time = this.times[1]
   /**结束*/
   this.click_id = data.id
   this.send_data.mo = mo_mp[0]
   this.send_data.mp = mo_mp[1]
   this.send_data.name = data.name
   if (this.myCharts) {
    this.myCharts.dispose()
    this.myCharts = null
   }
   //    this.loading = true
   setTimeout(() => {
    return this.get_curve_data()
   }, 16)
  },
  // 获取曲线前先看看有没有浏览记录
  get_has_records() {
   if (this.res_time) {
    this.commit_data.dura = +new Date() - this.res_time
    let copy_data = _.cloneDeep(this.commit_data)
    this.send_record(copy_data)
   }
   return this.get_curve_data()
  },
  // 获取曲线数据
  get_curve_data() {
   if (!this.send_data.mo || !this.send_data.mp)
    return this.$message({
     type: 'warning',
     showClose: true,
     duration: 1500,
     message: '请选择重要信息',
    })
   if (this.times[1] - this.times[0] > 7 * 24 * 60 * 60 * 1000)
    return this.$message.warning('最多不超过7天，请重新选择范围')
   this.send_data.time = this.times[0] / 1000
   this.send_data.end_time = this.times[1] / 1000 + 24 * 60 * 60 - 1
   this.loading = true
   let send_data = _.cloneDeep(this.send_data)
   retension_curve(send_data)
    .then(res => {
     if (send_data.name != res.name) return
     this.loading = false
     this.one_curve = {}
     let one_has_data = res.data.curve_data.every(item => item.data.length == 0)
     if (one_has_data) {
      this.has_data = false
      this.$message({
       type: 'warning',
       showClose: true,
       duration: 1500,
       message: '无数据...',
      })
     } else {
      this.has_data = true
      res.data.name = res.name
      res.data.unit = res.unit
      res.data.time = send_data.time
      res.data.endtime = send_data.end_time
      this.one_curve = _.cloneDeep(res.data)
     }
     this.draw_position_curve()
    })
    .catch(e => {
     console.log(e)
     this.loading = false
     this.has_data = false
     this.one_curve = {}
     this.draw_position_curve()
    })
  },
  // 第一个图
  draw_position_curve() {
   let myCharts = this.$echarts.getInstanceByDom(document.getElementById('one'))
   if (myCharts == null) {
    myCharts = this.$echarts.init(document.getElementById('one'))
   }
   let option = curveRetentivityOption(this.one_curve)
   myCharts.setOption(option, true)
   window.addEventListener('resize', () => {
    myCharts.resize()
   })
   const resizeOb = new ResizeObserver(entries => {
    for (const entry of entries) {
     this.$echarts.getInstanceByDom(entry.target).resize()
    }
   })
   resizeOb.observe(this.$refs.one)
  },
  // 点击获取预报警值
  alarm_warn_setting(type) {
    let send_data = {};
    if (!this.click_id) return this.$message.warning('请先选择设备...')
     let [mo, mp] = this.click_id.split('.')
     send_data = { mo, mp, posi: this.retension_posi }
     get_retension_force(send_data)
      .then(res => {
       this.retension_enable = res.enable;
       this.dw_alarm_low_drop = res.dw_alarm_low_drop;
       this.alarm_high_percent = res.alarm_high_percent;
       this.alarm_low_percent = res.alarm_low_percent;
       this.dialogVisible = true;
      })
      .catch(e => {
       console.log(e)
      })
     return
  },// 关闭预告警设置
  cancel_setting(type) {
     this.dialogVisible= false;
     this.retension_enable= true; 
     this.retension_posi=100;
     this.dw_alarm_low_drop= ''; 
     this.alarm_low_percent= ''; 
     this.alarm_high_percent= ''; 
  },// 保存预告警设置
  save_settting() {
    if (!this.click_id) return this.$message.warning('请先选择设备...')
   let dw_alarm_low_drop = '';
      let alarm_low_percent = '';
      let alarm_high_percent= '';
      let regex  = /^-?\d+$/;
      if (this.dw_alarm_low_drop) {
        if(!regex.test(this.dw_alarm_low_drop) || Math.abs(this.dw_alarm_low_drop) > 100000){
          return this.$message.warning('最低报警值要求：-100000~100000之间的数字');
        }else{
          dw_alarm_low_drop = Number(this.dw_alarm_low_drop);
        }        
      }
      if (this.alarm_low_percent ){
        if(this.alarm_low_percent < 5 || this.alarm_low_percent > 95){
          return this.$message.warning('下降超限百分比要求：5~95之间的数字');
        }else{
          alarm_low_percent= Number(this.alarm_low_percent);
        }        
     }
     if (this.alarm_high_percent ){
      if(this.alarm_high_percent < 5 || this.alarm_high_percent > 95){
        return this.$message.warning('上升超限百分比要求：5~95之间的数字');
      }else{
        alarm_high_percent= Number(this.alarm_high_percent);  
      }      
       
     }
     let [mo, mp] = this.click_id.split('.')

     let send_data = {
      mo,
      mp,
      posi: this.retension_posi,
      conf: {
       enable: this.retension_enable,
       dw_alarm_low_drop:dw_alarm_low_drop,
       alarm_low_percent:alarm_low_percent,
       alarm_high_percent:alarm_high_percent,
      },
     }
     set_retension_force(send_data)
      .then(res => {
       return this.$message.success('设置成功...')
      })
      .catch(e => {
       console.log(e)
      })
   },
  // 发送浏览记录
  send_record(commit_data) {
   if (commit_data.dura <= 500) return
   if (!commit_data.station || !commit_data.station_name) return
   if (!commit_data.mo || !commit_data.mo_name) return
   if (!commit_data.mp || !commit_data.mp_name) return
   commit_record([commit_data])
    .then(res => {})
    .catch(e => {})
  },
  // 离开界面时
  leave_page() {
   if (!this.res_time) return
   this.commit_data.dura = +new Date() - this.res_time
   let copy_data = _.cloneDeep(this.commit_data)
   return this.send_record(copy_data)
  },
  // 获取默认时间
  get_time() {
   let times = this.$dayjs().format('YYYY-MM-DD 00:00:00')
   let unix_time = this.$dayjs(times).unix() * 1000
   this.times = [unix_time - 24 * 60 * 60 * 1000, unix_time]
   this.draw_position_curve()
  },
 },
 mounted() {
  this.get_time()
 },
 activated() {
  if (this.click_id) {
   this.res_time = +new Date()
  } else {
   this.res_time = null
  }
 },
 deactivated() {
  this.leave_page()
 },
 beforeDestroy() {
  this.leave_page()
 },
}
</script>

<style lang="scss">
.station_tree {
 .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background-color: transparent;
 }
}
</style>
<style lang="scss" scoped>
@import '../../static/css/curve-retentivity.scss';
</style>
