<template>
  <div class="app-container">
    <el-card class="box-carde">
      <div slot="header" class="clearfix">
        <span>人工干预设置</span>
      </div>
      <el-container>
        <el-header style="padding: 0px;display:flex;justify-content:space-between;align-items: center">
          <div style="display: inline">
            <el-date-picker
              v-if="activeName=='first'"
              v-model="dateTime"
              type="date"
              placeholder="选择日期"/>
            <el-date-picker
              v-else-if="activeName=='second'"
              v-model="dateTime"
              type="date"
              placeholder="选择日期"/>
            <el-date-picker
              v-if="activeName=='third'"
              v-model="dateTime2"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"/>
            <el-date-picker
              v-if="activeName=='fourth'"
              v-model="dateTime2"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"/>
            <el-select v-model="fileType" :filterable="true" placeholder="请选择文件类型" prop="fileType">
              <el-option
                v-for="item in fileTypeData"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
            </el-select>
            <el-button v-if="activeName=='first'" type="primary" size="mini" style="margin-left: 5px"
                       icon="el-icon-search" @click="searchEmp">搜索
            </el-button>
            <el-button v-if="activeName=='second'" type="primary" size="mini" style="margin-left: 5px"
                       icon="el-icon-search" @click="searchEmp">搜索
            </el-button>
            <el-button v-if="activeName=='third'" type="primary" size="mini" style="margin-left: 5px"
                       icon="el-icon-search" @click="searchEmp2">搜索
            </el-button>
            <el-button v-if="activeName=='fourth'" type="primary" size="mini" style="margin-left: 5px"
                       icon="el-icon-search" @click="searchEmp3">搜索
            </el-button>
            <el-button type="primary" size="mini" style="margin-left: 5px" icon="el-icon-plus"
                       v-if="activeName=='first'" @click="saveManual('form')">保存
            </el-button>
            <el-button type="primary" size="mini" style="margin-left: 5px" icon="el-icon-refresh"
                       v-if="activeName=='first'" @click="refresh">更新首页短期数据
            </el-button>
            <el-button type="primary" size="mini" v-if="activeName=='second'" @click="insertEvent"
                       style="margin-left: 5px"
                       :loading="btnLonding">新增
            </el-button>
            <el-button type="primary" size="mini" @click="saveNumber" style="margin-left: 5px"
                       :loading="btnLonding">负偏差(点击保存，范围0-0.1)->
            </el-button>
            <el-input-number type="number" size="mini" style="margin-left: 5px;width: 200px" :max="0.1" :min="0"
                             :step="0.01" :precision="2" placeholder="负偏差" v-model="numberValue"></el-input-number>
          </div>
        </el-header>

        <el-tabs v-model="activeName" type="card">
          <el-tab-pane label="点位设置" name="first">

            <div class="echartsDiv">

              <div id="MyShortTermRealCharts"/>

            </div>
            <div ref="testInput">
              <el-table
                v-loading="tableLoading"
                :data="form.slice((currentPage-1)*pageSize,currentPage*pageSize)"
                height="550px"
                border
                stripe
                size="mini"
                style="width: 20%">
                <el-table-column
                  prop="time1"
                  header-align="center"
                  align="center"
                  label="时间">
                </el-table-column>
                <el-table-column
                  :show-overflow-tooltip="true"
                  prop="data1"
                  header-align="center"
                  align="center"
                  label="预测值">
                  <template slot-scope="scope">
                    <vxe-input type="number" v-model="scope.row.data1" size="small" style="width:100%" min="0"
                               :max="capacity" placeholder="超过装机容量默认最大值"></vxe-input>
                  </template>
                </el-table-column>
              </el-table>
              <div style="display: flex;justify-content: space-between;margin: 2px;float: right;width: 15%">
                总条数：{{ this.totalCount }}
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="系数设置" name="second">
            <div style="padding-top: 10px">
              <vxe-table
                highlight-hover-row
                :keep-source="true"
                align="center"
                :loading="loading"
                v-loading="false"
                ref="xTable"
                auto-resize
                highlight-current-row
                border
                resizable
                show-overflow
                :data="tableData"
                :edit-config="{trigger: 'manual', mode: 'row',autoClear: false,icon:'none'}"
              >
                <vxe-table-column width="25%" field="interveneStartTime" title="开始时间"
                                  :edit-render="{name:'$input',attrs:{type:'text'}}">
                  <template v-slot:edit="{ row }">
                    <el-time-select
                      style="width: 100%"
                      v-model="row.interveneStartTime"
                      :picker-options="{
                        start: '00:00',
                        step: '00:15',
                        end: '23:45'
                      }"
                      placeholder="选择开始时间"
                    />
                  </template>
                  <template v-slot="{ row }">{{ timestampToTimeRatio(row.interveneStartTime) }}
                  </template>
                </vxe-table-column>
                <vxe-table-column width="25%" field="interveneEndTime" title="结束时间"
                                  :edit-render="{name:'$input',attrs:{type:'text'}}">
                  <template v-slot:edit="{ row }">
                    <el-time-select
                      style="width: 100%"
                      v-model="row.interveneEndTime"
                      :picker-options="{
                        start: '00:00',
                        step: '00:15',
                        end: '23:45'
                      }"
                      placeholder="选择结束时间"/>
                  </template>
                  <template v-slot="{ row }">{{
                      timestampToTimeRatio(row.interveneEndTime)
                    }}
                  </template>
                </vxe-table-column>
                <vxe-table-column field="ratio" width="25%" title="系数"
                                  :edit-render="{name:'$input',attrs:{type:'text'}}"></vxe-table-column>
                <vxe-table-column fixed="right" width="25%" title="操作">
                  <template v-slot="{ row }">
                    <template v-if="$refs.xTable.isActiveByRow(row)">
                      <el-button
                        style="padding: 3px 4px 3px 4px;margin: 2px"
                        size="mini"
                        icon="el-icon-edit"
                        :loading="saveLoding"
                        @click="saveRatioData(row)">保存
                      </el-button>
                      <el-button
                        style="padding: 3px 4px 3px 4px;margin: 2px"
                        size="mini"
                        icon="el-icon-edit"
                        @click="cancelRowEvent(row)">取消
                      </el-button>
                    </template>
                    <template v-else>
                      <el-button
                        style="padding: 3px 4px 3px 4px;margin: 2px"
                        size="mini"
                        icon="el-icon-edit"
                        @click="editRowEvent(row)"
                        :loading="btnLonding">编辑
                      </el-button>
                      <el-button
                        type="danger"
                        style="padding: 3px 4px 3px 4px;margin: 2px"
                        size="mini"
                        icon="el-icon-delete"
                        @click="removeEvent(row)"
                        :loading=btnLonding>删除
                      </el-button>
                    </template>
                  </template>
                </vxe-table-column>
              </vxe-table>
            </div>
          </el-tab-pane>
          <el-tab-pane label="人工干预记录列表" name="third">
            <div>
              <el-table
                v-loading="tableLoading"
                :data="emps.slice((currentPage-1)*pageSize,currentPage*pageSize)"
                height="500px"
                border
                stripe
                size="mini"
                style="width: 100%">
                <el-table-column
                  sortable="custom"
                  :formatter="fileTypeFormat"
                  prop="fileType"
                  align="center"
                  header-align="center"
                  label="文件类型"/>
                <el-table-column
                  :show-overflow-tooltip="true"
                  :formatter="dateFormat"
                  prop="operationalTime"
                  align="center"
                  header-align="center"
                  label="操作时间"/>
                <el-table-column
                  :show-overflow-tooltip="true"
                  prop="interveneTime"
                  :formatter="dateFormats"
                  align="center"
                  header-align="center"
                  label="干预数据日期"/>
                <el-table-column
                  :show-overflow-tooltip="true"
                  :formatter="operationalFormat"
                  prop="operationalStatus"
                  align="center"
                  header-align="center"
                  label="操作类型"/>
                <el-table-column
                  header-align="center"
                  align="center"
                  label="操作">
                  <template slot-scope="scope">
                    <el-button
                      style="padding: 3px 4px 3px 4px;margin: 2px"
                      size="mini"
                      icon="el-icon-document"
                      @click="showErrorInfo(scope.row)">查看内容
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div style="display: flex;justify-content: space-between;margin: 2px;float: right">
                <el-pagination
                  :current-page="currentPage"
                  :page-size="pageSize"
                  :page-sizes="[10, 25, 50, 100]"
                  :total="totalCount2"
                  background
                  layout="total, sizes, prev, pager, next, jumper"
                  @size-change="handleSizeChange"
                  @current-change="currentChange"/>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane v-if="this.eltype=='E33'" label="负偏差修改记录" name="fourth">
            <div>
              <el-table
                v-loading="tableLoading"
                :data="fpcTable.slice((currentPage-1)*pageSize,currentPage*pageSize)"
                height="500px"
                border
                stripe
                size="mini"
                style="width: 100%">
                <el-table-column
                  :show-overflow-tooltip="true"
                  :formatter="dateFormat"
                  prop="operationalTime"
                  align="center"
                  header-align="center"
                  label="操作时间"/>
                <el-table-column
                  :show-overflow-tooltip="true"
                  prop="operationalContext"
                  align="center"
                  header-align="center"
                  label="操作内容"/>
              </el-table>
              <div style="display: flex;justify-content: space-between;margin: 2px;float: right">
                <el-pagination
                  :current-page="currentPage"
                  :page-size="pageSize"
                  :page-sizes="[10, 25, 50, 100]"
                  :total="totalCount3"
                  background
                  layout="total, sizes, prev, pager, next, jumper"
                  @size-change="handleSizeChange"
                  @current-change="currentChange"/>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
        <el-form
          ref="addEmpForm"
          :model="emp"
          style="margin: 0px;padding: 0px;"
          label-width="100px">
          <el-dialog
            :close-on-click-modal="false"
            :visible.sync="dialogVisibleErrorInfo"
            title="具体信息"
            style="padding: 0px;"
            label-width="1px"
            width="1000px">
            <el-input
              v-model="emp.operationalContext"
              :rows="20"
              type="textarea"
              style="width: 100%"/>
            <span
              slot="footer"
              class="dialog-footer">
            <el-button
              size="mini"
              @click="cancelEidtEI">关 闭</el-button>
          </span>
          </el-dialog>
        </el-form>
      </el-container>
    </el-card>
  </div>
