<!-- 电厂选择页 -->
<template>
  <div class="factory">
    <img class="left-border" src="../assets/img/border-left.png" />
    <img class="right-border" src="../assets/img/border-right.png" />
    <div class="title">
	  <img class="logo" src="../assets/img/logo-small.png" />
      <span class="txt">{{title}}</span>
    </div>
    <user-info class="user-info" />
    <div class="main" v-loading="loading" :element-loading-background="loadingColor">
      <chart-map ref="ChartMap" id="ChartMap" class="chart-map" :chartData="factoryList" @selectFactory="selectFactory" @clickFactory="clickFactory" />
      <!-- 关闭 -->
      <transition name="list">
        <div v-if="!factoryItem" class="factory-block factory-list">
          <div class="factory-item" v-for="fac of factoryList" :key="fac.plantId" @mouseover="showFactory(fac)" @click="goPage(fac)">
            <div class="factory-name">{{fac.plantName}}</div>
          </div>
        </div>
      </transition>
      <!-- 展开 -->
      <transition name="item">
        <div v-if="factoryShow" class="factory-block factory-sign" @mouseleave="closeFactory" @click="goPage(factoryItem)">
        <!-- <div v-if="factoryShow" class="factory-block factory-sign" @click="goPage(factoryItem)"> -->
          <div class="factory-name">{{factoryItem.plantName}}</div>
          <div class="y-line" :style="{height: (factoryItem.plantDevices.length > 11 ? 10 * 4.75 + 'rem' : (factoryItem.plantDevices.length - 1) * 4.75 + 'rem')}"></div>
          <div class="crew-list">
            <div class="crew-item" v-for="(dev,i) of factoryItem.plantDevices.slice(0,11)" :class="dev.runstate == null ? 'crew-item-error' : dev.runstate ? 'crew-item-run' : 'crew-item-stop'"
              :style="{'align-self': i % 2 !== 1 ? 'flex-start' : 'flex-end'}" :key="dev.deviceId">
              <span>{{dev.shortName}}</span>
              <span>{{dev.runstate == null ? '检修' : dev.runstate ? '运行' : '停机'}}</span>
              <div class="x-line" :class="i % 2 !== 1 ? 'x-line-s' : 'x-line-l'">
                <img class="x-line-arrow" src="../assets/img/arrow-double-s.png" />
              </div>
            </div>
          </div>
          <div class="crew-list crew-list2" v-if="factoryItem.plantDevices.length > 11">
            <div class="crew-item" v-for="(dev,i) in factoryItem.plantDevices.slice(11)" :class="dev.runstate == null ? 'crew-item-error' : dev.runstate ? 'crew-item-run' : 'crew-item-stop'"
              :style="{'align-self': i % 2 !== 1 ? 'flex-start' : 'flex-end'}" :key="dev.deviceId">
              <span>{{dev.shortName}}</span>
              <span>{{dev.runstate == null ? '检修' : dev.runstate ? '运行' : '停机'}}</span>
              <div class="x-line x-line-m"></div>
            </div>
          </div>
        </div>
      </transition>
    </div>
  </div>
</template>

