<template>
  <div class="screen-container">
    <bd-map :center="[121.9580475686964, 30.949993496740227]" :loaded="loaded"/>
    <div class="screen-title-container"><span class="title-content">{{ $t("screen.title") }}</span></div>
    <content-block :title="$t('screen.consManage')" class="screen-left-container">
      <template v-slot:content>
        <div class="control-content">
          <div class="ctl-item">
            <el-input
              :placeholder="$t('common.typeInfo',{name: $t('common.content')})"
              v-model="searchVal"
              class="input-with-select"
            >
              <el-button slot="append" icon="el-icon-search"></el-button>
            </el-input>
          </div>
          <div class="ctl-item">
            <cons-unit-tree
              :placeholder="$t('common.select', {name: $t('cons.consUnit')})"
              v-model="consUnit"
            />
          </div>
        </div>
        <div class="machine-list">
          <div class="list-container-title">
            {{ $t("screen.machineList") }}
            <span v-if="loading" style="font-size: 10px;color: #fefefe;margin-left: 10px">
              {{
                $t("common.loading")
              }}
            </span>
          </div>
          <div class="content-list infinite-list-wrapper"
               v-infinite-scroll="loadMachine"
               :infinite-scroll-disabled="disabled"
          >
            <div v-for="item in machineList"
                 :class="{'list-item':true,'selected-item': selectMachine && item.id===selectMachine.id}"
                 :key="item.id" @click="handleMachineClick(item)">
              <i class="machine-status"
                 :style="{backgroundColor: MachineStatus[item.status].color }"/>
              {{ item.name }}({{ item.machineNum }})
            </div>
            <p v-if="noMore" class="no-more" style="margin-top: auto">{{ $t("common.noMore") }}</p>
          </div>
        </div>
      </template>
    </content-block>
    <div class="screen-right-container">
      <content-block :title="$t('screen.onlineMachine')" class="online-machine-block">
        <template v-slot:content>
          <div class="online-summery">
            <div class="machine-pie-chart">
              <pie-chart-block :optCfg="machineOpt"/>
            </div>
            <div class="machine-pie-legend">
              <div class="legend-item">
                <i :style="{ backgroundColor:machineOpt.color[0] }"/>
                <span>{{ $t('screen.onlineMachine') }}</span>
                <span>{{ machineStatusCnt.online || 0 }}</span>
              </div>
              <div class="legend-item">
                <i :style="{ backgroundColor:machineOpt.color[1] }"/>
                <span>{{ $t('screen.offlineMachine') }}</span>
                <span>{{ machineStatusCnt.offline || 0 }}</span>
              </div>
            </div>
          </div>
          <div class="online-list">
            <div class="list-item" v-for="item in onlineMachine">
              <span class="machine-name">{{ item.name }}</span>
              <span class="cons-unit">{{ item.machineNum }}</span>
            </div>
          </div>
        </template>
      </content-block>
      <MachineIndex v-if="selectMachine" :select-machine="selectMachine">
        <template v-slot:title-right="scop">
          <el-tooltip
            class="item"
            effect="dark"
            content="click to machine"
            placement="top"
          >
            <svg-icon icon-class="location" @click="()=>{locationMachine(scop.data)}"/>
          </el-tooltip>
          <el-tooltip
            class="item"
            effect="dark"
            content="close"
            placement="top"
          >
            <i class="el-icon-close" @click="()=>{locationClose()}" style="margin-left: 5px"/>
          </el-tooltip>
        </template>
      </MachineIndex>
      <div class="pile-status-legend">
        <div class="legend-item" v-for="item in PileHoleStatus.DIC">
          <i :style="{ backgroundColor:item.color }"/>
          {{ item.name }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import BdMap from "@/components/map/index.vue";
import Treeselect from "@riophae/vue-treeselect";
import ConsUnitTree from "@/views/cons/consUnit/ConsUnitTree.vue";
import ContentBlock from "@/views/cons/screen/ContentBlock.vue";
import PieChartBlock from "@/components/charts/PieChartBlock.vue";
import LineChartBlock from "@/components/charts/LineChartBlock.vue";
import {calcPileMachineOnOffline, getConsUnitMachine, listAllPileMachineInfo} from "@/api/cons/pileMachineInfo";
import {listPileHoleRealtimeIndex} from "@/api/cons/pileHoleInfo";
import maphandle from "@/components/map/maphandle";
import MachineIndex from "@/views/cons/screen/MachineIndex.vue";
import PileHoleDetail from "@/views/cons/screen/PileHoleDetail.vue";
import {copyObj} from "@/utils";
import {Circle} from "@/components/map/GeoJson";
import pileMachine from "./img/pile-machine.svg"
import {MachineStatus, PileHoleStatus} from "@/utils/EnumConst";
import ComponentHandle from "@/utils/ComponentHandle"

const gemoCache = {}
export default {
  components: {
    PileHoleDetail,
    MachineIndex,
    LineChartBlock,
    PieChartBlock,
    ContentBlock,
    ConsUnitTree,
    BdMap,
    Treeselect
  },
  mixins: [maphandle],
  props: {
    ws: {
      type: String,
      default: '',
    },

  },
  computed: {
    PileHoleStatus() {
      return PileHoleStatus
    },
    MachineStatus() {
      return MachineStatus
    },
    noMore() {
      return this.count >= 100
    },
    disabled() {
      return this.loading || this.noMore
    }
  },
  watch: {
    consUnit(val) {
      this.loadMachine()
    },
    searchVal(val) {
      this.searchValOnchange()
    },
    onlineMachine(val) {
      val && this.addMachineMarker()
    }
  },
  data() {
    return {
      mapIns: null,
      consUnit: null,
      searchVal: "",
      count: 10,
      loading: false,
      machineList: [],
      machineOriList: [],
      selectMachine: null,
      pileMachineLayer: null,
      realtimeInterVal: null,
      machineLatextIndex: {},
      pileHoleList: [],
      pileHoleLayer: null,
      geoms: [],
      machineStatusCnt: {},
      onlineMachine: [],
      hisClickGeom: null,
      machineOpt: {
        color: ['#006699', '#4cabce'],
        tooltip: {
          show: false
        },
        legend: {
          show: false,
          top: 0
        },
        label: {
          show: false,
        },
        emphasis: {
          label: {
            show: false,
          }
        },
        labelLine: {
          show: false
        },
        series: [
          {
            type: 'pie',
            radius: ['50%', '70%'],
            center: ['50%', '50%'],
            label: {
              show: false,
              position: 'center'
            },
            data: [
              {
                value: 19,
                name: 'online',
              },
              {
                value: 75,
                name: 'offline',
              }
            ],
          },
        ],
      },
      timer: null,
      layerOnLoad: false
    };
  },
  // 组件卸载前清空图层信息
  beforeDestroy() {
    this.destroyLayer(this.pileHoleLayer.cust.layerId, this.mapIns)
    this.destroyLayer(this.pileMachineLayer.cust.layerId, this.mapIns)
    this.timer && clearInterval(this.timer)
  },
  created() {

  },
  mounted() {

  },
  methods: {
    init() {
      this.loadMachine()
      this.loadMachineOnOffline()
      this.loadOnlineMachine()
    },
    loadMachine() {
      this.loading = true;
      getConsUnitMachine(this.consUnit).then((response) => {
        this.machineList = response.data
        this.machineOriList = copyObj(response.data)
        this.searchValOnchange()
        this.count = 100
        this.loading = false
      })
    },

    loadOnlineMachine() {
      listAllPileMachineInfo({
        status: "00"
      }).then(response => {
        this.onlineMachine = response.rows
      });
    },
    addMachineMarker() {
      this.pileMachineLayer.removeAll()
      this.onlineMachine.forEach(item => {
        let marker = new BDLayers.Lib.Overlays.Marker(`marker${item.id}`, [item.lng, item.lat], {
          symbol: {
            'textName': `${item.name}`,
            'textSize': 12,
            markerWidth: 45,
            markerHeight: 45,
            markerDx: 30,
            textDx: 30,
            textDy: 10,
            'markerFile': pileMachine,
          }
        });
        marker.on('click', () => {
          this.selectMachine = item
        })
        this.pileMachineLayer.addMarker(marker)
      })
    },
    searchValOnchange() {
      if (this.searchVal) {
        this.machineList = this.machineOriList.filter(item => `${item.name}(${item.machineNum})`.includes(this.searchVal))
      }
    },
    loadMachineOnOffline() {
      calcPileMachineOnOffline().then(response => {
        if (response.data) {
          const {online, offline} = response.data
          this.machineStatusCnt = response.data
          this.machineOpt.series[0].data = [{
            value: online,
            name: 'online'
          },
            {
              value: offline,
              name: 'offline'
            }]
        }
      })
    },
    loadPileHole() {
      listPileHoleRealtimeIndex({}).then(response => {
        this.pileHoleList = response.data
        this.calcPileHole(response.data)
      })
    },
    addPileHoleToMap(holes) {
      const geoms = []
      holes.map((item, index) => {
        const codeToStatus = PileHoleStatus.codeToStatus(item.consStatus);
        const geom = new BDLayers.Lib.Overlays.FromGeoJson(Circle({
          radius: 0.4,
          coordinates: [item.lng, item.lat],
          symbol: [
            {
              lineColor: '#34495e',
              lineWidth: 1,
              polygonFill: codeToStatus.color,
              polygonOpacity: 0.8
            }
          ]
        }).geojson);

        geom.cust = item
        geom.on('click', (e) => {
          if (this.hisClickGeom) {
            this.hisClickGeom.updateSymbol([
              {
                lineColor: '#34495e',
                lineWidth: 1,
                polygonOpacity: 0.8
              }
            ])
          }
          this.hisClickGeom = geom
          geom.updateSymbol([
            {
              lineColor: 'green',
              lineWidth: 1,
              polygonOpacity: 1
            }
          ])
          const pileHoleInfo = e.target.cust
          geom.setPopWindow({
            autoPan: true,
            content: `<div id='pop-window' class="window-content"></div>`
          });
          ComponentHandle.createComponent({
            wrapper: 'pop-window',
            component: PileHoleDetail,
            props: pileHoleInfo,
            onclose: () => {
              if (this.hisClickGeom) {
                this.hisClickGeom.updateSymbol([
                  {
                    lineColor: '#34495e',
                    lineWidth: 1
                  }
                ])
                this.hisClickGeom = null
              }
              geom.closePopWindow();
            }
          });
        })
        gemoCache[item.id].marker = geom
        geoms.push(geom)
      })
      geoms.length && this.pileHoleLayer.addGeometries(geoms);
      if (!this.layerOnLoad) {
        this.layerOnLoad = true
        this.mapIns.fitExtent(this.pileHoleLayer.getExtent());
      }
    },
    updatePileHole(newList) {
      newList.forEach(
        item => {
          if (gemoCache[item.id]) {
            const codeToStatus = PileHoleStatus.codeToStatus(item.consStatus);
            gemoCache[item.id].marker.updateSymbol([
              {
                lineColor: '#34495e',
                lineWidth: 1,
                polygonFill: codeToStatus.color,
                polygonOpacity: 0.8
              }
            ])
          }
        }
      )
    },
    calcPileHole(newList) {
      if (!newList || !newList.length) {
        return
      }
      const changeHole = []
      const addList = []
      newList.forEach(item => {
        // 先比对已经存在的是否是变更状态
        if (gemoCache[item.id] && gemoCache[item.id].consStatus !== item.consStatus) {
          gemoCache[item.id].consStatus = item.consStatus;
          changeHole.push(item)
        }
        if (!gemoCache[item.id]) {
          gemoCache[item.id] = item;
          addList.push(item);
        }
      })
      this.addPileHoleToMap(addList)
      this.updatePileHole(changeHole)
    },
    loaded(map) {
      this.mapIns = map
      this.pileHoleLayer = this.createLayer(map)
      this.pileMachineLayer = this.createLayer(map, 2)

      this.loadPileHole()
      this.timer = setInterval(() => {
        this.loadPileHole()
        this.loadOnlineMachine()
      }, 30000)
      this.init();
    },
    handleClick(e) {
    },
    handleMachineClick(item) {
      if (item.status === MachineStatus.offline.code) {
        return;
      }
      if (this.selectMachine && this.selectMachine.id === item.id) {
        this.locationClose()
        return
      }
      this.locationMachine(item)
      this.selectMachine = item
    },
    locationMachine(selectMachine) {
      this.mapIns.flyToPoint([selectMachine.lng, selectMachine.lat], {duration: 1000})
    },
    locationClose() {
      this.selectMachine = null
    },
  },
};
</script>
<style lang="scss" src="./index.scss" scoped/>
