
<!-- 底图 -->
<template>
    <div id='floor_base' v-loading='loading' ref='graphy'>
        <canvas :id='`canvas${id}`' :width='canvasWidth' :height='canvasHeight' tabindex='0'></canvas>
        <!-- 地图底部操作按钮 -->
        <div class='strip-bottom'>
            <canvasFun @fit='fit' @savePng='savePng' @saveSvg='saveSvg' @saveJson='saveJson' @scale='scale' @showText='showText' ref='canvasFun'></canvasFun>
        </div>
        <room-box ref='boxRoom'></room-box>
    </div>
</template>
<script>
import { SFengParser } from '@saga-web/feng-map'
import { SFloorParser, ItemOrder } from '@saga-web/big'
import { FloorView } from '@/lib/FloorView'
import { FloorScene } from '@/lib/FloorScene'
import RoomBox from '@/views/room/index'
import canvasFun from '@/components/floorMap/canvasFun'
import { readGroup, queryStatis } from '@/api/public'
import { queryShops } from '@/api/equipmentList.js'
import { STopologyParser } from '@/lib/parsers/STopologyParser'
import { mapGetters, mapActions } from 'vuex'
import { SImageItem } from '@saga-web/graph/lib'
import bus from '@/utils/bus.js'

// import { uuid } from "@/components/mapClass/until";