<script>
  import {
    CONFIG,
    ChartStyle
  } from '@/common/const.js'
  import UserInfo from '@/components/UserInfo'
  import ChartMap from '@/components/Charts/ChartMap'
  import Factory from '@/api/factory.js';
  import User from '@/api/user.js';
  export default {
    components: {
      UserInfo,
      ChartMap
    },
    data() {
      return {
        loading: false,
        loadingColor: ChartStyle.loadingColor,
        title: CONFIG.TITLE,
        // 电厂列表
        factoryList: [],
        factoryShow: false, // 选择展开的电厂
        factoryItem: null, // 选择展开的电厂
        socket: null, // socket
        socketData: null,
      };
    },
    created() {
      this.getFactoryList();
      this.initSocket();
    },
    beforeDestroy() {
      this.closeSocket();
    },
    methods: {
      initData() {
        if(!this.factoryItem) return;
        this.factoryItem.plantDevices.forEach(i => i.runstate = this.socketData[i.deviceId]);
      },
      // 初始化socket
      initSocket() {
        this.socket = new WebSocket('ws://' + CONFIG.SOCKET + '/runningState/deviceInfo', [this.$x_user.token.split(' ')[1]]);
        this.socket.onopen = () => console.log('socket_factory success');
        this.socket.onerror = e => {
          console.log('socket_factory error', e);
          User.getRoleList(); // 捕获错误，然后发送一个请求，因为可能是token导致的socket连接错误，发送请求后如果是token过期，会自动注销用户
        }
        this.socket.onmessage = msg => {
          try{
            const data = JSON.parse(msg.data);
            // console.log('socket_factory data', msg);
            // console.log('socket_factory data', data);
            if (!data) return;
            this.socketData = data;
            this.initData();
          }catch(e){
            console.log(e);
          }
        }
      },
      // 关闭socket
      closeSocket() {
        if (this.socket) {
          this.socket.close();
          this.socket = null;
        }
      },
      // 获取电厂列表
      async getFactoryList() {
        this.loading = true;
        try {
          let res = await Factory.getPlantList();
          res.forEach(i => {
            i.name = i.plantName;
            i.value = [i.latitude, i.longitude];
            // 电厂简称
            let arr = i.plantName.match(/国网(.+)厂/);
            i.shortName = arr ? arr[1] : i.plantName;
            // 机组简称
            i.plantDevices.forEach(j => {
              let arr2 = j.deviceName.match(/^.+(\d.+)/);
              j.shortName = arr2 ? arr2[1] : j.deviceName;
            })
          })
          this.factoryList = res;
        } catch (e) {
          console.log(e);
        }
        this.loading = false;
      },
      // 选择电厂
      clickFactory(i) {
        this.goPage(this.factoryList[i]);
      },
      selectFactory(i) {
        if(i !== undefined) this.showFactory(this.factoryList[i]);
        else this.closeFactory();
      },
      // 页面跳转
      goPage(item) {
        this.$store.commit('factoryList', null);
        this.$store.commit('factory', null);
        this.$store.commit('crew', null);
        this.$store.commit('allData', null);
        let endTime = Date.now() + 3600 * 1000 * 24; // 24h后过期
        localStorage.setItem('electric_factoryList', JSON.stringify({
          data: this.factoryList,
          endTime
        }));
        localStorage.setItem('electric_factory', JSON.stringify({
          data: item,
          endTime
        }));
        this.$router.push('/', () => {}, () => {}); // 加后面两个空回调方法，是为了解决一个router的报错
      },
      // 展开电厂
      showFactory(item) {
        if(!this.socketData) {
		  if(document.getElementsByClassName('el-message').length === 0) this.$message.error('暂未获取到机组数据，请稍后重试！'); // 防止重复提示
          return;
        }
        this.factoryItem = item;
        this.initData();
        // 加上延迟,因为有动画
        setTimeout(()=>{
          this.factoryShow = true;
        }, 100)
      },
      // 收起电厂
      closeFactory() {
        this.factoryShow = false;
        setTimeout(()=>{
          this.factoryItem = null;
        }, 100)
      }
    }
  };
</script>

