<template>
  <div>
    <div class="box-first">
      <div class="video-box">
        <canvas id="video-1" />
      </div>
      <div class="infolist">
        <div class="userlist">
          <ul>
            <li>
              <UserItem title="用户名信息" name="USER INFORMATION" />
              <label>驾驶员</label>
              <pannel-item :value="driverInfo.name" />
              <label>联系方式</label>
              <pannel-item :value="driverInfo.mobile" />
              <label>身份证号</label>
              <pannel-item :value="driverInfo.cardNum" />
              <label>所属车队</label>
              <pannel-item :value="driverInfo.motorcade" />
            </li>
            <li>
              <UserItem title="车辆信息" name="VEHICLE INFORMATION" />
              <span>
                <label>车辆VIN码</label><label>{{ Carlink }}</label>
              </span>
              <pannel-item :value="vehicleInfo.vin" />
              <div class="carinfo">
                <p>
                  <label>车牌号</label>
                  <pannel-item :value="vehicleInfo.plate" />
                </p>
                <p>
                  <label>解锁状态</label>
                  <pannel-item :value="Carlock" />
                </p>
              </div>
              <div class="carinfo">
                <p>
                  <label>累计里程 (km)</label>
                  <pannel-item :value="vehicleInfo.mileage" />
                </p>
                <p>
                  <label>上电状态</label>
                  <pannel-item :value="Carbattery" />
                </p>
              </div>

              <label>累计换电 (次)</label>
              <pannel-item :value="vehicleInfo.swap" />
            </li>
            <li>
              <UserItem title="电池信息" name="Battery INFORMATION" />
              <label>电池编号</label>
              <pannel-item :value="batteryInfo.sn" />
              <label>电池仓</label>
              <pannel-item :value="batteryInfo.space" />
              <div class="carinfo">
                <P>
                  <label>换电电池SOC</label>
                  <pannel-item :value="batteryInfo.swapSoc" />
                </P>
                <P>
                  <label>车辆电池SOC</label>
                  <pannel-item :value="batteryInfo.vehSoc" />
                </P>
              </div>
              <label>换电量(kWh)</label>
              <pannel-item :value="batteryInfo.swapCapacity" />
            </li>
          </ul>
          <div class="bin-info">
            <!--
              * @step：动画步骤
              * @BatteryOnCar：控制车上亏电电池是否亮起
              * @storeInfoList：充电仓电池列表
              * @swapCode：换电电池编号
              * @connectionState：车站连接状态 1已连接 0断开连接
              * @swapCurrent：绿电池缓存电流,
              * @swapSoc：绿电池缓存SOC,
            -->
            <BinInfomation
              :battery-on-car="swapAnimationVo.soc"
              :store-info-list="storeInfoList"
              :swap-code="swapAnimationVo.swapCode*1-1"
              :step="swapAnimationVo.step"
              :connection-state="swapAnimationVo.connectionState"
              :swap-soc="swapAnimationVo.swapSoc"
              :swap-current="swapAnimationVo.swapCurrent"
            />
          </div>
        </div>
      </div>
    </div>
    <div class="box-second">
      <sub-title
        name="换电业务流程"
        statement="power exchange business process"
      />
      <process-symbol
        :processtext="processtext"
        :process-done="processDone"
      />
      <div class="process-details">
        <div v-for="(item, index) in processDone" :key="index" class="detail">
          <span
            class="process-state"
            :style="{color: item === true ? 'rgb(4,220,223)' : 'rgb(69,85,115)',}"
          >
            <div v-if="swapProcess.validation === null && index === 0">待验证</div>
            <div v-else-if="swapProcess.validation && index === 0">
              {{ swapProcess.validation }}
            </div>

            <div v-if="swapProcess.apply === null && index === 1">待申请</div>
            <div v-else-if="swapProcess.apply && index === 1">
              {{ swapProcess.apply }}
            </div>

            <div v-if="swapProcess.begin === null && index === 2">待开始</div>
            <div v-else-if="swapProcess.begin && index === 2">
              {{ swapProcess.begin }}
            </div>

            <div v-if="swapProcess.swap === null && index === 3">待更换</div>
            <div v-else-if="swapProcess.swap && index === 3">
              {{ swapProcess.swap }}
            </div>

            <div v-if="swapProcess.end === null && index === 4">待确定</div>
            <div v-else-if="swapProcess.end && index === 4">
              {{ swapProcess.end }}
            </div>
          </span>
          <quarter-change
            :percent="percent[index]"
            :process-deg="processDeg[index]"
            :is-done="item"
            :image="processImages[index]"
          />
        </div>
      </div>
    </div>
    <div class="box-three">
      <div class="exchange-statistics">
        <sub-title name="换电信息" statement="Power Change Details" />
        <div class="statistic-boxes">
          <statistic-item
            label="今日换电次数"
            :value="swapInfo.todaySwapFreq"
            unit="次"
          />
          <statistic-item
            label="今日换电量"
            :value="swapInfo.todayCapacity"
            unit="kWh"
          />
          <statistic-item
            label="累计换电次数"
            :value="swapInfo.swapFreq"
            unit="次"
          />
          <statistic-item
            label="累计换电量"
            :value="swapInfo.capacity"
            unit="kWh"
          />
          <statistic-item
            label="当前可换电池"
            :value="swapInfo.quantity"
            unit="块"
          />
          <statistic-item
            label="今日告警数"
            :value="swapInfo.todayAlarmFreq"
            unit="次"
          />
        </div>
      </div>

      <div class="exchange-records">
        <sub-title name="换电记录" statement="Exchange Records" />
        <div class="exchange-details">
          <div class="header-row">
            <span class="v-plate">车牌号</span>
            <span class="v-type">车型</span>
            <span class="v-power">换电量</span>
            <span class="v-time">换电时间</span>
          </div>
          <div v-for="item in carRecord" :key="item.id" class="record-row">
            <span class="v-plate">{{ item.vehiclePlate }}</span>
            <span class="v-type">{{ item.modelName }}</span>
            <span class="v-power color-blue">{{ item.swapCapacity }}</span>
            <span class="v-time">{{ item.swapBeginTime }}</span>
          </div>
        </div>
      </div>

      <div class="gate-details">
        <sub-title name="告警记录" statement="ALARM LOG" />
        <div class="recordlist">
          <div class="recordtilte">
            <span>告警代码</span><span>告警设备</span><span>告警信息</span><span>告警时间</span>
          </div>
          <div
            v-for="item in alarmRecordList"
            :key="item.id"
            class="recordinfo"
          >
            <span>{{ item.code }}</span><span>{{ item.equipment }}</span><span :title="item.info">{{ item.info }}</span><span>{{ item.beginTime }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { swapInfo, swapRecord, alarmRecord } from '@/api/powerCharge'
import wsUrl from '../../../vue.config.js'
import UserItem from './components/UserItem.vue'
import PannelItem from './components/PannelItem.vue'
import BinInfomation from './components/BinInfomation.vue'
import SubTitle from './components/SubTitle.vue'
import ProcessSymbol from './components/ProcessSymbol.vue'
import QuarterChange from './components/QuarterChange.vue'
import StatisticItem from './components/StatisticItem.vue'
import '../../utils/jsmpeg.min'
import { getToken } from '@/utils/auth'
export default {
  name: 'PowerChangeMonitoring',
  components: {
    UserItem,
    PannelItem,
    BinInfomation,
    SubTitle,
    ProcessSymbol,
    QuarterChange,
    StatisticItem
  },
  data() {
    return {
      ws: null,
      // 司机信息
      driverInfo: {
        name: '—',
        mobile: '—',
        cardNum: '—',
        motorcade: '—'
      },
      // 车辆信息开始
      vehicleInfo: {
        vin: '—',
        plate: '—',
        lockState: '—',
        mileage: '—',
        batteryState: '—',
        swap: '—',
        conState: 0
      },
      batteryInfo: {
        sn: '—',
        vehSoc: '—',
        space: '—',
        swapSoc: '—',
        swapCapacity: '—'
      },
      // 电池动画
      swapAnimationVo: {
        step: 0, // 动画步骤
        soc: 30, // 车上电池SOC
        transitCode: null, // 中转仓编号
        swapCode: 0, // 换电仓编号
        connectionState: 0, // 车站连接状态
        swapSoc: 0, // 绿电池缓存数据
        swapCurrent: 0 // 绿电池缓存数据
      },
      storeInfoList: [], // 电池列表和充电机状态列表
      // 电池动画结束
      // 第二部分动画开始
      swapProcess: {
        // 第一步
        validation: null,
        valPercentage: null,
        valAngle: null,
        // 第二步
        apply: null,
        applyPercentage: null,
        applyAngle: null,
        // 第三步
        begin: null,
        beginPercentage: null,
        beginAngle: null,
        // 第四步
        swap: null,
        swapPercentage: null,
        swapAngle: null,
        // 第五步
        end: null,
        endPercentage: null,
        endAngle: null
      },
      processtext: [
        '车辆验证',
        '发起换电申请',
        '卸载车辆电池',
        '安装满电电池',
        '换电完成'
      ],
      processImages: [
        'yewu1.png',
        'yewu2.png',
        'yewu3.png',
        'yewu4.png',
        'yewu5.png'
      ],
      processDone: [false, false, false, false, false],
      percent: [0, 0, 0, 0, 0],
      processDeg: [0, 0, 0, 0, 0],
      // 第二部分动画结束

      // 换电详情
      swapInfo: {
        capacity: '--',
        quantity: '--',
        swapFreq: '--',
        todayAlarmFreq: '--',
        todayCapacity: '--',
        todaySwapFreq: '--'
      },
      // 换电记录
      carRecord: [],
      // 告警记录
      alarmRecordList: []
    }
  },
  computed: {
    // 车辆链接状态
    Carlink() {
      if (this.vehicleInfo.conState != '—') {
        return this.vehicleInfo.conState ? '已链接' : '未链接'
      } else {
        return '—'
      }
    },
    // 解锁状态
    Carlock() {
      if (this.vehicleInfo.lockState != '—') {
        return this.vehicleInfo.lockState ? '已解锁' : '未解锁'
      } else {
        return '—'
      }
    },
    // 上电状态
    Carbattery() {
      if (this.vehicleInfo.batteryState != '—') {
        return this.vehicleInfo.batteryState ? '已下电' : '未下电'
      } else {
        return '—'
      }
    }
  },
  mounted() {
    // 监控视频
    const videoUrl = wsUrl.devServer.proxy["/video"].target
    let canvas = document.getElementById("video-1");
    var player = new window.JSMpeg.Player(videoUrl, {
      canvas: canvas,
    });
    player.play();
    if (getToken()) {
      if (this.ws) {
        this.ws.close()
      }
      this.websocketConnect()
      // 清除定时器
      this.clearTimerList()
      // 检测断开重连
      this.detectWebsocketConnection()
      // 开启定时器
      this.setTimerList()
    }
  },
  destroyed() {
    this.websocketOnClose()
    this.clearTimerList()
  },
  methods: {
    // 定时器列表
    setTimerList() {
      this.exchargeInfo()
      this.swapRecord()
      this.alarmRecord()
      this.exchargeTimer = setInterval(() => {
        this.exchargeInfo()
        this.swapRecord()
        this.alarmRecord()
      }, 5000)
    },
    // 清除定时器列表
    clearTimerList() {
      if (this.exchargeTimer) {
        clearInterval(this.exchargeTimer)
      }
      if (this.wsTimer) {
        clearInterval(this.wsTimer)
      }
    },
    // 换电信息
    exchargeInfo() {
      swapInfo().then((rs) => {
        this.swapInfo = rs.data
      })
    },
    // 换电记录
    swapRecord() {
      const params = {
        page: 1,
        pageSize: 2,
        orderByWays: 'desc',
        orderByField: 'swapBeginTime'
      }
      swapRecord(params).then((rs) => {
        this.carRecord = rs.data.records
      })
    },
    // 告警记录
    alarmRecord() {
      const params = {
        page: 1,
        pageSize: 2,
        orderByWays: 'desc',
        orderByField: 'beginTime'
      }
      alarmRecord(params).then((rs) => {
        this.alarmRecordList = rs.data.records
      })
    },
    websocketOnOpen() {
      console.log('socket连接成功')
    },
    websocketOnMessage(m) {
      const d = JSON.parse(m.data)
      // console.log(d)
      if (d.driverInfoVo) {
        this.driverInfo = d.driverInfoVo
      }
      // 车辆信息
      if (d.vehicleInfo) {
        this.vehicleInfo = d.vehicleInfo
      }
      // 电池信息
      if (d.batteryInfo) {
        this.batteryInfo = d.batteryInfo
      }
      // 换电流程动画
      if (d.swapProcess) {
        this.swapProcess = d.swapProcess
        if (this.swapProcess.valAngle === null) {
          this.processDone = [false, false, false, false, false]
          this.percent = [0, 0, 0, 0, 0]
          this.processDeg = [0, 0, 0, 0, 0]
        }
        if (this.swapProcess.valAngle) {
          this.processDone.splice(0, 1, true)
          this.percent.splice(0, 1, this.swapProcess.valPercentage)
          this.processDeg.splice(0, 1, this.swapProcess.valAngle)
        }
        if (this.swapProcess.applyAngle) {
          this.processDone.splice(1, 1, true)
          this.percent.splice(1, 1, this.swapProcess.applyPercentage)
          this.processDeg.splice(1, 1, this.swapProcess.applyAngle)
        }
        if (this.swapProcess.beginAngle) {
          this.processDone.splice(2, 1, true)
          this.percent.splice(2, 1, this.swapProcess.beginPercentage)
          this.processDeg.splice(2, 1, this.swapProcess.beginAngle)
        }
        if (this.swapProcess.swapAngle) {
          this.processDone.splice(3, 1, true)
          this.percent.splice(3, 1, this.swapProcess.swapPercentage)
          this.processDeg.splice(3, 1, this.swapProcess.swapAngle)
        }
        if (this.swapProcess.endAngle) {
          this.processDone.splice(4, 1, true)
          this.percent.splice(4, 1, this.swapProcess.endPercentage)
          this.processDeg.splice(4, 1, this.swapProcess.endAngle)
        }
      }
      // 右上角电池动画
      if (d.swapAnimationVo) {
        this.swapAnimationVo = d.swapAnimationVo
      }
      if (d.storeInfoList) {
        this.storeInfoList = d.storeInfoList
        for (let i = 0; i < d.storeInfoList.length; i++) {
          this.$set(this.storeInfoList, i, d.storeInfoList[i])
        }
      }
    },
    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(wsUrl.devServer.proxy['/ws'].target+'/'+wstoken)
      this.ws.onopen = this.websocketOnOpen
      this.ws.onerror = this.websocketOnError
      this.ws.onmessage = this.websocketOnMessage
      this.ws.onclose = this.websocketOnClose
    }
  }
}
</script>

