<!-- 机组监测 -->
<template>
  <div class="crew-monitoring">
    <div class="title">
      {{$x_factory.plantName}} - {{$x_crew ? $x_crew.shortName : ''}}
    </div>
    <!-- <div class="number">
      <number-flipper class="num" title="机组转速" unit="r/min" :number="dataTop ? dataTop[0].kksValueR : 0" :point="1" />
      <number-flipper class="num" title="有功功率" unit="kW" :number="dataTop ? dataTop[1].kksValueR : 0" :point="1" />
    </div> -->
    <div class="model">
      <img src="../assets/img/crew.png" />
      <div class="name" :class="dataTop && getCrewState(dataTop[0]) ? (getCrewState(dataTop[0]) == 1 ? 'name-run' : 'name-stop') : 'name-error' ">{{$x_crew ? $x_crew.shortName : ' '}}</div>
      <scroll-window class="roll-left-top">
        <div class="win-list flex-down" v-if="listLeftTop">
        <!-- <el-scrollbar class="win-list flex-down" v-if="listLeftTop"> -->
          <div class="win-item" :style="{color: getWarnColor(v.state)}" v-for="v of listLeftTop" :key="v.kksCode">
            <div class="win-item-left">{{v.cpName}}</div>
            <div class="win-item-right">{{v.kksValueR + ' ' + v.cpUnit}}</div>
          </div>
        <!-- </el-scrollbar> -->
        </div>
      </scroll-window>
      <scroll-window class="roll-right-top" direction="1">
        <div class="win-list flex-down" v-if="listRightTop">
        <!-- <el-scrollbar class="win-list flex-down" v-if="listRightTop"> -->
          <div class="win-item" :style="{color: getWarnColor(v.state)}" v-for="v of listRightTop" :key="v.kksCode">
            <div class="win-item-left">{{v.cpName}}</div>
            <div class="win-item-right">{{v.kksValueR + ' ' + v.cpUnit}}</div>
          </div>
        <!-- </el-scrollbar> -->
        </div>
      </scroll-window>
      <scroll-window class="roll-left-bottom" isTop="1">
        <el-scrollbar class="win-list" v-if="listLeftBottom">
          <div class="win-item" :style="{color: getWarnColor(v.state)}" v-for="v of listLeftBottom" :key="v.kksCode">
            <div class="win-item-left">{{v.cpName}}</div>
            <div class="win-item-right">{{v.kksValueR + ' ' + v.cpUnit}}</div>
          </div>
        </el-scrollbar>
      </scroll-window>
      <scroll-window class="roll-right-bottom" direction="1" isTop="1">
        <el-scrollbar class="win-list" v-if="listRightBottom">
          <div class="win-item" :style="{color: getWarnColor(v.state)}" v-for="v of listRightBottom" :key="v.kksCode">
            <div class="win-item-left">{{v.cpName}}</div>
            <div class="win-item-right">{{v.kksValueR + ' ' + v.cpUnit}}</div>
          </div>
        </el-scrollbar>
      </scroll-window>
    </div>
    <div class="block left">
      <div class="border-bg">
        <div class="chart-title">功率水头曲线</div>
        <chart-line-broken id="ChartLeftTop" ref="ChartLeftTop" class="chart-main" :chartData="dataLeftTop" />
      </div>
      <div class="border-bg">
        <div class="chart-title">机组背景量</div>
        <div class="chart-main">
          <div class="chart-nums">
            <number-flipper v-for="v of dataLeftBottom" class="chart-num" :key="v.kksCode" :title="v.cpName" :unit="v.cpType ? v.cpUnit : ''" :number="v.kksValueR" :state="v.state" :point="1" simple="1" />
          </div>
          <!-- <chart-bar-three id="ChartLeftBottom" ref="ChartLeftBottom" class="chart-chart" :chartData="dataLeftBottom" /> -->
        </div>
      </div>
    </div>
    <div class="block right">
      <div class="border-sm">
        <div class="chart-title">机组摆度监测</div>
        <div class="chart-main" style="flex-direction: column;">
          <div class="single-row" v-for="(row,index) of dataRightTop" :key="index">
            <div class="single-col" :style="{width: (100 / getArrMaxLen(dataRightTop)) + '%'}" v-for="(v,index2) of row" :key="index2">
              <chart-bar-single :id="'ChartRightTop' + index + index2" :chartData="v" />
            </div>
          </div>
          <!-- <crew-state-count class="chart-count" :count="countRightTop" /> -->
          <!-- <chart-bar-pic id="ChartRightTop" ref="ChartRightTop" class="chart-chart" :chartData="dataRightTop" /> -->
        </div>
      </div>
      <div class="border-sm">
        <div class="chart-title">机组振动监测</div>
        <div class="chart-main" style="flex-direction: column;">
          <div class="single-row" v-for="(row,index) of dataRightCenter" :key="index">
            <div class="single-col" :style="{width: (100 / getArrMaxLen(dataRightCenter)) + '%'}" v-for="(v,index2) of row" :key="index2">
              <chart-bar-single :id="'ChartRightCenter' + index + index2" :chartData="v" />
            </div>
          </div>
          <!-- <crew-state-count class="chart-count" :count="countRightCenter" /> -->
          <!-- <chart-bar-pic id="ChartRightCenter" ref="ChartRightCenter" class="chart-chart" :chartData="dataRightCenter" /> -->
        </div>
      </div>
      <div class="border-sm">
        <div class="chart-title">温度监测</div>
        <div class="chart-main">
          <!-- <crew-state-count class="chart-count" :count="countRightBottom" /> -->
          <chart-bar-pic id="ChartRightBottom" ref="ChartRightBottom" class="chart-chart" :chartData="dataRightBottom" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import {
    CONFIG,
    CrewState,
    CrewMConfig
  } from '@/common/const.js';
  import {
    randomData,
    dateFormat,
    getCharacterFromCrew,
    getWarnColor,
    toFixedNum
  } from '@/common/util.js';
  import NumberFlipper from '@/components/NumberFlipper'
  import ChartLineBroken from '@/components/Charts/ChartLineBroken'
  import ChartBarThree from '@/components/Charts/ChartBarThree';
  import ChartBarArc from '@/components/Charts/ChartBarArc'
  import ChartBarPic from '@/components/Charts/ChartBarPic'
  import ChartBarCylinder from '@/components/Charts/ChartBarCylinder'
  import ChartBarSingle from '@/components/Charts/ChartBarSingle';
  import CrewStateCount from '@/components/CrewStateCount'
  import ScrollWindow from '@/components/ScrollWindow'
  import User from '@/api/user.js';
  export default {
    components: {
      NumberFlipper,
      ChartLineBroken,
      ChartBarThree,
      ChartBarArc,
      ChartBarPic,
      ChartBarCylinder,
      ChartBarSingle,
      CrewStateCount,
      ScrollWindow,
    },
    data() {
      return {
        dataTop: null,
        dataLeftTop: null,
        dataLeftBottom: null,
        dataRightTop: null,
        dataRightCenter: null,
        dataRightBottom: null,
        countLeftBottom: null,
        countRightTop: null,
        countRightCenter: null,
        countRightBottom: null,
        listLeftTop: null,
        listLeftBottom: null,
        listRightTop: null,
        listRightBottom: null,
        timer: null,
        socket: null, // socket
        getWarnColor: getWarnColor,
      }
    },
    watch: {
      $x_crew: {
        immediate: true,
        handler(val) {
          if (!val) this.$router.push('/FactoryMonitoring');
          else {
            this.clearChart(); // 清空图表
            // this.initRandomData(); // 模拟数据
            this.initData(); // 图表数据
            this.closeSocket();
            this.initSocket(); // 左上角数据
          }
        }
      },
      $x_allData: {
        handler(val) {
          this.initData(); // 图表数据
        }
      }
    },
    beforeDestroy() {
      this.closeSocket();
      this.clearTimer();
    },
    methods: {
      initData() {
        if(!this.$x_crew || !this.$x_allData.length) return;
        this.dataTop = this.initDataList('top');
        this.dataLeftBottom = this.initDataList('leftBottom', 9);
        this.dataRightTop = this.initDataChartSingle('rightTop', 3);
        this.dataRightCenter = this.initDataChartSingle('rightCenter', 3);
        this.dataRightBottom = this.initDataChart('rightBottom', 4, 1);
        this.listLeftTop = this.initDataList('listLeftTop');
        this.listLeftBottom = this.initDataList('listLeftBottom');
        this.listRightTop = this.initDataList('listRightTop');
        this.listRightBottom = this.initDataList('listRightBottom');
      },
      // 处理框框数据，传入位置, len为截取长度，不传则不截取，type为是否模糊匹配
      initDataList(pos, len, type) {
        const crew = this.$x_allData.find(i => i.deviceId == this.$x_crew.deviceId);
        // 提取相关测点
        let list = CrewMConfig[pos].map(arr => {
          for (let key of arr) {
            let res = getCharacterFromCrew(crew, key, null, type);
            if(res) return res;
          }
          return false;
        }).filter(i => !!i);
        if(len) list.splice(parseInt(len), list.length);
        return list;
      },
      // 处理图表数据，传入位置, len为截取长度，不传则不截取，type为是否模糊匹配
      initDataChart(pos, len, type) {
        let list = this.initDataList(pos, len, type);
        let data = {
          xAxis: list.map(i => i.cpName),
          dataList: [{
            name: this.$x_crew.deviceName,
            // value: list.map(i => i.kksValue?.value), // 传原值，图表里处理state
            value: list.map(i => i.kksValueR), // 传真实值
            // value: list.map(i => toFixedNum(i.kksValueR, 2)), // 保留小数，看用户是否需要
            state: list.map(i => i.state),
          }],
        }
        return data;
      },
      // 处理图表数据中的胶囊图数据，返回二维数组，即宫格对应位置，传入位置, len为截取长度，不传则不截取
      initDataChartSingle(pos, len, type) {
        const crew = this.$x_allData.find(i => i.deviceId == this.$x_crew.deviceId);
        // 提取相关测点
        let list = CrewMConfig[pos].map(row => {
          let list2 = row.map(col => {
            for (let key of col) {
              let res = getCharacterFromCrew(crew, key.name, type);
              if(res) {
                res.defaultMax = key.defaultMax; // 添加默认最大值
                return res;
              }
            }
            return false;
          }).filter(i => !!i);
          if(len) list2.splice(parseInt(len), list2.length);
          return list2;
        });
        return list;
      },
      // 初始化socket
      initSocket() {
        this.socket = new WebSocket('ws://' + CONFIG.SOCKET + '/powerCurve/' + this.$x_crew.deviceId, [this.$x_user.token.split(' ')[1]]);
        this.socket.onopen = () => console.log('socket_crew success');
        this.socket.onerror = e => {
          console.log('socket_crew error', e);
          User.getRoleList(); // 捕获错误，然后发送一个请求，因为可能是token导致的socket连接错误，发送请求后如果是token过期，会自动注销用户
        }
        this.socket.onmessage = msg => {
          try{
            const data = JSON.parse(msg.data);
            // console.log('socket_crew data', msg);
            // console.log('socket_crew data', data);
            if (!data) return;
            data.xAxis = data.xaxis.map(i => dateFormat(new Date(i * 1000), 'YY/MM/DD\nHH:mm:ss')); // 时间转换
			data.dataList.sort((a,b) => a.name.localeCompare(b.name));
            this.dataLeftTop = data;
          }catch(e){
            console.log(e);
          }
        }
      },
      // 关闭socket
      closeSocket() {
        if (this.socket) {
          this.socket.close();
          this.socket = null;
        }
      },
      // 清除定时器
      clearTimer() {
        if (this.timer) {
          window.clearTimeout(this.timer);
          this.timer = null;
        }
      },
      // 清空图表
      clearChart() {
        this.dataTop = null;
        this.dataLeftTop = null;
        this.dataLeftBottom = null;
        this.dataRightTop = null;
        this.dataRightCenter = null;
        this.dataRightBottom = null;
        this.countLeftBottom = null;
        this.countRightTop = null;
        this.countRightCenter = null;
        this.countRightBottom = null;
        this.listLeftTop = null;
        this.listLeftBottom = null;
        this.listRightTop = null;
        this.listRightBottom = null;
      	if (this.$refs.ChartLeftTop) this.$refs.ChartLeftTop.clear();
      	if (this.$refs.ChartRightBottom) this.$refs.ChartRightBottom.clear();
      },
      // 初始化虚拟数据
      initRandomData() {
        this.clearTimer();
        const fun = () => {
          this.dataLeftTop = this.initDataLeftTop();
          this.dataLeftBottom = this.initDataLeftBottom();
          this.dataRightTop = this.initDataRightTop();
          this.dataRightCenter = this.initDataRightCenter();
          this.dataRightBottom = this.initDataRightBottom();
          // this.countLeftBottom = this.initCountLeftBottom();
          // this.countRightTop = this.initCountRightTop();
          // this.countRightCenter = this.initCountRightCenter();
          // this.countRightBottom = this.initCountRightBottom();
        };
        fun();
        this.timer = setInterval(fun, 3000);
      },
      initDataLeftTop() {
        let data = {
          unit: '(MW)',
          xAxis: ['08-25 08', '08-25 09', '08-25 10', '08-25 11', '08-25 12'],
          dataList: [{
            name: '机组功率',
            value: []
          }, {
            name: '水位头',
            value: []
          }],
        }
        for (let i = 0; i < data.xAxis.length; i++) {
          for (let j = 0; j < data.dataList.length; j++) {
            data.dataList[j].value.push(Math.ceil(Math.random() * 20 + 20));
          }
        }
        return data;
      },
      initDataLeftBottom() {
        let data = {
          xAxis: ['一级报警', '二级报警', '三级报警'],
          dataList: [{
            name: '1号机组',
            value: []
          }],
        }
        for (let i = 0; i < data.xAxis.length; i++) {
          for (let j = 0; j < data.dataList.length; j++) {
            data.dataList[j].value.push(Math.ceil(Math.random() * 20 + 20));
          }
        }
        return data;
      },
      initDataRightTop() {
        // let data = {
        //   xAxis: ['一级报警', '二级报警', '三级报警'],
        //   dataList: [{
        //     name: '1号机组',
        //     value: []
        //   }],
        // }
        // for (let i = 0; i < data.xAxis.length; i++) {
        //   for (let j = 0; j < data.dataList.length; j++) {
        //     data.dataList[j].value.push(Math.ceil(Math.random() * 20 + 20) + '.005');
        //   }
        // }
        // return data;
        let data = [{
          title: '上导轴承振动',
          xAxis: ['X', 'Y'],
          dataList: [{
            name: '1号机组',
            value: []
          }],
        }, {
          title: '上机架振动',
          xAxis: ['X', 'Y'],
          dataList: [{
            name: '1号机组',
            value: []
          }],
        }]
        for (let i = 0; i < data.length; i++) {
          for (let j = 0; j < data[i].xAxis.length; j++) {
            for (let k = 0; k < data[i].dataList.length; k++) {
              data[i].dataList[k].value.push(Math.ceil(Math.random() * 20 + 20) + '.005');
            }
          }
        }
        return data;
      },
      initDataRightCenter() {
        // let data = {
        //   xAxis: ['一级报警', '二级报警', '三级报警'],
        //   dataList: [{
        //     name: '1号机组',
        //     value: []
        //   }],
        // }
        // for (let i = 0; i < data.xAxis.length; i++) {
        //   for (let j = 0; j < data.dataList.length; j++) {
        //     data.dataList[j].value.push(Math.ceil(Math.random() * 20 + 20) + '.005');
        //   }
        // }
        // return data;
        let data = [{
          title: '上导轴承振动',
          xAxis: ['X', 'Y'],
          dataList: [{
            name: '1号机组',
            value: []
          }],
        }, {
          title: '法兰振动',
          xAxis: ['X', 'Y'],
          dataList: [{
            name: '1号机组',
            value: []
          }],
        }, {
          title: '水导轴承振动',
          xAxis: ['X', 'Y'],
          dataList: [{
            name: '1号机组',
            value: []
          }],
        }]
        for (let i = 0; i < data.length; i++) {
            for (let j = 0; j < data[i].xAxis.length; j++) {
                for (let k = 0; k < data[i].dataList.length; k++) {
                    data[i].dataList[k].value.push(Math.ceil(Math.random() * 20 + 20) + '.005');
                }
            }
        }
        return data;
      },
      initDataRightBottom() {
        // let data = {
        //   xAxis: ['一级报警', '二级报警', '三级报警'],
        //   dataList: [{
        //     name: '1号机组',
        //     value: []
        //   }],
        // }
        // for (let i = 0; i < data.xAxis.length; i++) {
        //   for (let j = 0; j < data.dataList.length; j++) {
        //     data.dataList[j].value.push(Math.ceil(Math.random() * 20 + 20) + '.005');
        //   }
        // }
        // return data;
        let data = [{
          title: '上导轴承振动',
          xAxis: ['X', 'Y'],
          dataList: [{
            name: '1号机组',
            value: []
          }],
        }, {
          title: '顶盖振动',
          xAxis: ['X', 'Y'],
          dataList: [{
            name: '1号机组',
            value: []
          }],
        }]
        for (let i = 0; i < data.length; i++) {
          for (let j = 0; j < data[i].xAxis.length; j++) {
            for (let k = 0; k < data[i].dataList.length; k++) {
              data[i].dataList[k].value.push(Math.ceil(Math.random() * 20 + 20) + '.005');
            }
          }
        }
        return data;
      },
      initCountLeftBottom() {
        let count = {};
        for (let key in CrewState) {
          count[key] = Math.ceil(Math.random() * 20 + 20);
        }
        return count;
      },
      initCountRightTop() {
        let count = {};
        for (let key in CrewState) {
          count[key] = Math.ceil(Math.random() * 20 + 20);
        }
        return count;
      },
      initCountRightCenter() {
        let count = {};
        for (let key in CrewState) {
          count[key] = Math.ceil(Math.random() * 20 + 20);
        }
        return count;
      },
      initCountRightBottom() {
        let count = {};
        for (let key in CrewState) {
          count[key] = Math.ceil(Math.random() * 20 + 20);
        }
        return count;
      },
      // 获取数组中最大的一个，用于计算胶囊图宽度
      getArrMaxLen(list){
        let max = 0;
        list.forEach(i => {
          if(i.length > max) max = i.length;
        })
        return max;
      },
      // 获取机组状态,传入转速测点,1正常，0维修，2停机
      getCrewState(chat) {
        if(!chat.kksValue || (Date.now() - chat.kksValue.timestamp) > (24 * 3600 * 1000) ) return 0;
        if(chat.kksValueR > 1) return 1;
        return 2;
      }
    }
  }