export default {
    data() {
        return {
            appName: '万达可视化系统',
            key: '23f30a832a862c58637a4aadbf50a566',
            mapServerURL: `http://map.wanda.cn/editor`,
            canvasWidth: 600,
            canvasHeight: 800,
            loading: false, // 限制重复查询
            view: null,
            urlMsg: {},
            canvasID: 'canvas',
            floorid: '', //楼层id
            topologyParser: null, // 解析器数据
            fParser: null, // 底图解析器
            wellMap: {} // 电井控制商铺映射
        }
    },
    props: {
        id: {
            default: '1',
            type: String
        },
        categoryId: {
            default: '',
            type: String
        },
        // 弹窗高度，适配底图高度使用
        modalHeight: {
            type: [Number, undefined],
            default: undefined
        },
        loadName: null,
        type: null
    },
    components: { RoomBox, canvasFun },
    computed: {
        ...mapGetters(['plazaId', 'fmapID', 'haveFengMap', 'bunkObj'])
    },
    methods: {
        ...mapActions(['getfmapID']),
        init(floorid) {
            // this.loading = true
            this.floorid = floorid
            this.mapSize()
            this.$refs.canvasFun.isShow = false
            setTimeout(() => {
                if (this.haveFengMap) {
                    this.clearGraphy()
                    this.scene = new FloorScene()
                    this.scene.selectContainer.connect('listChange', this, this.listChange)
                    if (this.canvasID != `canvas${this.id}`) {
                        this.canvasID = `canvas${this.id}`
                    }
                    this.parserData(floorid)
                }
            }, 100)
        },
        parserData(floor) {
            if (floor == 'g80') {
                // 屋顶
                if (window.fengmapData.frImg) {
                    let imgItem = new SImageItem(null, `${this.mapServerURL}/webtheme/${this.fmapID}/${window.fengmapData.frImg}`)
                    this.scene.addItem(imgItem)
                    this.view.scene = this.scene
                    this.view.minScale = this.view.scale
                    if (this.$refs.canvasFun) {
                        this.$refs.canvasFun.everyScale = this.view.scale
                    }
                    this.view.fitSceneToView()
                }
            } else {
                if (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)
                            if (t.data.Name && this.bunkObj[t.data.Name]) {
                                t.name = this.bunkObj[t.data.Name].detailtype
                            } else {
                                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.view.minScale = this.view.scale
                        if (this.$refs.canvasFun) {
                            this.$refs.canvasFun.everyScale = this.view.scale
                        }
                    })
                } else {
                    console.log('楼层不正确')
                }
            }
            this.readGroup(this.floorid).then(data => {
                this.loading = false
                if (data.Result == 'failure') {
                    this.$store.commit('SETISMESSAGE', false)
                    return
                } else {
                    this.$store.commit('SETISMESSAGE', true)
                }
                // 无返回Data处理
                if (!(data.Data && data.Data.length)) {
                    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 = []
                    scpzTable = data.Data[0].Elements.Nodes || []
                    this.$store.commit('SETSCPZTABLE', scpzTable)
                }
                // 放到后边 $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)
                })
                // 增加文字
                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)
                })
                // 增加管线类
                // 增加图标类图例
                this.topologyParser.relationList.forEach(t => {
                    this.scene.addItem(t)
                })
                this.view.fitSceneToView()
            })
        },
        clearGraphy() {
            if (this.view) {
                this.view.scene = null
                return
            }
            this.view = new FloorView(`canvas${this.id}`)
        },
        listChange(item, ev) {
            if (ev[0].length) {
                let selectItem1 = ev[0][0],
                    name = selectItem1.data.Name,
                    location = selectItem1.data.AttachObjectIds[0] ? selectItem1.data.AttachObjectIds[0].id : ''
                if (name.slice(name.length - 2, name.length) == '机房') {
                    if (location) {
                        this.$refs.boxRoom.open({ name: name, type: this.type, location: location })
                    } else {
                        this.$message('未添加位置类型')
                    }
                }
                // 选中电井设置电井关联的商铺高亮
                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
                ) {
                    if (this.wellMap.hasOwnProperty(location)) {
                        this.wellMap[location].forEach(item => {
                            item.highLightFlag = true
                            item.zOrder = 30
                        })
                    } else {
                        let getParams = {
                            plazaId: this.plazaId,
                            floor: this.floorid,
                            keyword: `${location}:wellnum;`
                        }
                        queryShops({ getParams }).then(res => {
                            let shopsnumList = []
                            let shopsnumItemList = []
                            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
                                        shopsnumItemList.push(item)
                                    }
                                })
                                this.wellMap[location] = shopsnumItemList
                            }
                        })
                    }
                }
            })
        },
        // 清除电井关联商铺的高亮状态
        clearHightLight() {
            for (let key in this.wellMap) {
                this.wellMap[key].forEach(item => {
                    item.highLightFlag = false
                    item.zOrder = ItemOrder.spaceOrder
                })
            }
        },
        // 适配底图到窗口
        fit() {
            this.view.fitSceneToView()
        },
        // 保存为png
        savePng() {
            this.view.saveImage(`${this.loadName}.png`, 'png')
            //console.log(`${this.loadName}.png`)
        },
        // 保存为svg
        saveSvg() {
            this.view.saveSceneSvg(`${this.loadName}.svg`, 6400, 4800)
        },
        // 保存为json
        saveJson() {
            this.view.saveFloorJson(`${this.loadName}.json`)
        },
        // 缩放
        scale(val) {
            if (!this.view) {
                return
            }
            let scale = this.view.scale
            this.view.scaleByPoint(val / scale, this.canvasWidth / 2, this.canvasHeight / 2)
        },
        // 小眼睛控制显示铺位名称
        showText(val) {
            // this.topologyParser.zoneLegendList.forEach(t => {
            //     t.showText = val
            // })
            this.fParser.spaceList.forEach(t => {
                t.showBaseName = val
            })
        },
        // 读取数据
        readGroup(FloorID) {
            const data = {
                BuildingID: '1',
                FloorID: FloorID,
                categoryId: this.categoryId ? this.categoryId : this.$cookie.get('categoryId'),
                projectId: this.urlMsg.ProjectID,
                Pub: true
            }
            return readGroup(data)
        },
        // 地图尺寸
        mapSize() {
            this.canvasWidth = this.$refs.graphy.offsetWidth
            if (window.screen.height == '768') {
                this.canvasHeight = this.$refs.graphy.offsetHeight - 100
            } else {
                this.canvasHeight = 900
            }
            // 弹窗中底图高度适配
            if (this.modalHeight) {
                this.canvasHeight = this.modalHeight
            }
        },
        getEvent() {
            bus.$on('changeShow', res => {
                this.topologyParser.zoneLegendList.forEach(t => {
                    let id = t.data.GraphElementId
                    t.maskFlag = !(res.indexOf(id) > -1)
                })
                this.topologyParser.textMarkerList.forEach(t => {
                    let id = t.data.GraphElementId
                    t.maskFlag = !(res.indexOf(id) > -1)
                })
                this.topologyParser.imageMarkerList.forEach(t => {
                    let id = t.data.GraphElementId
                    t.maskFlag = !(res.indexOf(id) > -1)
                })
                this.topologyParser.lineMarkerList.forEach(t => {
                    let id = t.data.GraphElementId
                    t.maskFlag = !(res.indexOf(id) > -1)
                })
                this.topologyParser.imageLegendList.forEach(t => {
                    let id = t.data.GraphElementId
                    t.maskFlag = !(res.indexOf(id) > -1)
                })
                this.topologyParser.relationList.forEach(t => {
                    let id = t.data.GraphElementId
                    t.maskFlag = !(res.indexOf(id) > -1)
                })
            })
        }
    },
    watch: {
        'view.scale': {
            handler(n) {
                if (this.$refs.canvasFun) {
                    let s = (n * 10) / this.view.minScale
                    this.$refs.canvasFun.sliderVal = s > 1000 ? 1000 : s
                }
            }
        },
        haveFengMap(val) {
            if (val) {
                this.init(this.floorid)
            }
        }
    },
    mounted() {
        this.mapSize()
        this.getEvent()
    },
    created() {
        this.urlMsg = {
            categoryId: this.$cookie.get('categoryId'),
            ProjectID: this.plazaId,
            BuildingID: '1',
            FloorID: this.$cookie.get('floorMapId') || 'f1',
            fmapID: this.fmapID
        }
    }
}
</script>
<style lang="less" scoped>
#floor_base {
    position: relative;
    height: 100%;
    .fengMap {
        position: fixed;
        width: 100px;
        height: 100px;
        z-index: -1;
    }
    .strip-bottom {
        position: absolute;
        right: 0;
        bottom: 40px;
        width: 100%;
    }
}
</style>