<style lang="scss" scoped>
.box-first {
  display: flex;
  flex-direction: row;
  padding: 10px 20px;

  .video-box {
    width: 460px;
    height: 368px;
    #video-1 {
      flex: 1;
      width: 100%;
      margin-top: 0.6%;
      height: 100%;
    }
  }

  .infolist {
    flex: 1;
    height: 368px;
    .userlist {
      height: 100%;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      width: 100%;
      ul {
        width: 73%;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        height: 100%;
        margin: 0;
        padding: 0;
        li:first-child {
          width: 30%;
          padding-left: 1.2%;
        }
        li:nth-child(2) {
          flex: 1;
          margin: 0 12px;
        }
        li:last-child {
          width: 29%;
        }
        li {
          list-style-type: none;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          span {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            label:last-child {
              text-align: right;
              color: #86edab;
              font-weight: 500;
            }
          }
          label {
            display: block;
            font-size: 1rem;
            width: 95%;
            text-align: left;
            color: #788799;
            font-weight: 500;
            padding-left:12px;
            margin: 10px 0;
          }
          .carinfo {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            p {
              margin: 0;
              padding: 0;
              width: 48%;
            }
          }
        }
      }
      .battery-info {
        width: 100%;
        display: flex;
        height: 80%;
        flex-wrap: wrap;
        justify-content: space-around;
        align-items: center;
        margin-top: 5%;
      }
      .bin-info {
        width: 380px;
      }
    }
  }
}
.box-second {
  display: flex;
  padding: 20px;
  flex-direction: column;

  .process-details {
    display: flex;
    flex-direction: row;
    flex: 1;
    padding: 10px;
    align-items: center;
  }
  .detail {
    flex: 1;
    position: relative;
    height: 230px;
    margin-top: 15px;
  }
  .process-state {
    /* color:white; */
    font-size: 1rem;
    position: absolute;
    font-weight: 600;
    bottom: -10px;
    left: 40%;
    z-index: 1;
  }
}
.box-three {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding: 5px 20px;
  position: relative;
  .exchange-statistics {
    width: 34%;
    display: flex;
    flex-direction: column;
    .statistic-boxes {
      flex: 1;
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      width: 100%;
      justify-content: space-between;
    }
  }
  .exchange-records {
    display: flex;
    flex-direction: column;
    width: 34%;
    margin: 0px 18px;
    .exchange-details {
      display: flex;
      flex-direction: column;
      padding: 0 0.5%;
      .header-row {
        height: 44px;
        line-height: 44px;
        color: #6e7987;
      }
      .record-row {
        height: 54px;
        line-height: 54px;
        color: #ecf6f7;
      }
      .record-row,
      .header-row {
        flex: 1;
        display: flex;
        flex-direction: row;
        text-indent: 15px;
        justify-content: space-between;
        align-items: center;
        font-size: 0.9rem;
        font-weight: 600;
        font-family: "微软雅黑";

        .v-plate {
          width: 20%;
        }
        .v-type {
          width: 22%;
        }
        .v-time {
          flex: 1;
        }
        .v-status {
          width: 15%;
        }
        .v-power {
          width: 25%;
        }
        .color-blue {
          color: rgb(20, 189, 243);
        }
      }
      .record-row:nth-child(2) {
        background: #0e182a;
        border: #0f244a solid 2px;
        border-radius: 0 0 1.2rem 0;
      }
    }
  }
  .gate-details {
    display: flex;
    flex-direction: column;
    flex: 1;
    .recordlist {
      text-indent: 12px;
      .recordtilte {
        font-size: 0.9rem;
        color: #6e7987;
        font-weight: 600;
        display: flex;
        flex-direction: row;
        height: 48px;
        line-height: 48px;

        span:first-child {
          width: 88px;
        }
        span:nth-child(2) {
          width: 100px;
        }
        span:nth-child(3) {
          width: 190px;
          text-align: left;
          text-indent: 15px;
          overflow: hidden; 
          text-overflow: ellipsis;
          white-space: nowrap;
          cursor: pointer;
        }
        span:last-child {
          flex: 1;
        }
      }

      .recordinfo {
        display: flex;
        flex-direction: row;
        color: #ecf6f7;
        font-weight: 600;
        font-size: 0.9rem;
        height: 54px;
        line-height: 54px;
        span:first-child {
          width: 88px;
        }
        span:nth-child(2) {
          width: 100px;
        }
        span:nth-child(3) {
          width: 190px;
          text-align: left;
          text-indent: 15px;
          overflow: hidden; 
          text-overflow: ellipsis;
          white-space: nowrap;
          cursor: pointer;
        }
        span:last-child {
          flex: 1;
        }
      }
      .recordinfo:nth-child(2) {
        background: #0e182a;
        border: #0f244a solid 2px;
        border-radius: 0 0 1.2rem 0;
      }
    }
  }
}
</style>
