<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 LegendItem">
          <i :style="{ backgroundColor:item.color }"/>
          {{ item.name }}
        </div>
      </div>
    </div>
    <!--    <PileHoleDetail ref="pileHoleDialog"/>-->
  </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} from "@/utils/EnumConst";
import ComponentHandle from "@/utils/ComponentHandle"

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

  },
  computed: {
    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,
      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',
              }
            ],
          },
        ],
      },
      LegendItem: {
        NotStated: {
          color: '#C1C1C1',
          name: this.$t("screen.notStart")
        },
        InProcess: {
          color: '#FF5454',
          name: this.$t("screen.inProcess")
        },
        Completed: {
          color: '#93D467',
          name: this.$t("screen.completed")
        },
        Deviation: {
          color: '#F6E65C',
          name: this.$t("screen.deviation")
        }
      }
    };
  },
  // 组件卸载前清空图层信息
  beforeDestroy() {
    this.destroyLayer(this.pileHoleLayer.cust.layerId, this.mapIns)
    this.destroyLayer(this.pileMachineLayer.cust.layerId, this.mapIns)
  },
  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.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.pileHoleList.forEach((item, index) => {
          const geom = new BDLayers.Lib.Overlays.FromGeoJson(Circle({
            radius: 0.4,
            coordinates: [item.lng, item.lat],
            symbol: [
              {
                lineColor: '#34495e',
                lineWidth: 1,
                polygonFill: '#1bbc9b',
                polygonOpacity: 0.2
              }
            ]
          }).geojson);

          geom.cust = item
          geom.on('click', (e) => {
            if (this.hisClickGeom) {
              this.hisClickGeom.updateSymbol([
                {
                  lineColor: '#34495e',
                  lineWidth: 1,
                  polygonFill: '#1bbc9b',
                  polygonOpacity: 0.2
                }
              ])
            }
            this.hisClickGeom = geom
            geom.updateSymbol([
              {
                lineColor: 'green',
                lineWidth: 1,
                polygonFill: '#1bbc9b',
                polygonOpacity: 0.2
              }
            ])
            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,
                      polygonFill: '#1bbc9b',
                      polygonOpacity: 0.2
                    }
                  ])
                }
                geom.closePopWindow();
              }
            });

          })
          this.pileHoleLayer.addGeometry(geom);
        })
      })
    },
    loaded(map) {
      this.mapIns = map
      this.pileHoleLayer = this.createLayer(map)
      this.pileMachineLayer = this.createLayer(map)
      this.loadPileHole()
      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/>