</template>
<script>
import echarts from 'echarts'

export default {
  data() {
    return {
      numberValue: '',
      saveLoding: false,
      showTable: true,
      btnLonding: false,
      ef: '',
      // 日期选择器
      dateTime: new Date(new Date().toLocaleDateString()),
      dateTime2: [new Date(new Date().toLocaleDateString()).getTime(), new Date(new Date().toLocaleDateString()).getTime() + 60 * 60 * 24 * 3 * 1000],

      // 场站信息存储对象
      elTableData: [],
      efiId: '',
      emps: [],
      fpcTable: [],
      dataList: [],
      keywords: '',
      jType: '',
      dialogTitle: '',
      dialogVisibleErrorInfo: false,
      loading: false,
      multipleSelection: [],
      downLoading: false,
      depTextColor: '#c0c4cc',
      totalCount: -1,
      totalCount2: -1,
      totalCount3: -1,
      currentPage: 1,
      pageSize: 100,
      dialogVisible: false,
      tableLoading: false,
      fileParsing: [],
      activeName: 'first',
      ultraValueData: [],
      shortValueData: [],
      realPowerValueData: [],
      capacityUnit: '',
      capacity: '',
      shortValueDate: [],
      fileType: '',
      fileTypeData: [
        {value: 0, label: '短期'},
        {value: 1, label: '超短期'}
      ],
      form: [{
        time1: '',
        data1: '',
        fileType: '',
        lastModifyTime: '',
      }],
      radioStartTime: '',
      radioEndTime: ',',
      tableData: [],
      isEdit: false,
      eltype: '',
      sysid: null,
      myChart: {},
      symbolSize: 20,
      chartsData: [],
      emp: {
        operationalContext: ''
      },
      option: {
        title: {
          text: '人工干预数据对比',
          left: '3%', // left 的值可以是像 20 这样的具体像素值，可以是像 '20%' 这样相对于容器高宽的百分比，也可以是 'left', 'center', 'right',如果 left 的值为'left', 'center', 'right'，组件会根据相应的位置自动对齐。
          top: '10px', // left 的值可以是像 20 这样的具体像素值，可以是像 '20%' 这样相对于容器高宽的百分比，也可以是 'left', 'center', 'right',如果 left 的值为'left', 'center', 'right'，组件会根据相应的位置自动对齐。
          right: 'auto', // right 的值可以是像 20 这样的具体像素值，可以是像 '20%' 这样相对于容器高宽的百分比。
          bottom: 'auto'// bottom 的值可以是像 20 这样的具体像素值，可以是像 '20%' 这样相对于容器高宽的百分比。
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 会出现横竖2个方向的指示器
            type: 'cross'
          },

        },
        // 图例名
        legend: {
          top: '2%',
          data: ['预测数据', '干预后预测数据']
        },
        grid: {
          top: '70px',
          left: '5%', // 图表距边框的距离
          right: '5%',
          bottom: '20%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          axisLine: {onZero: false}
        },
        yAxis: [{
          max: 30,
          min: 0,
          type: 'value',
          axisLine: {onZero: false}
        }],

        // 工具框，可以选择
        toolbox: {
          show: true,
          feature: {
            mark: {show: true},
            dataView: {show: true, readOnly: false},
            magicType: {show: true, type: ['line', 'bar']},
            restore: {show: true},
            saveAsImage: {show: true}
          }
        },
        dataZoom: [
          {
            type: 'slider',
            xAxisIndex: 0,
            filterMode: 'none'
          },
          {
            type: 'inside',
            xAxisIndex: 0,
            filterMode: 'none'
          }
        ],
        series: [
          {
            name: '干预后预测数据',
            id: 'a',
            type: 'line',
            smooth: true,
            color: ['red'],
            symbolSize: 10,
            data: [],
            max: 30
          },
          {
            name: '预测数据',
            id: 'b',
            type: 'line',
            smooth: true,
            color: ['orange'],
            symbolSize: 10,
            data: []
          }
        ]
      }

    }


  },
  created: function () {
    this.fileType = 0;
    this.getEl()
    this.draData()
    this.getRecordList()
  },
  mounted: function () {

    this.getRecordList()
    this.getRecordList2()
  },
  methods: {

    cancelEidtEI() {
      this.dialogVisibleErrorInfo = false
    },
    operationalFormat(row, column) {
      let belongTo = '未知的文件类型场站'
      for (let i = 0; i < this.emps.length; i++) {
        if (row.operationalStatus == "0") {
          belongTo = "点位新增"
        }
        if (row.operationalStatus == "1") {
          belongTo = "点位修改"
        }
        if (row.operationalStatus == "2") {
          belongTo = "点位删除"
        }
        if (row.operationalStatus == "3") {
          belongTo = "系数"
        }
        if (row.operationalStatus == "4") {
          belongTo = "系数删除"
        }
      }
      return belongTo
    },
    dateFormats(row, column) {
      let that = this;
      const date = row[column.property]
      if (date === undefined) {
        return ''
      }
      return this.$moment(date).format('YYYY-MM-DD')// 使用moment插件进行日期格式化
    },
    fileTypeFormat(row, column) {
      let belongTo = '未知的文件类型场站'
      for (let i = 0; i < this.emps.length; i++) {
        if (row.fileType == "0") {
          belongTo = "短期"
        }
        if (row.fileType == "1") {
          belongTo = "超短期"
        }
      }
      return belongTo
    },
    showErrorInfo(row) {
      this.emp.operationalContext = row.operationalContext
      this.dialogVisibleErrorInfo = true
    },
    draData() {

      this.option.series[0].data = this.chartsData2
      this.option.series[1].data = this.chartsData
      this.option.yAxis.max = this.capacity

      // 基于准备好的dom，初始化echarts实例
      this.myChart = echarts.init(document.getElementById('MyShortTermRealCharts'))
      var data = this.chartsData2
      var myChart = this.myChart
      let symbolSize = this.symbolSize;
      myChart.setOption(this.option)
      var form1 = this.form
      setTimeout(function () {
// Add shadow circles (which is not visible) to enable drag.
        myChart.setOption({
          graphic: data.map(function (item, dataIndex) {
            return {
              type: 'circle',
              position: myChart.convertToPixel('grid', item),
              shape: {
                cx: 0,
                cy: 0,
                r: 10
              },
              invisible: true,
              draggable: true,
              ondrag: function (dx, dy,) {

                onPointDragging(dataIndex, [item[0], dx.offsetY]);
              },
              onmousemove: function () {
                showTooltip(dataIndex);
              },
              onmouseout: function () {
                hideTooltip(dataIndex);
              },
              z: 100
            };
          })
        });
      }, 0);
      window.addEventListener('resize', updatePosition);
      myChart.on('dataZoom', updatePosition);

      function updatePosition() {
        myChart.setOption({
          graphic: data.map(function (item, dataIndex) {
            return {
              position: myChart.convertToPixel('grid', item)
            };
          })
        });
      }

      function showTooltip(dataIndex) {
        myChart.dispatchAction({
          type: 'showTip',
          seriesIndex: 0,
          dataIndex: dataIndex
        });
      }

      function hideTooltip(dataIndex) {
        myChart.dispatchAction({
          type: 'hideTip'
        });
      }

      function onPointDragging(dataIndex, pos,) {


        data[dataIndex][1] = myChart.convertFromPixel('grid', pos)[1].toFixed(2);

        if (myChart.convertFromPixel('grid', pos)[1].toFixed(2) > 30) {
          data[dataIndex][1] = 30
        }
        if (myChart.convertFromPixel('grid', pos)[1].toFixed(2) < 0) {
          data[dataIndex][1] = 0
        }
        form1[dataIndex].data1 = data[dataIndex][1]
        // Update data
        myChart.setOption({

          series: [
            {
              id: 'a',
              data: data,
            }
          ]
        });

        updatePosition()
      }
      this.form = form1
      updatePosition()
    },

    saveNumber() {
      this.btnLonding = true
      if (this.numberValue > 0.1 || this.numberValue < 0) {
        alert("无法保存，注意负偏差范围")
      } else {
        var row = {
          id: this.sysid,
          sysKey: "negative_deviation",
          sysValue: this.numberValue,
          describe: "浙江负偏差数字（注意只能填数字）"
        }

        this.$axios.post('/sysParameter/noSaveValidate', row).then(response => {
          this.btnLonding = false
          this.$message.success('设置成功！')
          var rowLog = {
            fileType: "2",
            operationalTime: new Date().getTime(),
            operationalContext: "修改负偏差为：" + this.numberValue,
            operationalStatus: 5,
            interveneTime: null
          }
          this.$axios.put('/manualInterventionLogController/saveForecastPowerShortTerm', rowLog).then(res => {

          }).catch((error) => {
            this.$emit('sendLoading', this.loading)
            this.$message.error('记录保存出错' + error)
          })

        }).catch((error) => {
          this.$emit('sendLoading', this.loading)
          this.$message.error('设置出错' + error)
        })
      }
      this.btnLonding = false
    },
    //取消编辑或添加操作
    cancelRowEvent(row) {
      this.saveLoding = false
      this.btnLonding = false
      const xTable = this.$refs.xTable
      xTable.clearActived().then(() => {
        // 还原行数据
        if (!this.isEdit) {
          //编辑
          xTable.revertData(row)
        } else {
          //新增
          xTable.remove(row)
        }
        this.isEdit = false
      })
    },
    //编辑框改变
    editRowEvent(row) {
      this.startTimeShow = false
      if (row.interveneStartTime < new Date().getTime()) {
        this.startTimeShow = true
      }
      this.checkSign = true
      this.btnLonding = true
      row.interveneStartTime = this.timestampToTimeRatio(row.interveneStartTime)
      row.interveneEndTime = this.timestampToTimeRatio(row.interveneEndTime)
      this.$refs.xTable.setActiveRow(row)
    },
    //删除数据
    removeEvent(row) {
      this.$XModal.confirm('您确定要删除该数据?').then(type => {
        if (type === 'confirm') {
          this.$axios.delete("/manualInterventionRatioController/delete/" + row.id).then(response => {
            this.$message.success(`删除成功`)
            this.queryManualInterventionRatio()
          })
        }
      })
    },
    //新增编辑框
    insertEvent() {
      this.isEdit = true
      this.startTimeShow = false
      this.showTable = true
      this.btnLonding = true
      this.checkSign = false
      this.$refs.xTable.insert()
        .then(({row}) => this.$refs.xTable.setActiveRow(row))
    },
    getEl() {
      this.$axios.get("/electricField/").then(res => {

        this.capacity = res.data.capacity
        this.queryManualIntervention()
        this.queryManualInterventionRatio()
        this.querySysParameter()
        this.getInterventionData()
      })
    },
    //获取干预对比数据
    getInterventionData() {
      const startTime = Math.round(this.dateTime)
      const endTime = Math.round(this.dateTime) + 60 * 60 * 24 * 1000 - 1
//预测的
      this.$axios.get('/manualInterventionController/getForecastPowerShortTermForDrawing/' + startTime + '/' + endTime + '/' + this.fileType).then((res) => {

        this.chartsData = res.data
        //人工干预之后的数据
        this.$axios.get('/manualInterventionLogController/queryForecastAndManualInterventionData/' + startTime + '/' + endTime + '/' + this.fileType).then((res) => {
          this.chartsData2 = res.data
          this.draData()
        })
      })
    },
    querySysParameter() {
      this.$axios.get('/sysParameter/sysParameterKey/negative_deviation').then((res) => {
        if (res.data != null) {
          this.numberValue = res.data.sysValue
          this.sysid = res.data.id
        }
      })
    },
    refreshShortTermHisData() {
      this.$XModal.confirm('您确定要更新首页短期数据?').then(type => {
        if (type === 'confirm') {
          this.$axios.get('/manualInterventionController/refreshSt',).then(res => {
            if (res.code == 0) {
              this.$message.success("更新成功！")
            }
          })
        }
      })
    },
    timestampToTimess(time) {
      const date = new Date(time)// 时间戳为10位需*1000，时间戳为13位的话不需乘1000
      const Y = date.getFullYear() + '-'
      const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      const D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' '
      const H = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + ':'
      const m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes())
      return Y + M + D + H + m
    },
    timestampToTimeRatio(time) {
      const date = new Date(time)// 时间戳为10位需*1000，时间戳为13位的话不需乘1000
      const H = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + ':'
      const m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes())
      return H + m
    },
    // 根据类型获取class
    queryManualIntervention() {
      this.tableLoading = true
      const a = [];
      for (var i = 0; i <= 23; i++) {
        if (i < 10) {
          a.push(this.timestampToTimes(Math.round(this.dateTime)) + "0" + i + ":00")
          a.push(this.timestampToTimes(Math.round(this.dateTime)) + "0" + i + ":15")
          a.push(this.timestampToTimes(Math.round(this.dateTime)) + "0" + i + ":30")
          a.push(this.timestampToTimes(Math.round(this.dateTime)) + "0" + i + ":45")
        } else {
          a.push(this.timestampToTimes(Math.round(this.dateTime)) + i + ":00")
          a.push(this.timestampToTimes(Math.round(this.dateTime)) + i + ":15")
          a.push(this.timestampToTimes(Math.round(this.dateTime)) + i + ":30")
          a.push(this.timestampToTimes(Math.round(this.dateTime)) + i + ":45")
        }
      }
      for (var i = 0; i < a.length; i++) {
        this.form[i] = {
          time1: a[i],
          data1: ""
        }
      }
      const startTime = Math.round(this.dateTime)
      const endTime = Math.round(this.dateTime) + 60 * 60 * 24 * 1000 - 1
      this.$axios.get('/manualInterventionController/queryManualInterventionData/' + startTime + '/' + endTime + '/' + this.fileType).then((res) => {
        for (var i = 0; i < res.data.length; i++) {
          for (var j = 0; j < this.form.length; j++) {
            if (this.timestampToTimess(res.data[i].interveneTime) == this.form[j].time1) {
              this.form[j].data1 = res.data[i].interveneData
            }
          }
        }

        this.totalCount = this.form.length
        this.tableLoading = false
      }).catch((error) => {
        this.$message.error('查询人工干预数据出错' + error)
      })
    },

    saveManual(formName) {
      this.tableLoading = true
      this.form[0].fileType = this.fileType
      this.form[0].lastModifyTime = Math.round(this.dateTime)
      this.$axios.put('/manualInterventionController/saveManualIntervention', this.form).then((res) => {
        this.$message.success(`保存成功`)
        this.queryManualIntervention()
        this.tableLoading = false
        this.getEl()
        this.draData()
      }).catch((error) => {
        this.$message.error('保存人工干预数据出错' + error)
      })

    },
    time_to_sec(time) {

      if (time !== null) {
        var s = "";
        var hour = time.split(":")[0];
        var min = time.split(":")[1];
        var sec = time.split(":")[2];
        s = Number(hour * 3600) + Number(min * 60) + Number(sec);
        return s;
      }
    },
    queryManualInterventionRatio() {
      this.loading = true
      this.saveLoding = false
      const startTime = Math.round(this.dateTime)
      const endTime = Math.round(this.dateTime) + 60 * 60 * 24 * 1000 - 1

      this.$axios.get('/manualInterventionRatioController/queryManualInterventionRatioData/' + startTime + '/' + endTime + '/' + this.fileType).then((res) => {
        this.tableData = res.data
        this.loading = false

      })
    },
    saveRatioData(row){
      this.saveLoding = true
      if(row.ratio == null || row.interveneStartTime ==null ||row.interveneEndTime == null||row.interveneStartTime >= row.interveneEndTime){
        this.saveLoding = false
        return this.$XModal.message({status: 'error', message: '校验不通过！'})
      }
      const formData = new FormData()
      formData.append('ratio', row.ratio)
      formData.append('interveneStartTime', this.dateTime.getTime()+this.time_to_sec(row.interveneStartTime+":00")*1000)
      formData.append('interveneEndTime',this.dateTime.getTime()+this.time_to_sec(row.interveneEndTime+":00")*1000)
      formData.append('interveneType', this.fileType)
      row.interveneStartTime = this.dateTime.getTime()+this.time_to_sec(row.interveneStartTime+":00")*1000
      row.interveneEndTime = this.dateTime.getTime()+this.time_to_sec(row.interveneEndTime+":00")*1000
      row.interveneType = this.fileType
      this.$refs.xTable.validate(valid => {
        if (valid) {
          this.$refs.xTable.clearActived().then(() => {
            this.loading = true
            this.$axios.post("/manualInterventionRatioController/saveManualInterventionRatio", row).then(response => {
              this.$XModal.message({status: 'warning', message: response.message})
              this.saveLoding = false
              this.queryManualInterventionRatio()
            }).catch((error) => {
              this.$message.error('保存失败，请检查是否设置过点位')
            })
          this.btnLonding = false
            this.loading = false
            this.queryManualInterventionRatio()
          })

        } else {
          this.$XModal.message({status: 'error', message: '校验不通过！'})
          this.saveLoding = false
          this.loading = false
        }

      })
    },
    // 时间格式化
    dateFormat(row, column) {
      const date = row[column.property]
      if (date === undefined) {
        return ''
      }
      return this.$moment(date).format('YYYY-MM-DD HH:mm:ss')// 使用moment插件进行日期格式化
    },
    timestampToTime(time) {
      const a = parseInt(time)
      const date = new Date(a) // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
      const Y = date.getFullYear() + '-'
      const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      const D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' '
      const H = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + ':'
      const m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes())
      return H + m
    },
    timestampToTimes(time) {
      const a = parseInt(time)
      const date = new Date(a) // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
      const Y = date.getFullYear() + '-'
      const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      const D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' '
      const H = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + ':'
      const m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes())
      return Y + M + D
    },
    searchEmp() {
      this.queryManualIntervention()
      this.queryManualInterventionRatio()
      this.getInterventionData()
    },
    searchEmp2() {
      this.getRecordList()
    },
    searchEmp3() {
      this.getRecordList2()
    },
    getRecordList() {
      if (this.dateTime2 == '' || this.dateTime2 == null) {
        alert('请选择时间')
        return
      }
      this.$axios.get('/electricField/').then((res) => {
        this.capacityUnit = 'mw'
        this.eltype = res.data.provinceEnum
        this.capacity = res.data.capacity
      })
      const formData = new FormData()
      const startTime2 = Math.round(this.dateTime2[0])
      const endTime2 = Math.round(this.dateTime2[1]) + 60 * 60 * 24 * 1000 - 1
      this.$axios.get('/manualInterventionLogController/queryManualInterventionLogData/' + startTime2 + '/' + endTime2 + '/' + this.fileType).then((res) => {
        this.emps = res.data
        this.totalCount2 = this.emps.length
      })
    },
    getRecordList2() {
      if (this.dateTime2 == '' || this.dateTime2 == null) {
        alert('请选择时间')
        return
      }
      this.$axios.get('/manualInterventionLogController/getByFileType/2').then((res) => {
        this.fpcTable = res.data
        this.totalCount3 = this.fpcTable.length
      })

    },


    refresh() {
      this.refreshShortTermHisData()
    },
    currentChange(currentChange) {
      this.currentPage = currentChange
      this.queryManualIntervention()
    },
    handleSizeChange(handleSizeChange) {
      this.pageSize = handleSizeChange
      this.queryManualIntervention()
    },
    changeTime(row, column) {
      return this.timestampToTime(row.time1)
    },
  }

}
</script>
<style>

.echartsDiv {
  float: left;
  width: 80%;
  height: 400px;
}

.el-dialog__body {
  padding-top: 0px;
  padding-bottom: 0px;
}

.slide-fade-enter-active {
  transition: all .8s ease;
}

.slide-fade-leave-active {
  transition: all .8s cubic-bezier(1.0, 0.5, 0.8, 1.0);
}

.slide-fade-enter, .slide-fade-leave-to {
  transform: translateX(10px);
  opacity: 0;
}

#MyShortTermRealCharts {
  width: 100%;
  height: 580px;
}
</style>
