<template>
  <div class="main">
    <!-- 左侧盒子 -->
    <div class="left">
      <!-- 第一排盒子 -->
      <div class="PlcCar">
        <!-- 机器人状态 -->
        <div class="PlcStatus">
          <SubTitle words="机器人状态" />
          <div class="bottom">
            <div class="list">
              <div class="plcConnect">
                <PannelItem words="PLC通讯" :status="robotInfoVo.plcState ? '正常' : '异常'" :flag="robotInfoVo.plcState" />
              </div>
              <div class="plcModel">
                <PannelItem words="机器人模式" :status="PlcMode" :flag="robotInfoVo.exchangeMode" />
              </div>
            </div>
            <div class="status">
              <div class="circle"><img :src="require(`${PlcState[0]}`)"></div>
              <div class="descript">机器人状态</div>
              <div class="frame">
                <span :class="PlcState[1]" style="display: inline-block;margin-right: 5px;">{{PlcState[2] || '—'}}</span>
                <template v-if="errordata.length>0">
                  <span v-for="item in errordata" class="errordata" :title="item.alarmName" :key="item.alarmCode">{{ item.alarmCode }}</span>
                </template>
                <div class="shinning"></div>
              </div>
            </div>
            <PannelItem words="急停状态" :status="robotInfoVo.emergencyMode==1 ? '急停' : robotInfoVo.emergencyMode==0?'未急停':'—'" :flag="robotInfoVo.emergencyMode==0" />
            <PannelItem words="暂停状态" :status="robotInfoVo.pause==1 ? '暂停' :robotInfoVo.pause==0? '未暂停':'—'" handle="true" :flag="robotInfoVo.pause==0" />
          </div>
        </div>
        <!-- 机器人状态结束、车辆状态开始 -->
        <div class="CarStatus">
          <SubTitle words="车辆信息" flag="true" @ShowCarline="ShowCarline" :CarNum="vehicleInfo.onlineNum" />
          <div class="bottom">
            <div class="list">
              <div class="carLeft">
                <PannelTitle words="车牌号" :value="vehicleInfo.plate ? vehicleInfo.plate : '—'" Isblue="true" @refreshCar="refreshCar" @HandleEditPlate="HandleEditPlate" />
                <PannelItem words="车牌识别器" :status="vehicleInfo.plateComState ? '正常' : '异常'" :flag="vehicleInfo.plateComState" />
                <PannelItem words="车辆到位" :status="vehicleInfo.sensorState ? '已到位' : '未到位'" :flag="vehicleInfo.sensorState" />
                <PannelItem words="鉴权状态" :status="vehicleInfo.authState ? '已通过' : '未通过'" :flag="vehicleInfo.authState" />
              </div>
              <div class="carRight">
                <div class="statusTop">
                  <PannelTitle words="车辆VIN码" :value="vehicleInfo.vin ? vehicleInfo.vin : '—'" Isblue="true" />
                </div>
                <div class="statusLeft">
                  <PannelItem words="车牌识别" :status="vehicleInfo.plateState ? '成功' : '未识别'" :flag="vehicleInfo.plateState" />
                  <PannelItem words="连接状态" :status="vehicleInfo.conState ? '已连接' : '未连接'" :flag="vehicleInfo.conState" />
                </div>
                <div class="statusRight">
                  <!-- <PannelTitle words="车辆里程" :value="vehicleInfo.mileage ? vehicleInfo.mileage+'km' : '—'" Isblue="true" /> -->
                  <PannelTitle words="下电状态" :value="vehicleInfo.batteryState==null ? '—':vehicleInfo.batteryState?'已下电':'未下电'" :flag="vehicleInfo.batteryState"/>
                  <PannelTitle words="解锁状态" :value="vehicleInfo.lockState==null ? '—':vehicleInfo.lockState?'已上锁':'已解锁'" :flag="vehicleInfo.lockState==false"/>
                </div>
                <PannelTitle words="" value="" :isline="true" :flag="vehicleInfo.lockState" handle="true" />
              </div>
            </div>
          </div>
        </div>
        <!-- 车辆状态结束 -->
      </div>
      <!-- 第一排盒子结束 -->
      <!-- 任务进度 -->
      <div class="Progress">
        <SubTitle words="任务进度" :swapId="swapProcess.swapId" />
        <div class="TaskFoot">
          <!-- 换电 -->
          <div class="Exchange" v-if="!TcInfoVo.sourceCode || !TcInfoVo.targetCode">
            <div class="Progress-btn">换电</div>
            <div class="Exchange-status">
              <PannelTitle words="换电状态" :value="swapProcess.swapState ? '换电中' : '未换电'" flag="1" />
              <PannelTitle words="环节步骤" :value="swapProcess.stepDescription || '—'" flag="1" />
              <PannelTitle words="解锁状态" :value="swapIsLock" flag="1" />
            </div>
            <div class="Exchange-times">
              <PannelTitle :words="swapProcess.batteryCode ? swapProcess.batteryCode+'号仓位' : '*'+'号仓位'" :value="swapProcess.chargerState ? '充电中' :'未充电'" Isblue="true" />
              <div class="lock">
                <span>{{ swapProcess.forbidLockState ? '锁止已屏蔽' : ''}}</span>
                <span class="time">换电时长：<font>{{PlcChangerTime || '—'}}</font></span>
              </div>
              <div class="percent">
                <div class="percent-bar">
                  <div class="bar">
                    <div class="bar-green" :style="{ 'width': swapPercent + '%' }">
                      <div class="bar-percent" :class="[swapPercent < 10 ? 'bar-ten' : '']">{{ swapPercent }}%</div>
                    </div>
                  </div>
                </div>
                <div class="count-step">
                  <font>{{swapProcess.step || 0}}</font>/{{swapProcess.plcStep || 0}}
                </div>
              </div>
              <div class="lock">
                <span></span>
                <span class="time">机器人工作时长：<font>{{PlcWorkTime || '—'}}</font></span>
              </div>
            </div>
            <div class="Exchange-battery">
              <div class="character"></div>
              <div class="handle-battery">
                <button class="leftBtn" :class="[BatteryFullStatus ? 'active' : '']" type="primary"
                  @click="ChangeBattery(1)">满电换电电池</button>
                <button class="leftBtn Rbtn" :class="[BatteryFullStatus ? '' : 'active']" type="primary"
                  @click="ChangeBattery(0)">亏电换电电池</button>
              </div>
              <div class="battery-detail">
                <div class="detail-text">
                  <div class="text">电池编号</div>
                  <div class="frame">
                    <span class="frameText">{{BatteryFullStatus?batteryInfo.targetSn || '—':batteryInfo.sourceSn || '—'}}</span>
                    <div class="shinning"></div>
                  </div>
                </div>
                <div class="detail-text">
                  <div class="text">SOC</div>
                  <div class="frame">
                    <span class="frameText">{{BatteryFullStatus?batteryInfo.targetSoc:batteryInfo.sourceSoc}}%</span>
                    <div class="shinning"></div>
                  </div>
                </div>
                <div class="detail-text">
                  <div class="text">SOH</div>
                  <div class="frame">
                    <span class="frameText">{{BatteryFullStatus?batteryInfo.targetSoh:batteryInfo.sourceSoh}}%</span>
                    <div class="shinning"></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <!-- 换电结束 -->
          <!-- 消防换仓 -->
          <div class="Exchange" v-if="XfInfoVo.xfTargetCode">
            <div class="Progress-btn Fire">消防换仓</div>
            <div class="Fire-status">
              <PannelTitle words="仓位" :value="XfInfoVo.xfTargetCode+'号仓'" :flag="true" />
              <PannelTitle words="动作流程" :value="XfInfoVo.actionFlow || '—'" :flag="true" />
              <PannelTitle words="工作时长" :value="PlcChangeFileStore || '—'" :flag="true" />
            </div>
            <div class="Exchange-battery">
              <div class="character"></div>
              <div class="handle-battery">
                <button class="info-btn" type="primary">电池信息</button>
                <span>{{XfInfoVo.chargerState?'充电中':'未充电'}}</span>
              </div>
              <div class="battery-detail">
                <div class="detail-text">
                  <div class="text">电池编号</div>
                  <div class="frame">
                    <span class="frameText">{{XfInfoVo.sn || '—'}}</span>
                    <div class="shinning"></div>
                  </div>
                </div>
                <div class="detail-text">
                  <div class="text">SOC</div>
                  <div class="frame">
                    <span class="frameText">{{XfInfoVo.soc | PercentFilter}}</span>
                    <div class="shinning"></div>
                  </div>
                </div>
                <div class="detail-text">
                  <div class="text">SOH</div>
                  <div class="frame">
                    <span class="frameText">{{XfInfoVo.soh | PercentFilter}}</span>
                    <div class="shinning"></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <!-- 消防换仓结束 -->
          <!-- 调仓 -->
          <div class="Exchange" v-if="TcInfoVo.sourceCode && TcInfoVo.targetCode">
            <div class="Progress-btn">调仓</div>
            <!-- <div class="Exchange-status">
              <PannelTitle words="仓位" value="8号仓" style="padding-left: 32px;" :flag="true" />
              <PannelTitle words="动作流程" value="抓取电池" :flag="true" />
            </div> -->
            <div class="Change-status">
              <div class="change-top">
                <PannelTitle words="仓位" :value="TcInfoVo.sourceCode+'号仓'" :flag="true" />
                <span class="jiantou"><img src="./assets/jiantou.gif"></span>
                <PannelTitle words="仓位" :value="TcInfoVo.targetCode+'号仓'" :flag="true" />
              </div>
              <PannelTitle words="动作流程" :value="TcInfoVo.actionFlow || '—'" :flag="true" />
              <PannelTitle words="工作时长" :value="PlcChangeStore || '—'" :flag="true" />
            </div>
            <div class="Exchange-battery">
              <div class="character"></div>
              <div class="handle-battery">
                <button class="info-btn" type="primary">电池信息</button>
                <span>{{TcInfoVo.chargerState?'充电中':'未充电'}}</span>
              </div>
              <div class="battery-detail">
                <div class="detail-text">
                  <div class="text">电池编号</div>
                  <div class="frame">
                    <span class="frameText">{{TcInfoVo.sn || '—'}}</span>
                    <div class="shinning"></div>
                  </div>
                </div>
                <div class="detail-text">
                  <div class="text">SOC</div>
                  <div class="frame">
                    <span class="frameText">{{TcInfoVo.soc | PercentFilter}}</span>
                    <div class="shinning"></div>
                  </div>
                </div>
                <div class="detail-text">
                  <div class="text">SOH</div>
                  <div class="frame">
                    <span class="frameText">{{TcInfoVo.soh | PercentFilter}}</span>
                    <div class="shinning"></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <!-- 调仓结束 -->
        </div>
      </div>
      <!-- 任务进度结束 -->
      <!-- 选电模式 -->
      <div class="getModel">
        <div class="top">
          <div class="title">
            <div class="icon"></div>
            <div class="name">选电模式</div>
            <div class="btnList">
              <div class="handle-model">
                <button class="leftBtn" :class="[pamars.batChooseMode===0 ? 'active' : '']" @click="ChangeModel(0)"
                  type="primary">自动选电</button>
                <button class="leftBtn Rbtn" :class="[pamars.batChooseMode===1 ? 'active' : '']" @click="ChangeModel(1)"
                  type="primary">手动选电</button>
              </div>
              <div class="handle-group">
                <el-button type="primary" @click="BeginChangePower">开始换电</el-button>
                <el-button type="primary" @click="HandleChangeStore">调仓</el-button>
                <el-button type="primary" @click="HandleFireStore">消防换仓</el-button>
                <el-button type="primary" @click="HandleIsLock(1)">锁止屏蔽</el-button>
                <el-button type="primary" @click="HandleIsLock(0)">锁止放开</el-button>
                <el-button type="primary" @click="PausePLC(1)">急停</el-button>
                <el-button type="primary" @click="PausePLC(6)">中止</el-button>
                <!-- <el-button type="primary">中止</el-button> -->
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 选电模式结束 -->
      <!-- 仓位/电池 -->
      <div class="store-battery">
        <div class="line"></div>
        <div class="store-container">
          <div class="title">
            <div class="icon"></div>
            <div class="name">仓位/电池</div>
            <div class="battery-count">
              <div class="circle"><img src="./assets/green.png"></div>
              <div class="descript">可用电池</div>
              <div class="count-number">{{ availableBatteries || 0}}</div>
            </div>
            <div class="battery-btn">
              <el-button class="active" @click="HandleFreeze(1)">冻结</el-button>
              <el-button @click="HandleFreeze(0)">解冻</el-button>
            </div>
          </div>
          <div class="storeList">
            <!-- 电池列表信息 -->
            <BatteryInfo v-for="(item, index) in storeInfoList" 
              :soc="item.soc"
              :alarmState="item.alarmState"
              :chgAlarmState="item.chargerInfoVo.alarmState" 
              :chgState="item.chargerInfoVo.chgState" 
              :chgEstimatedTime="item.chargerInfoVo.chgEstimatedTime"
              :key="index"
              :storeState="item.storeState" 
              :storeCode="item.storeCode" 
              :freezeState="item.freezeState"
              :comState="item.comState"
              :chargerComState="item.chargerInfoVo.comState"
              :BatterySelectAllArr="BatterySelectAllArr" 
              :BatterySelected="BatterySelected"
              :IsSelect="BatteryIsSelectArr[index]" />
            <!-- 电池信息结束 -->
          </div>
        </div>
      </div>
      <!-- 仓位/电池结束 -->
    </div>
    <!-- 左侧盒子结束 -->
    <!-- 换电日志 -->
    <div class="right">
      <div class="video"><canvas id="video-1"/></div>
      <div class="Exchange-log">
        <div class="logHead">
          <div class="top">
            <div class="title">
              <div class="icon"></div>
              <div class="name">换电日志</div>
              <!-- <div class="logDescript">通过人工手动解锁, PLC触摸平板点击继续换电</div> -->
            </div>
          </div>
        </div>
        <div class="logFoot">
          <LogList v-for="item in logList" :key="item.id" :item="item" />
        </div>

      </div>
    </div>
    <!-- 换电日志结束 -->
    <!--实时车辆弹窗-->
    <div class="onlineManage">
      <el-dialog title="实时车辆连接信息" :visible.sync="dialogCarlineVisible" :destroy-on-close="true">
        <div class="charge-table-bottom">
          <el-table :data="CarlineList" :header-cell-style="{
              background: '#1d283e',
              borderColor: '#2f3c86',
              height: '0.45rem',
              lineHeight: '0.45rem',
              color: 'white',
              fontSize: '0.2rem',
            }" 
            stripe 
            fit 
            style="width: 100%">
            <el-table-column label="车牌号">
              <template slot-scope="{row}">
                <div class="iscar">
                  <span>{{ row.vehiclePlate }}</span><img src="./assets/iscar.png"
                    v-if="vehicleInfo.plate == row.vehiclePlate">
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="vehicleVin" label="VIN码" />
            <el-table-column label="启动状态">
              <template slot-scope="{row}">
                <span class="item" :class="{ disable: row.keyState < 2 }">{{ row.keyState === 0 ? '熄火' : row.keyState === 1?'未点火':'启动' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="解锁状态">
              <template slot-scope="{row}">
                <span>{{ row.lockState === true ? '已上锁' : row.lockState === false?'已解锁':'' }}</span>
              </template>
            </el-table-column>
            <!-- <el-table-column
              prop="mileage"
              label="行驶里程(KW)"
            />
            <el-table-column
              prop="sn"
              label="电池编号"
              width="220"
            />
            <el-table-column
              prop="Voltage"
              label="电压(V)"
            />
            <el-table-column
              prop="Current"
              label="电流(A)"
            />
            <el-table-column
              prop="swapSoc"
              label="SOC"
            />
            <el-table-column
              prop="swapSoh"
              label="SOH"
            />
            <el-table-column
              prop="driver"
              label="司机"
            />
            <el-table-column
              prop="phone"
              label="联系电话"
            /> -->
          </el-table>
        </div>
        <div class="pageblock">
          站内连接车辆数：<span>{{ CarlineList.length }}</span>
        </div>
        <div slot="footer" class="dialog-footer" />
      </el-dialog>
    </div>
    <!--实时车辆弹窗结束-->
    <!--修改车牌号弹窗-->
    <div class="rolemanage plateBox">
      <el-dialog title="编辑车牌号" :visible.sync="dialogPlateVisible" :destroy-on-close="true">
        <el-form :model="ruleForm" :rules="rules" ref="PlateForm" v-loading="loading">
          <el-form-item label="编辑车牌号:" prop="plate">
            <el-input v-model="ruleForm.plate" placeholder="请输入您的车牌号"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="exit" @click="dialogPlateVisible = false">取消</el-button>
          <el-button type="primary" class="save" @click="handlePlate">确定</el-button>
        </div>
      </el-dialog>
    </div>
    <!--修改车牌号弹窗结束-->
    <!-- Loading公共组件 -->
    <vue-loading
      :isLoading="loading"
      type="loading3"
      :text="loadText"
      color="lightgreen"
      scale="1"
    ></vue-loading>
    <!-- Loading公共结束 -->
  </div>
</template>

<script>
import { CarOnline, EditPlate, EditforbidLock,beginSwap,setMode,plcStop,batteryfreeze,RuleChangestorage,FireChangestorage,refreshPlate } from '@/api/powerCharge'
import SubTitle from './components/SubTitle'
import PannelItem from './components/PannelItem'
import PannelTitle from './components/PannelTitle'
import BatteryInfo from './components/BatteryInfo'
import LogList from './components/LogList'
import './index.scss'
import '../../utils/jsmpeg.min'
import { getToken } from '@/utils/auth'
import { isLicensePlateNumberNER } from '@/utils'
export default {
  name: 'PowerChangeMonitoring',
  components: {
    SubTitle, PannelItem, PannelTitle, BatteryInfo, LogList
  },
  data() {
    return {
      ws: null,
      loading: false,
      loadText:'加载中...',
      soc: 95,
      ischarge: false,
      logList: [],
      dialogCarlineVisible: false,//在线车辆弹窗
      CarlineList: [],//在线车辆列表
      dialogPlateVisible: false,//修改车牌号弹窗
      ruleForm: {
        plate: undefined,
      },
      errordata:[],
      rules: {
        plate: [
          { required: true, message: '请输入车牌号', trigger: 'blur' },
          { min: 6, max: 12, message: '格式错误', trigger: 'blur' }
        ],
      },//验证车牌号
      BatteryFullStatus: true,//切换满电、亏点电池状态
      BatterySelectAllArr: [],//存储所有选中的电池仓位号
      BatteryIsSelectArr: [false, false, false, false, false, false, false, false],//存储电池的选中状态
      robotInfoVo: {},//机器人状态对象
      vehicleInfo: {},//车辆信息对象
      batteryInfo: {},//电池信息对象
      swapProcess: {},//换电进度对象
      TcInfoVo:{},//普通调仓进度对象
      XfInfoVo:{},//消防换仓进度对象
      pamars:{
        batChooseMode:undefined,
        batChosenIndex:0,
        startMode:0,
        userId:this.$store.getters.userId,
        userName:this.$store.getters.name,
      },//开始换电参数
      storeInfoList:[],//电池仓列表数组
      availableBatteries:undefined,//可用电池数
      // taskState:1,//任务进度展示切换
    }
  },
  watch: {
  },
  computed: {
    //消防换仓时长
    PlcChangeFileStore(){
      if(this.XfInfoVo.startTime){
        let end_time=this.$moment()
        let seconds=end_time.diff(this.XfInfoVo.startTime,"seconds")
        return parseInt(seconds/60)+'分'+(seconds%60)+'秒'
      }
    },
    //调仓时长
    PlcChangeStore(){
      if(this.TcInfoVo.startTime){
        let end_time=this.$moment()
        let seconds=end_time.diff(this.TcInfoVo.startTime,"seconds")
        return parseInt(seconds/60)+'分'+(seconds%60)+'秒'
      }
    },
    //换电时长
    PlcChangerTime(){
      if(this.swapProcess.swapStartTime){
        let end_time=this.$moment()
        let seconds=end_time.diff(this.swapProcess.swapStartTime,"seconds")
        return parseInt(seconds/60)+'分'+(seconds%60)+'秒'
      }
    },
    //机器人工作时长
    PlcWorkTime(){
      if(this.swapProcess.plcStartTime){
        let end_time=this.$moment()
        let seconds=end_time.diff(this.swapProcess.plcStartTime,"seconds")
        return parseInt(seconds/60)+'分'+(seconds%60)+'秒'
      }
    },
    //换电百分比
    swapPercent(){
      if(this.swapProcess.plcPercentage){
        return this.swapProcess.plcPercentage
      }else{return 0}
    },
    //换电解锁状态
    swapIsLock(){
      switch(this.swapProcess.lockState){
        case true:
          return '已上锁'
        case false:
          return '已解锁'
        default:
          return '—'
      }
    },
    //机器人状态
    PlcState() {
      switch (this.robotInfoVo.robotState) {
        case 1:
          return ['./assets/green.png','','就绪']
        case 2:
          return ['./assets/blue.png','isblue','运行']
        case 3:
          return ['./assets/blue.png','isblue','完成']
        case 4:
          return ['./assets/yellow.png','isflag','故障']
        case 5:
          return ['./assets/yellow.png','isflag','中止']
        default:
          return ['./assets/yellow.png','isflag','未就绪']
      }
    },
    //机器人模式
    PlcMode() {
      switch (this.robotInfoVo.exchangeMode) {
        case 0:
          return '无效';
        case 1:
          return '手动模式';
        case 2:
          return '自动模式';
        case 3:
          return '单步模式';
      }
    },
  },
  mounted() {
    // 监控视频
    const videoUrl = process.env.VUE_APP_VIDEO
    let canvas = document.getElementById("video-1");
    var player = new window.JSMpeg.Player(videoUrl, {canvas});
    player.play();
    if (getToken()) {
      if (this.ws) {
        this.ws.close()
      }
      this.websocketConnect()
      // 检测websocket断开重连
      this.detectWebsocketConnection()
    }
  },
  destroyed() {
    this.websocketOnClose()
  },
  methods: {
    websocketOnOpen() {
      console.log('socket连接成功')
      const wsMessage = {
        type: 'page',
        payload: 'power-change-monitoring'
      }
      this.ws.send(JSON.stringify(wsMessage))
    },
    websocketOnMessage(m) {
      const d = JSON.parse(m.data)
      console.log(d)
      if(d.plcAlarmList){
        this.errordata = d.plcAlarmList
      }
      //可用电池数
      if(d.availableBatteries>=0){
        this.availableBatteries=d.availableBatteries
      }
      //云端连接状态
      if (d.cloundState) {
        this.cloundState = d.cloundState
      }
      // 车辆信息
      if (d.vehicleInfo) {
        this.vehicleInfo = d.vehicleInfo
      }
      // 电池信息
      if (d.batteryInfo) {
        this.batteryInfo = d.batteryInfo
      }
      //机器人状态
      if (d.robotInfoVo) {
        this.robotInfoVo = d.robotInfoVo
      }
      //换电进度
      if (d.swapProcess) {
        this.swapProcess = d.swapProcess
      }
      //调仓进度
      if(d.sourceCode && d.targetCode){
        this.TcInfoVo={
          sourceCode:d.sourceCode,
          targetCode:d.targetCode,
          actionFlow:d.actionFlow,
          startTime:d.startTime,
          sn:d.sn,
          chargerState:d.chargerState,
          soc:d.soc,
          soh:d.soh
        }
      }else{
        this.TcInfoVo={}
      }
      //消防调仓进度
      if(d.xfTargetCode){
        this.XfInfoVo={
          xfTargetCode:d.xfTargetCode,
          actionFlow:d.actionFlow,
          startTime:d.startTime,
          sn:d.sn,
          chargerState:d.chargerState,
          soc:d.soc,
          soh:d.soh
        }
      }else{
        this.XfInfoVo={}
      }
      //选电模式
      if(d.batChooseMode>=0){
        this.pamars.batChooseMode=d.batChooseMode
      }
      //电池仓位列表
      if(d.storeInfoList){
        this.storeInfoList=d.storeInfoList
      }
      //日志列表
      if(d.logList){
        this.logList=d.logList.reverse()
      }
    },
    websocketOnError(e) {
      console.log('socket错误', e)
    },
    websocketOnClose(e) {
      console.log('socket断开', e)
    },
    detectWebsocketConnection() {
      this.wsTimer = setInterval(() => {
        if (this.ws.readyState != 1) {
          this.ws.close()
          this.websocketConnect()
        }
      }, 3000)
    },
    websocketConnect() {
      const wstoken = getToken()
      this.ws = new WebSocket(process.env.VUE_APP_WS + '/' + wstoken)
      this.ws.onopen = this.websocketOnOpen
      this.ws.onerror = this.websocketOnError
      this.ws.onmessage = this.websocketOnMessage
      this.ws.onclose = this.websocketOnClose
    },
    //实时车辆弹窗
    ShowCarline() {
      this.dialogCarlineVisible = true
      this.getCarOnline()
    },
    //已连接站控车辆列表
    getCarOnline() {
      CarOnline().then((rs) => {
        this.CarlineList = rs.data
      })
    },
    //编辑车牌号弹窗
    HandleEditPlate(plate) {
      this.dialogPlateVisible = true
      this.ruleForm.plate = plate
    },
    //刷新车辆
    refreshCar(){
      this.$confirm(`是否重新检测车辆?`, '刷新车辆', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async()=>{
        const res= await refreshPlate()
        if (res.code === 0) {
          this.$message({
            type: 'success',
            message: '刷新成功!',
          })
        } else {
          this.$message({
            type: 'warning',
            message: '刷新失败!',
          })
        }
      }).catch(err => { console.error(err) })
    },
    //修改车牌号提交
    handlePlate() {
      if (this.ruleForm.plate == this.vehicleInfo.plate) {
        // this.$message({
        //   type: 'warning',
        //   message: '提交成功！'
        // })
        this.dialogPlateVisible = false
      } else {
        if (!isLicensePlateNumberNER(this.ruleForm.plate)) {
          this.$message({
            type: 'warning',
            message: '请填写新能源车牌号!'
          })
        } else {
          EditPlate(this.ruleForm.plate).then((rs) => {
            if (rs.code == 0) {
              this.dialogPlateVisible = false
              this.vehicleInfo.plate = this.ruleForm.plate
              this.$message({
                type: 'success',
                message: '修改成功!'
              })
            } else {
              this.$message({
                type: 'error',
                message: '修改失败'
              })
            }
          })
            .catch(err => { console.error(err) })
        }
      }
    },
    //切换满电、亏电电池信息
    ChangeBattery(id) {
      if (id === 1) {
        this.BatteryFullStatus = true
      } else { this.BatteryFullStatus = false }
    },
    //切换换电模式(自动、手动)
    ChangeModel(modelId) {
      let modelText = modelId===1?'手动':'自动'
      this.$confirm(`请确认选电模式切换为${modelText}？`, '选电模式', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await setMode(modelId)
          if (res.code === 0) {
            if (modelId === 1) { this.pamars.batChooseMode = 1 }
            else { this.pamars.batChooseMode = 0 }
            this.$message({
              type: 'success',
              message: '选电模式切换成功!',
            })
          } else {
            this.$message({
              type: 'warning',
              message: '选电模式切换失败!',
            })
          }
        })
        .catch(err => { console.error(err) })
    },
    //开始换电
    BeginChangePower() {
      if(this.pamars.batChooseMode===1){
        
        if(this.BatterySelectAllArr.length!==1 || this.BatterySelectAllArr[0].storeState!==1){
          this.$message({
            type: 'warning',
            message: '请手动选择一个电池进行换电!',
          })
          return
        }else{
          this.pamars.batChosenIndex=this.BatterySelectAllArr[0].storeCode
        }
      }else{
        this.pamars.batChosenIndex=0
        if(this.BatterySelectAllArr.length!==0){
          this.$message({
            type: 'warning',
            message: '自动换电不用选择电池,请取消选中的电池!',
          })
          return
        }
      }
        const pamars =this.pamars
        this.$confirm('请确认站控发起换电?', '开始换电', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            // this.$message({
            //   type: 'success',
            //   message: '换电指令已下发，请等待!',
            // })
            const res = await beginSwap(pamars)
            if (res.code === 0) {
              this.clearStore()
              this.$message({
                type: 'success',
                message: '发起换电成功!',
              })
            } else {
              this.$message({
                type: 'warning',
                message: res.code==3?`发起换电失败,${res.msg}!`:'发起换电失败!',
              })
            }
          })
          .catch(err => { console.error(err) })
    },
    //锁止屏蔽、放开
    HandleIsLock(islock) {
      let lockTest = ''
      if (islock === 0) {
        lockTest = '锁止放开'
      } else {
        lockTest = '锁止屏蔽'
      }
      this.$confirm(`请确认${lockTest}?`, lockTest, {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await EditforbidLock(islock)
          if (res.code === 0) {
            this.$message({
              type: 'success',
              message: islock===0?'放开成功':'屏蔽成功',
            })
          } else {
            this.$message({
              type: 'warning',
              message: islock===0?'放开失败':'屏蔽失败',
            })
          }
        })
        .catch(err => { console.error(err) })
    },
    //急停、中止
    PausePLC(isStop) {
      const text=isStop==1?'急停机器人':'中止机器人'
      this.$confirm(`请确认${text}?`, `${text}`, {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await plcStop(isStop)
          if (res.code === 0) {
            this.$message({
              type: 'success',
              message: isStop===1?'急停成功':'中止成功',
            })
          } else {
            this.$message({
              type: 'warning',
              message: isStop===1?'急停失败':'中止失败',
            })
          }
        })
        .catch(err => { console.error(err) })
    },
    //选择电池仓位数
    BatterySelected(CurrentStore) {
      this.$set(this.BatteryIsSelectArr, CurrentStore.storeCode - 1, !this.BatteryIsSelectArr[CurrentStore.storeCode - 1])//选中电池取反
      if (this.BatteryIsSelectArr[CurrentStore.storeCode - 1]) {
        this.BatterySelectAllArr = [...this.BatterySelectAllArr, CurrentStore] //将选中的电池放入数组中
      } else {
        this.BatterySelectAllArr = this.BatterySelectAllArr.filter(item => item.storeCode != CurrentStore.storeCode)//将取消选中的电池从数组中移除
      }
      if (this.BatterySelectAllArr.length === 3) {
        this.$set(this.BatteryIsSelectArr, this.BatterySelectAllArr[0].storeCode - 1, false)
        this.BatterySelectAllArr.shift()//删除第一个元素
      }
      // console.log(this.BatterySelectAllArr)
    },
    //开始调仓
    HandleChangeStore() {
      let source=0
      let target=0
      if(this.BatterySelectAllArr.length===2){
        source=this.BatterySelectAllArr[0].storeState?1:0
        target=this.BatterySelectAllArr[1].storeState?1:0
      }
      if (this.BatterySelectAllArr.length !==2 || source==target) {
        this.$message({
          type: 'warning',
          message: '请选择一个电池和一个空仓位!'
        })
        return
      }
      // else if(this.robotInfoVo.robotState==2){
      //   this.$message({
      //     type: 'warning',
      //     message: '机器人正在运行，请稍后再试!'
      //   })
      // } 
      else if(this.BatterySelectAllArr[0].getChgState == 2 || this.BatterySelectAllArr[1].getChgState == 2){
        this.$message({
          type: 'warning',
          message: `【${this.BatterySelectAllArr[0].storeState===1?this.BatterySelectAllArr[0].storeCode:this.BatterySelectAllArr[1].storeCode}】号仓位电池未断电,请断电后在进行调仓!`
        })
      }else {
        const pamars={
          sourceCode: this.BatterySelectAllArr[0].storeState===1?this.BatterySelectAllArr[0].storeCode:this.BatterySelectAllArr[1].storeCode,//选有电池的仓位号
          targetCode: this.BatterySelectAllArr[1].storeState!==1?this.BatterySelectAllArr[1].storeCode:this.BatterySelectAllArr[0].storeCode//选空仓的仓位号
        }
        this.$confirm(`请确认将【${pamars.sourceCode}】号仓位电池移至【${pamars.targetCode}号】仓位？`, `确认调仓`, {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
            // this.$message({
            //   type: 'success',
            //   message: '调仓指令已下发，请等待!',
            // })
            const res = await RuleChangestorage(pamars)
            if (res.code === 0) {
              this.clearStore()
              this.$message({
                type: 'success',
                message: '发起调仓成功!',
              })
            } else {
              this.$message({
                type: 'warning',
                message: '发起调仓失败!',
              })
            }
          })
        .catch(err => { console.error(err) })
      } 
    },
    //消防换仓
    HandleFireStore() {
      if (this.BatterySelectAllArr.length !== 1 || this.BatterySelectAllArr[0].storeState!==1) {
        this.$message({
          type: 'warning',
          message: '请选择一个电池!'
        })
        return 
      }
      // else if(this.robotInfoVo.robotState==2){
      //   this.$message({
      //     type: 'warning',
      //     message: '机器人正在运行，请稍后再试!'
      //   })
      // }
      else if(this.BatterySelectAllArr[0].getChgState == 2){
        this.$message({
          type: 'warning',
          message: `【${this.BatterySelectAllArr[0].storeCode}】号仓位电池未断电,请断电后在进行消防换仓!`
        })
      } 
      else {
        const pamars={
          targetCode: this.BatterySelectAllArr[0].storeCode
        }
        this.$confirm(`请确认消防换仓,将【${this.BatterySelectAllArr[0].storeCode}】号仓位电池移至消防仓?`, `消防调仓`, {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
            // this.$message({
            //   type: 'success',
            //   message: '消防换仓指令已下发，请等待!',
            // })
            const res = await FireChangestorage(pamars)
            if (res.code === 0) {
              this.clearStore()
              this.$message({
                type: 'success',
                message: '发起消防换仓成功!',
              })
            } else {
              this.$message({
                type: 'warning',
                message: '发起消防换仓失败!',
              })
            }
          })
        .catch(err => { console.error(err) })
      }
    },
    //冻结、解冻
    HandleFreeze(isFree) {
      const text = isFree === 1 ? '冻结' : '解冻'
      if (this.BatterySelectAllArr.length !== 1 || this.BatterySelectAllArr[0].storeState!==1) {
        this.$message({
          type: 'warning',
          message: `请选择一个电池进行${text}!`
        })
      } 
      else if(isFree === 1 && this.BatterySelectAllArr[0].freezeState==1){
        this.$message({
          type: 'warning',
          message: `选择电池已冻结，无需再次冻结!`
        })
      }
      else if(isFree === 0 && !this.BatterySelectAllArr[0].freezeState){
        this.$message({
          type: 'warning',
          message: `选择电池已解冻，无需再次解冻!`
        })
      }
      else {
        const pamars={
          code:this.BatterySelectAllArr[0].storeCode,
          type:isFree
        }
        this.$confirm(`请确认${text}【${this.BatterySelectAllArr[0].storeCode}】号电池?`, `确认${text}`, {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            const res = await batteryfreeze(pamars) 
            if (res.code === 0) {
              this.clearStore()
              this.$message({
                type: 'success',
                message: isFree===1?'冻结成功':'解冻成功',
              })
            } else {
              this.$message({
                type: 'warning',
                message: isFree===1?'冻结失败':'解冻失败',
              })
            }
          })
        .catch(err => { console.error(err) })
      }
    },
    //清空选择的仓位
    clearStore(){
      this.BatterySelectAllArr=[]
      this.BatteryIsSelectArr=[false, false, false, false, false, false, false, false]
    },
  },
}
</script>