</script>

<style lang="scss" scoped>
  .crew-monitoring {
    position: relative;
    width: 100%;
    height: 100%;

    .title {
      font-size: 1.625rem;
      color: $color-cyan;
      @extend %pos-center;
      top: 0;
    }

    .number {
      width: 30%;
      @extend %pos-center;
      top: 3.75rem;
      display: flex;
      justify-content: space-between;

      .num {
        // transform: scale(0.9);
      }
    }

    .model {
      width: 40%;
      height: calc(100% - 5rem);
      @extend %pos-center;
      bottom: 1.25rem;

      img {
        width: auto;
        height: 50%;
        @extend %pos-center;
        top: 0;
        bottom: 0;
        transform: translateX(-1.5rem);
      }
      
      .name {
        width: 6rem;
        height: 2.25rem;
        border-radius: 4px;
        background: rgba(0, 0, 0, 0.20);
        border: 1px dashed $color-cyan;
        @extend %flex-center;
        @extend %pos-center;
        top: 62%;
      }
      
      .name-run{
        border-color: $color-red;
        background: rgba($color: $color-red, $alpha: 0.3);
        animation: switch 2s infinite;
      }
      .name-stop{
        border-color: $color-green;
        background: rgba($color: $color-green, $alpha: 0.3);
      }
      .name-error{
        border-color: $color-grey;
        background: rgba($color: $color-grey, $alpha: 0.3);
      }
      @keyframes switch
      {
      	0% {
          background: rgba($color: $color-red, $alpha: 0.3);
        }
      	50% {
          background: rgba($color: $color-red, $alpha: 0.7);
        }
        100% {
          background: rgba($color: $color-red, $alpha: 0.3);
        }
      }
      
      $win-width: 40%;
      $win-pos: 0;
      .roll-left-top {
        width: $win-width;
        height: 30vh;
        position: absolute;
        top: 0;
        left: $win-pos;
      }
      .roll-right-top {
        width: $win-width;
        height: 28vh;
        position: absolute;
        top: 5%;
        right: $win-pos;
      }
      .roll-left-bottom {
        width: $win-width;
        height: 30vh;
        position: absolute;
        left: $win-pos;
        bottom: 14%;
      }
      .roll-right-bottom {
        width: $win-width;
        height: 40vh;
        position: absolute;
        right: $win-pos;
        bottom: 3%;
      }
      
      .win-list{
        height: 100%;
        line-height: 1.5rem;
        .win-item{
          display: flex;
          align-items: center;
          .win-item-left {
            text-align: right;
            margin-right: 1rem;
            width: 55%;
          }
          .win-item-right {
            text-align: left;
          }
        }
      }
      .flex-down{
        display: flex;
        flex-direction: column;
        justify-content: flex-end;
      }
      
      /deep/.el-scrollbar__wrap {
        overflow-x: hidden;
      }
    }

    .block {
      width: 30%;
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      padding: 1% 1.5%;
      box-sizing: border-box;
    }

    .left {
      position: absolute;
      left: 0;
    }

    .right {
      position: absolute;
      right: 0;
    }

    .border-bg {
      height: 49%;
      background-image: url(../assets/img/border-big.png);
      background-size: 100% 100%;
    }

    .border-sm {
      height: 31.5%;
      background-image: url(../assets/img/border-small.png);
      background-size: 100% 100%;
    }

    .chart-main {
      height: calc(100% - 2.5rem);
      box-sizing: border-box;
      padding: 1.25rem;
      display: flex;
      align-items: center;

      .chart-count {
        width: 20%;
        height: 11.25rem;
        box-sizing: border-box;
        padding: 0 2%;
      }

      .chart-chart {
        // width: 80%;
        width: 100%;
      }
      
      .chart-nums{
        width: 100%;
        height: 100%;
        display: flex;
        flex-wrap: wrap;
        
        .chart-num {
          width: 33.3%;
          height: 33.3%;
          transform: scale(0.9);
          @extend %flex-center;
          flex-direction: column;
        }
      }
      
      .single-row{
        width: 100%;
        height: 33.3%;
        display: flex;
        
        .single-col{
          height: 100%;
        }
      }
    }


    .chart-title {
      font-size: 1.125rem;
      color: $color-cyan;
      line-height: 3rem;
    }
  }
</style>
