<template>
  <div class='map-view'>
    <van-nav-bar :title="`${floorName}平面图`" @click-left='backPage'>
      <template #left>
        <van-icon name="arrow-left" size="18" color="#333333" />
      </template>
    </van-nav-bar>
    <div id="bind-map-content">
      <canvas id="bind-canvas" ref="bind-canvas" tabindex="0"></canvas>
      <!-- 地图底部操作按钮 -->
      <div class='strip-bottom'>
        <canvasFun @fit='fit' @showText='showText' ref='canvasFun'></canvasFun>
      </div>
      <floor-list ref="fList" class="bind-floor-list" v-if='floorsArr.length>0' :floorsArr='floorsArr'
        @emitFloor='emitFloor'></floor-list>
      <div class="change-direction" @click='changeOri'>
        <i class="iconfont wanda-hengshuping"></i>
      </div>
    </div>
  </div>
</template>
<script>
/**
 * 平面图展示
 */
import Vue from 'vue'
import { mapGetters } from 'vuex'
import { NavBar, Toast } from 'vant'
import floorList from "@/components/floorMap/floorList.vue"
import canvasFun from '@/components/floorMap/canvasFun'
import { readGroup, queryStatis, graphQuery } from '@/api/public'
import { queryShops } from '@/api/equipmentList.js'
import { FloorView } from '@/lib/FloorView'
import { FloorScene } from '@/lib/FloorScene'
import { STopologyParser } from '@/lib/parsers/STopologyParser'

import { TipelineItem } from '@/lib/items/TipelineItem'
import { SImageLegendItem } from '@/lib/items/SImageLegendItem'