<style lang="scss" scoped>
  $line-color: #00CCF7;
  
  .list-enter-active, .list-leave-active {
    transition: all .1s;
  }
  .list-enter, .list-leave-to {
    opacity: 0;
    transform: translateX(30px);
  }
  
  .item-enter-active, .item-leave-active {
    transition: all .1s;
  }
  .item-enter, .item-leave-to {
    opacity: 0;
    transform: translateX(30px);
  }

  .factory {
    width: 100%;
    height: 100%;
    overflow: hidden;
    position: relative;
    background-image: url(../assets/img/bg.png);
    @extend %background-center;

    .left-border {
      position: absolute;
      left: 0;
      height: 100%;
    }

    .right-border {
      position: absolute;
      right: 0;
      height: 100%;
    }

    .title {
      @extend %pos-center;
      // width: 58.75rem;
      width: 64rem;
      height: 4.875rem;
      background-image: url(../assets/img/title-bg.png);
      @extend %background-center;
	  
	  .logo{
		  width: auto;
		  height: 3rem;
		  margin-right: 0.5rem;
		  position: relative;
		  top: 0.5rem;
	  }

      .txt {
        font-size: 2.5rem;
        font-weight: bold;
        letter-spacing: 0.25rem;
        @extend %txt-gradients;
      }
    }

    .user-info {
      width: calc((100% - 58.75rem) / 2);
      position: absolute;
      top: 0.8rem;
      right: 0;
    }

    .main {
      @extend %bg-position;
      display: flex;
      padding: 1.5% 15% 0;
      box-sizing: border-box;

      .chart-map {
        width: 60%;
        height: 100%;
      }

      .factory-block {
        width: 40%;
        height: 100%;
        padding: 3% 0;
        box-sizing: border-box;

        .factory-name {
          width: 9rem;
          height: 8.875rem;
          background-image: url(../assets/img/circle.png);
          @extend %background-center;
          @extend %flex-center;
          font-size: 1.25rem;
          padding: 1.5rem;
          box-sizing: border-box;
          margin-right: 3rem;
          z-index: 1;
        }

        .crew-list {
          width: 16.875rem;
          display: flex;
          flex-direction: column;

          .crew-item {
            width: 11.625rem;
            height: 4.75rem;
            @extend %background-center;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 1.5rem;
            box-sizing: border-box;
            position: relative;
          }

          .crew-item-run {
            background-image: url(../assets/img/crew-run.png);
          }
          .crew-item-stop {
            background-image: url(../assets/img/crew-stop.png);
          }
          .crew-item-error {
            background-image: url(../assets/img/crew-error.png);
          }
        }

        .crew-list2 {
          position: relative;
          left: -3.125rem;
          height: 52.25rem;
        }

        .x-line {
          // height: 0.0625rem;
          height: 1px;
          background-color: $line-color;
          position: absolute;
		  top: 0;
		  bottom: 0;
		  margin: auto;
          display: flex;
          justify-content: center;
          align-items: center;

          .x-line-arrow {
            width: 0.7rem;
            height: auto;
          }
        }

        .x-line-m {
          width: 4.4rem;
          left: -3.3rem;
        }

        .x-line-s {
          width: 8.6rem;
          left: -7.5rem;
        }

        .x-line-c {
          width: 9.4rem;
          left: -8.3rem;
        }

        .x-line-l {
          width: 13.9rem;
          left: -12.8rem;
        }

      }

      .factory-list {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        padding-left: 10%;

        .factory-item {
          height: 30%;
          display: flex;
          align-items: center;
          // justify-content: center;
          position: relative;
          cursor: pointer;
        }

        .arrow {
          width: 3rem;
          height: auto;
          position: absolute;
          right: 8%;
          cursor: pointer;
        }

        .y-line {
          // width: 0.0625rem;
          width: 1px;
          background-color: $line-color;
          position: absolute;
          top: 0;
          bottom: 0;
          margin: auto;
          left: 4.5rem;
        }
      }

      .factory-sign {
        display: flex;
        align-items: center;
        position: relative;
        cursor: pointer;

        .arrow {
          width: 3rem;
          height: auto;
          cursor: pointer;
          margin-right: 1rem;
        }

        .y-line {
          // width: 0.0625rem;
          width: 1px;
          background-color: $line-color;
          position: absolute;
          top: 0;
          bottom: 0;
          margin: auto;
          left: 4.5rem;
        }
      }
    }
  }
</style>
