<template>
    <div style="height:100%;overflow: auto;">
        <Row  type="flex" justify="end"  align="middle">
            <Button size="small"  @click="exportMap">打印</Button>
        </Row>
       <div v-if="reset" ref="divMap" id="map" class="efuture-map" :style="divStyle"></div>
    </div>
</template>

<script>
import 'ol/ol.css';
import { Map, View, Feature } from 'ol';
import { Style, Fill, Stroke, Text } from 'ol/style';
import LayerVector from 'ol/layer/Vector';
import SourceVector from 'ol/source/Vector';
import Polygon from 'ol/geom/Polygon';
import load from '@/components/base/load.js';
import ImageLayer from 'ol/layer/Image';
import ImageStatic from 'ol/source/ImageStatic';
import { Projection } from 'ol/proj';
import { getCenter } from 'ol/extent';
import html2Canvas from 'html2canvas';
import {defaults as defaultControls} from 'ol/control';
import pako from 'pako';
export default {
    mixins:[load],
    data () {
        return {
            map:null,
            initStyle:new Style({
                stroke:new Stroke({
                    color:'#17233d',
                    width:1
                }),
                fill:new Fill({
                    color:'rgba(255,255,255,0)'
                }),
                text:new Text({
                    font:'12px Calibri, sans-serif',
                    fill:new Fill({
                        color:'#000'
                    })
                })
            }),
            reset:true,
            lands:null,
            culMapInfo:null,
            mmfcode:'',
            data:[],
            adjustHeight:80,
            isImg:false,
            imgx:0,
            imgy:0
        };
    },
    computed:{
        divStyle () {
            let height = this.$Store.state.app.clientHeight - this.adjustHeight - 24;
            return 'height:' + height + 'px';
        }
    },
    props:{
        config:{
            type:Object,
            default:() => {}
        }
    },
    methods:{
        init () {
            if (!this.mmfcode) {
                return false;
            }
            let map = this.getMapInfo(this.mmfcode);
            if (map) {
                if (map.mapinfo) {
                    this.culMapInfo = JSON.parse(map.mapinfo);
                }
                if (map.shopinfo) {
                    this.shopinfo = map.shopinfo;
                    this.initShop(map.shopinfo);
                }
                this.getMapGeojson(map);
            } else {
                this.alert('楼层未导入平面图，请重新选择');
                return false;
            }
            return true;
        },
        setAdjustHeight (value) {
            this.adjustHeight = value;
        },
        initShop (shopinfo) {
            if (shopinfo && shopinfo.length > 0) {
                this.mapData = [];
                shopinfo.forEach(e => {
                    let tmp = {};
                    let pro = JSON.parse(e.pro);
                    tmp.code = pro.id;
                    tmp.name = pro.text;
                    if (pro.spcode) {
                        tmp.spcode = pro.spcode;
                    }
                    if (pro.spcname) {
                        tmp.spcname = pro.spcname;
                    }
                    tmp.geometrytype = e.geometrytype;
                    tmp.coordinates = e.coordinates;
                    this.mapData.push(tmp);
                });
            }
        },
        initMap () {
            let vectorLayer = '';
            let viewObj = {};
            vectorLayer = new ImageLayer({
                source:new ImageStatic({
                    url:this.mapBg, // 加载静态地图
                    imageExtent:this.extent // 地图的位置
                })
            });
            viewObj = {
                center:getCenter(this.extent),
                zoom:2
            };
            if (this.culMapInfo !== null) {
                viewObj = Object.assign({}, viewObj, this.culMapInfo);
                if (this.culMapInfo.projection) {
                    viewObj.projection = new Projection({ // 投影
                        extent:this.culMapInfo.projection.extent_
                    });
                }
            }
            let obj = {
                target:'map',
                layers:[vectorLayer],
                view:new View(viewObj),
                controls:defaultControls({
                    zoom:false
                })
            };

            this.map = new Map(obj);

            if (this.mapData && this.mapData.length > 0) {
                let shopVector = this.getShopSourceVector(this.mapData);
                let vector = new LayerVector({
                    source:shopVector,
                    style:feature => {
                        return this.getInitColor(feature);
                    }
                });
                this.map.addLayer(vector);
            }
            this.map.on('click', evt => {
                this.getShopFeatureInfo(evt.pixel);
            });
        },
        getInitColor (feature) {
            let pro = feature.getProperties();
            let id = pro.id;
            let index = this.mapData.findIndex(el => el.code === id);
            if (index !== -1) {
                if (this.mapData[index].spcode) {
                    let tmp = this.data.find(el => el.spcode === this.mapData[index].spcode);
                    if (tmp) {
                        return this.getSpidStyle(tmp.color, tmp.text);
                    } else {
                        return this.getHighlightStyle(id);
                    }
                } else {
                    return this.getHighlightStyle(id);
                }
            } else {
                return this.initStyle;
            }
        },
        hexToRgba (hex, opacity) {
            return (
                'rgba(' +
            parseInt('0x' + hex.slice(1, 3)) +
            ',' +
            parseInt('0x' + hex.slice(3, 5)) +
            ',' +
            parseInt('0x' + hex.slice(5, 7)) +
            ',' +
            opacity +
            ')'
            );
        },
        getSpidStyle (color, text) {
            let style = new Style({
                stroke:new Stroke({
                    color:'#2b85e4',
                    width:1
                }),
                fill:new Fill({
                    color:this.hexToRgba(color, 1)
                }),
                text:new Text({
                    font:'12px Calibri, sans-serif',
                    fill:new Fill({
                        color:'#000'
                    })
                })
            });
            if (text) {
                style.getText().setText(text);
            }
            return style;
        },
        getShopSourceVector (temp) {
            let sourceFeatures = [];
            temp.forEach(e => {
                let type = e.geometrytype;
                if (type === 'Polygon') {
                    let id = e.code;
                    let spcode = e.spcode;
                    let text = e.name;
                    let coordinates = JSON.parse(e.coordinates);
                    let feature = new Feature({
                        geometry:new Polygon(coordinates),
                        id:id,
                        text:text,
                        spcode:spcode
                    });
                    sourceFeatures.push(feature);
                }
            });
            let sourcepoly = new SourceVector({
                features:sourceFeatures,
                wrapX:false
            });
            return sourcepoly;
        },
        getShopFeatureInfo (pixel) {
            let feature = this.map.forEachFeatureAtPixel(pixel, feature => feature);
            if (feature) {
                let pro = feature.getProperties();
                let index = this.mapData.findIndex(el => el.code === pro.id);
                if (index !== -1) {
                    let shop = {};
                    shop.id = pro.id;
                    if (this.mapData[index].spcode) {
                        shop.spcode = this.mapData[index].spcode;
                        shop.spcname = this.mapData[index].spcname;
                        shop.spid_name = '[' + shop.spcode + ']' + shop.spcname;
                    } else {
                        shop.spcode = '';
                        shop.spcname = '';
                        shop.spid_name = '';
                    }
                    this.$emit('mapClick', shop);
                }
            }
        },
        ReInitMap () {
            this.reset = false;
            this.$nextTick(() => {
                this.reset = true;
                this.$nextTick(() => {
                    this.initMap();
                });
            });
        },
        clearData () {
            this.culMapInfo = null;
            this.lands = null;
            this.reset = false;
            this.data = [];
            this.$nextTick(() => {
                this.reset = true;
            });
        },
        getMapInfo (mmfcode) {
            let para = {};
            para.mmfcode = mmfcode;
            let self = this;
            let mapinfo = null;
            self.synchroPost(this.OmdUrl.sysconfboot, 'mss.sysconf.floor.getMap', para, function (data) {
                if (data && data.floor) {
                    mapinfo = data.floor;
                }
            });
            return mapinfo;
        },
        getMapGeojson (obj) {
            this.mapBg = this.OmdUrl.downfile + obj.imgkey +  '&token=' + this.getToken();
            this.extent = this.culMapInfo.projection.extent_;
            this.ReInitMap();
        },
        setData (obj) {
            this.data = obj;
            this.ReInitMap();
        },
        setMmfcode (value) {
            this.mmfcode = value;
            return this.init();
        },
        getHighlightStyle (text) {
            let style = new Style({
                stroke:new Stroke({
                    color:'#f00',
                    width:1
                }),
                fill:new Fill({
                    color:'rgba(255, 0, 0, 0.1)'
                }),
                text:new Text({
                    font:'12px Calibri, sans-serif',
                    fill:new Fill({
                        color:'#000'
                    })
                })
            });
            if (text) {
                style.getText().setText(text);
            }
            return style;
        },
        unzip (str) {
            let charData = atob(str).split('').map(function (x) { return x.charCodeAt(0); });
            let binData = new Uint8Array(charData);
            return pako.inflate(binData, {to:'string'});
        },
        exportMap () {
            // 使用html2canvas或其他库来导出图像
            html2Canvas(this.$refs.divMap).then(canvas => {
                const img = canvas.toDataURL('image/png');
                this.downloadImage(img, 'map.png');
            });
        },
        downloadImage (data, filename) {
            const link = document.createElement('a');
            if (typeof link.download === 'string') {
                link.href = data;
                link.download = filename;
                document.body.appendChild(link); // 需要将链接添加到文档中才能触发点击
                link.click();
                document.body.removeChild(link); // 下载完成后移除链接
            } else {
                window.open(data);
            }
        }
    },
    mounted () {
    }
};
</script>