import { SImageItem, SImageShowType, SGraphItem } from '@saga-web/graph/lib'
import { ProjectRf } from '@saga-web/feng-map'
import { SFloorParser, ItemOrder, ItemColor, SPolygonItem, SBoardItem } from '@saga-web/big'
import { SColor } from '@saga-web/draw/lib'
Vue.use(NavBar).use(Toast)
export default {
  name: 'MapView',
  props: {},
  components: { floorList, canvasFun },
  computed: {
    ...mapGetters(['plazaId', 'fmapID', 'haveFengMap', 'bunkObj', 'floorsArr', 'categoryId']),
  },
  data() {
    return {
      view: '',
      scene: '',
      mapServerURL: "http://map.wanda.cn/editor",
      canvasLoading: false,
      floorid: '', //楼层id
      floorName: '', //楼层名
      count: 0, // 顶楼为多张图时计数器
      topologyParser: null, // 解析器数据
      fParser: null, // 底图解析器
      direction: '竖屏',
    }
  },
  props: {},
  beforeMount() { },
  mounted() {
    window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", () => {
      this.clearGraphy();
      setTimeout(() => {
        if (window.orientation === 0 || window.orientation === 180) {
          console.log("竖屏");
        }
        if (window.orientation === 90 || window.orientation === -90) {
          console.log("横屏");
        }
        document.getElementById("bind-canvas").width = document.getElementById("bind-map-content").offsetWidth;
        document.getElementById("bind-canvas").height = document.getElementById("bind-map-content").offsetHeight;
        this.init(this.floorid)
      }, 500)
    }, false);
    this.$nextTick(() => {
      document.getElementById("bind-canvas").width = document.getElementById("bind-map-content").offsetWidth;
      document.getElementById("bind-canvas").height = document.getElementById("bind-map-content").offsetHeight;
    })
  },
  methods: {
    backPage() {
      if (this.direction === '横屏') {
        this.roateY()
        this.direction = '竖屏'
      }
      this.$router.go(-1);
    },
    // 切换楼层
    emitFloor(floorObj) {
      if (floorObj) {
        this.$nextTick(() => {
          this.floorid = floorObj.gname;
          this.floorName = floorObj.code;
          this.init(floorObj.gname);
        })
      }
    },
    init(floorid) {
      // this.canvasLoading = true
      Toast.loading({
        duration: 0, // 持续展示 toast
        message: '加载中...',
        forbidClick: true,
      });
      // this.floorid = floorid
      // this.$refs.canvasFun.isShow = false
      setTimeout(() => {
        this.clearGraphy()
        this.scene = new FloorScene()
        if (this.haveFengMap == 1) {
          this.scene.selectContainer.connect('listChange', this, this.listChange)
          this.getGraphDetail().then((res) => {
            if (res.Content.length == 1) {
              const data = res.Content[0]
              if (data.MaxY && data.MinX) {
                window.fengmapData.maxY = data.MaxY
                window.fengmapData.minX = data.MinX
              }
            }
            this.parserData(floorid)
          })
          // this.parserData(floorid);
        } else if (this.haveFengMap == 0) {
          this.view.scene = this.scene
          this.readGraph()
        } else {
          this.canvasLoading = false
          Toast.clear();
        }
      }, 100)
    },
    // 解析底图
    parserData(floor) {
      if (floor == 'g80') {
        // 屋顶
        if (window.fengmapData.frImg) {
          const pj = this.fmapID.split('_')[0]
          // 单张图片
          if (!ProjectRf[pj]) {
            let imgItem = new SImageItem(null, `${this.mapServerURL}/webtheme/${this.fmapID}/${window.fengmapData.frImg}`)
            imgItem.showType = SImageShowType.AutoFit
            imgItem.connect('imgLoadOver', this, () => {
              this.readGraph()
            })
            this.scene.addItem(imgItem)
            this.view.scene = this.scene
            // this.view.fitSceneToView()
          } else {
            // 多张图
            try {
              // 初始化0
              this.count = 0
              ProjectRf[pj].forEach((t) => {
                const item = new SImageItem(null, `${this.mapServerURL}/webtheme/${this.fmapID}/${t.name}`)
                item.width = t.width
                item.height = t.height
                item.moveTo(t.x, t.y)
                item.connect('imgLoadOver', this, () => {
                  this.countRf(ProjectRf[pj].length)
                })
                this.scene.addItem(item)
              })
              this.view.scene = this.scene
            } catch (e) {
              console.log(e)
            }
          }
        } else {
          // 屋顶图不为图片
          this.readBaseMap(floor)
        }
      } else {
        if (window.fengmapData.gnameToGid[floor]) {
          this.readBaseMap(floor)
        } else {
          console.log('楼层不正确')
        }
      }
    },
    // 解析楼地板
    loadBoard(floor) {
      window.fengmapData.loadFloor(floor, (res) => {
        const zone = new SBoardItem(null, res)
        this.scene.addItem(zone)
      })
    },
    readBaseMap(floor) {
      this.loadBoard(window.fengmapData.gnameToGid[floor])
      window.fengmapData.parseData(window.fengmapData.gnameToGid[floor], (res) => {
        if (res.err) {
          console.log('errr', res.err)
          return
        }
        this.fParser = new SFloorParser(null)
        this.fParser.parseData(res)
        this.fParser.spaceList.forEach((t) => {
          this.scene.addItem(t)
          t.nameSize = 12
          t.nameColor = '#2a2a2a'
          if (t.data.Name && this.bunkObj[t.data.Name]) {
            t.name = this.bunkObj[t.data.Name].brandname
          } else {
            // t.name = t.data.Name
            t.name = ''
          }
        })
        this.fParser.wallList.forEach((t) => this.scene.addItem(t))
        this.fParser.virtualWallList.forEach((t) => this.scene.addItem(t))
        this.fParser.doorList.forEach((t) => this.scene.addItem(t))
        this.fParser.columnList.forEach((t) => this.scene.addItem(t))
        this.fParser.casementList.forEach((t) => this.scene.addItem(t))
        this.view.scene = this.scene
        // this.view.fitSceneToView()
        this.readGraph()
      })
    },
    readGraph() {
      this.readGroup()
        .then((data) => {
          if (data.Result == 'failure') {
            this.$store.commit('SETISMESSAGE', false)
            this.view.fitSceneToView()
            this.view.minScale = this.view.scale
            if (this.$refs.canvasFun) {
              this.$refs.canvasFun.everyScale = this.view.scale
            }
            Toast.clear();
            return
          } else {
            if (
              data.Data[0].Elements.Nodes.length === 0 &&
              data.Data[0].Elements.Markers.length === 0 &&
              data.Data[0].Elements.Relations.length === 0
            ) {
              this.$store.commit('SETISMESSAGE', false)
            } else {
              this.$store.commit('SETISMESSAGE', true)
            }
          }
          // 无返回Data处理
          if (!(data.Data && data.Data.length)) {
            this.view.fitSceneToView()
            this.view.minScale = this.view.scale
            if (this.$refs.canvasFun) {
              this.$refs.canvasFun.everyScale = this.view.scale
            }
            return false
          }
          // // 请求回来的备注
          // if (data.Data && data.Data[0].Note) {
          //   let note = data.Data[0].Note
          //   bus.$emit('queryRemarksMethods', note)
          // } else {
          //   bus.$emit('queryRemarksMethods', '')
          // }
          // //土建装饰的图例展示
          // if (this.$cookie.get('categoryId') == 'SCPZ') {
          //   let scpzTable = [],
          //     arr = []
          //   scpzTable = data.Data[0].Elements.Nodes || []
          //   console.log(scpzTable)
          //   if (scpzTable.length > 0) {
          //     scpzTable.forEach((e) => {
          //       if (e.Properties.ItemExplain) {
          //         let obj = e
          //         arr.push(obj)
          //       }
          //     })
          //   }
          //   console.log(arr)
          //   this.$store.commit('SETSCPZTABLE', arr)
          // }
          // if (data.Data[0].Elements.Nodes.length > 0) {
          //   this.$store.commit('SETTYPENUM', '')
          //   let Lengd = data.Data[0].Elements.Nodes
          //   Lengd.forEach((el) => {
          //     if (el.Type == 'Image' && el.Num > 1) {
          //       console.log(el.Num)
          //       this.$store.commit('SETTYPENUM', el.Num)
          //     }
          //   })
          // }
          // 放到后边 $cookie graphId
          // this.$cookie.set('graphId', data.Data[0].ID, 3)
          // if (this.$cookie.get('graphId')) {
          //   // 得到graphId 就请求图例
          //   // 除土建装饰之外的图例展示 包括楼层功能
          //   bus.$emit('queryViewMethods')
          // }
          this.topologyParser = new STopologyParser(null)
          this.topologyParser.parseData(data.Data[0].Elements)
          // 多边形
          this.topologyParser.zoneLegendList.forEach((t) => {
            this.scene.addItem(t)
            // t.connect('legendItemClick', t, this.handleClickLegendItem)
          })
          // 增加文字
          this.topologyParser.textMarkerList.forEach((t) => {
            this.scene.addItem(t)
          })
          // 增加图片
          this.topologyParser.imageMarkerList.forEach((t) => {
            this.scene.addItem(t)
          })
          // 增加直线
          this.topologyParser.lineMarkerList.forEach((t) => {
            this.scene.addItem(t)
          })
          // 增加图标类图例
          this.topologyParser.imageLegendList.forEach((t) => {
            this.scene.addItem(t)
            // t.connect('legendItemClick', t, this.handleClickLegendItem)
          })
          // 增加管线类
          // 增加图标类图例
          this.topologyParser.relationList.forEach((t) => {
            t.selectable = true
            this.scene.addItem(t)
            // t.connect('legendItemClick', t, this.handleClickLegendItem)
          })
          // this.view.fitSceneToView()
          // this.view.minScale = this.view.scale
          if (this.$refs.canvasFun) {
            this.$refs.canvasFun.everyScale = this.view.scale
          }
          this.view.fitSceneToView()
          this.view.minScale = this.view.scale
          this.canvasLoading = false
          Toast.clear();
        })
        .catch(() => {
          this.canvasLoading = false
          Toast.clear();
        })
    },
    // 顶楼为多张图时计数器
    countRf(len) {
      this.count++
      if (len == this.count) {
        this.readGraph()
      } else {
        console.log('所有图片未加载完成')
      }
    },
    clearGraphy() {
      if (this.view) {
        this.view.scene = null
        return
      }
      this.view = new FloorView("bind-canvas");
    },
    listChange(item, ev) {
      if (ev[0].length) {
        // 选中电井设置电井关联的商铺高亮
        this.setHightLight(ev[0])
      } else {
        this.clearHightLight()
      }
    },
    // 选中电井关联的商铺高亮
    setHightLight(arr) {
      this.clearHightLight()
      arr.forEach((item) => {
        let location = item.data.AttachObjectIds[0] ? item.data.AttachObjectIds[0].id : ''
        // 添加了位置类型并且选中的类型为电井类型
        if (
          (item.data.GraphElementId == '100050' ||
            item.data.GraphElementId == '100055' ||
            item.data.GraphElementId == '100056' ||
            item.data.GraphElementId == '100057') &&
          location
        ) {
          let getParams = {
            plazaId: this.plazaId,
            floor: this.floorid,
            keyword: `${location}:wellnum;`,
          }
          queryShops({ getParams }).then((res) => {
            let shopsnumList = []
            if (res.data && res.data.length) {
              for (let floor in res.data[0]) {
                if (res.data[0][floor].length) {
                  res.data[0][floor].forEach((v) => {
                    shopsnumList = shopsnumList.concat(v.shopsnumList.split(','))
                  })
                }
              }
            }
            if (shopsnumList.length) {
              this.fParser.spaceList.forEach((item) => {
                if (shopsnumList.findIndex((name) => name == item.data.Name) != -1) {
                  item.highLightFlag = true
                  item.zOrder = 30
                }
              })
            }
          })
        }
      })
    },
    // 清除电井关联商铺的高亮状态
    clearHightLight() {
      ItemColor.spaceHighColor = new SColor('#FBF2CC')
      this.fParser.spaceList.forEach((item) => {
        item.highLightFlag = false
        item.zOrder = ItemOrder.spaceOrder
      })
    },
    // 适配底图到窗口
    fit() {
      this.view.fitSceneToView()
    },
    // 小眼睛控制显示铺位名称
    showText(val) {
      this.fParser.spaceList.forEach((t) => {
        t.showBaseName = val
      })
    },
    // 读取数据
    readGroup() {
      const data = {
        BuildingID: '1',
        FloorID: this.floorid,
        categoryId: this.categoryId,
        projectId: this.plazaId,
        Pub: true,
      }
      return readGroup(data)
    },
    // 获取图最大最小值
    getGraphDetail() {
      const categoryId = this.categoryId
      const data = {
        Filters: `categoryId='${categoryId}';projectId='${this.plazaId}';BuildingID='1';FloorID='${this.floorid}';isPub=true`,
      }
      return graphQuery(data)
    },
    changeOri() {
      if (this.direction === '竖屏') {
        this.roateX()
        this.direction = '横屏'
      } else if (this.direction === '横屏') {
        this.roateY()
        this.direction = '竖屏'
      }
    },
    roateX() {
      console.log('横屏')
      window.webkit &&
        webkit.messageHandlers.cordova_iab.postMessage(
          JSON.stringify({
            method: 'roateX',
          })
        )
    },

    // 竖屏
    roateY() {
      console.log('竖屏')
      window.webkit &&
        webkit.messageHandlers.cordova_iab.postMessage(
          JSON.stringify({
            method: 'roateY',
          })
        )
    },
  },
  watch: {
    '$route.params.floor': {
      handler(floor) {
        this.$nextTick(() => {
          this.floorid = floor.FloorId;
          this.floorName = floor.FloorName;
          let index = this.floorsArr.findIndex(item => {
            return item.gname === floor.FloorId
          })
          let item = {
            gname: floor.FloorId,
            code: floor.FloorName
          }
          this.$refs.fList.tabFloor(item ,index);
          // this.$refs.fList.currentFloorId = floor.FloorId;
          // this.init(floor.FloorId);
        })
      },
      immediate: true,
      deep: true
    }
  },
}
</script>
<style lang='less' scoped>
.map-view {
  width: 100%;
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  #bind-map-content {
    width: 100%;
    height: calc(100% - 50px);
    position: relative;
    overflow: hidden;
    .bind-floor-list {
      position: fixed;
      top: 65px;
      right: 16px;
    }
    .strip-bottom {
      position: fixed;
      bottom: 60px;
      right: 16px;
    }
    .change-direction {
      position: fixed;
      bottom: 60px;
      left: 16px;
      .wanda-hengshuping {
        font-size: 26px;
      }
    }
  }
}
// 横屏
@media screen and (orientation: landscape) {
  .map-view {
    /deep/ .van-nav-bar {
      height: 40px;
    }
    #bind-map-content {
      .bind-floor-list {
        position: fixed;
        top: 47px;
        right: 16px;
      }
      .strip-bottom {
        position: fixed;
        bottom: 15px;
        right: 60px;
      }
      .change-direction {
        position: fixed;
        bottom: 15px;
        left: 15px;
        .wanda-hengshuping {
          font-size: 26px;
        }
      }
    }
  }
}
</style>