<template>
    <div class="mapItems">
        <modular-loading :loadding="loadding" tipsText="地图加载中"></modular-loading>
        <div class="topSelect">
            <div></div>
        </div>
        <div class="mapInit" id="mapInit"></div>
    </div>
</template>
<script>
import { mapState } from 'vuex';
export default {
    data() {
        return {
            map: '',
            disCountry: '',
            placeSearch: '',
            district: null,
            marker: '',
            polygons: [],
            addressName: '', //地址查询名称
            poisArray: [],
            loadding: true,
            centet: []
        };
    },
    mounted() {},
    computed: {
        ...mapState(['globalCommunity', 'findCompanyCommunityTree']),
        poisArrays() {
            let arrs = [];
            this.fitersValue(arrs, this.findCompanyCommunityTree);
            return arrs;
        }
    },
    watch: {
        globalCommunity: {
            handler(newVal, oldVal) {
                if (!!this.map) {
                    this.map.clearMap();
                }
                if (this.poisArrays.length > 0) {
                    this.addIcon(this.poisArrays);
                }
            },
            deep: true
        }
    },

    methods: {
        init() {
            this.map = new AMap.Map('mapInit', {
                resizeEnable: true, //是否监控地图容器尺寸变化
                center: !!this.centet[0] ? this.centet : '',
                zoom: !!this.centet[0] ? 8 : 5, //初始化地图层级
                mapStyle: 'amap://styles/darkblue',
                defaultCursor: 'pointer'
            });
            //地图加载完成监听点击事件
            this.map.on('complete', () => {
                this.loadding = false;
                if (this.poisArrays.length > 0) {
                    this.addIcon(this.poisArrays);
                }
                this.mapClick();
            });
        },
        mapClick() {
            this.map.on('click', (ev) => {
                this.getAddress([ev.lnglat.lng, ev.lnglat.lat]);
            });
        },

        addIcon(arrs) {
            let self = this;
            arrs.map((item) => {
                self.marker = new AMap.Marker({
                    icon: new AMap.Icon({
                        image: require('@assets/img/icon_point_community.png'),
                        size: new AMap.Size(40, 50),
                        imageSize: new AMap.Size(40, 50)
                    }),
                    position: [item.longitude, item.latitude],
                    map: self.map,
                    communityData: item
                });
                self.marker.setLabel({
                    offset: new AMap.Pixel(-15, 50),
                    content: `${item.name}`
                });
                if (self.poisArrays.length < 2) {
                    self.map.setFitView();
                }
                self.marker.on('click', function () {
                    self.setCommunity(this.De.communityData);
                });
            });
        },
        setCommunity(its) {
            this.$store.commit('setGlobalCommunity', {
                value: [its.value]
            });
            let newarr = this.finterParent(this.findCompanyCommunityTree, its.value);
            newarr.push(its.value);
            this.$store.commit('setThisArr', newarr);
            this.$parent.showMap = false;
        },
        finterParent(data, id) {
            // 深度遍历查找
            function dfs(data, id, parents) {
                for (var i = 0; i < data.length; i++) {
                    var item = data[i];
                    // 找到id则返回父级id
                    if (item.value === id) return parents;
                    // children不存在或为空则不递归
                    if (!item.children || !item.children.length) continue;
                    // 往下查找时将当前id入栈
                    parents.push(item.value);

                    if (dfs(item.children, id, parents).length) return parents;
                    // 深度遍历查找未找到时当前id 出栈
                    parents.pop();
                }
                // 未找到时返回空数组
                return [];
            }

            return dfs(data, id, []);
        },
        //搜索区域
        districtMask(val) {
            if (!this.district) {
                //实例化DistrictSearch
                var opts = {
                    subdistrict: 0, //获取边界不需要返回下级行政区
                    extensions: 'all', //返回行政区边界坐标组等具体信息
                    level: 'district' //查询行政级别为 市
                };
                this.district = new AMap.DistrictSearch(opts);
            }
            // this.district.setLevel(val);
            this.district.search(val, (status, result) => {
                this.map.remove(this.polygons); //清除上次结果
                this.polygons = [];
                var bounds = result.districtList[0].boundaries;
                if (bounds) {
                    for (var i = 0, l = bounds.length; i < l; i++) {
                        //生成行政区划polygon
                        var polygon = new AMap.Polygon({
                            strokeWeight: 1, //边界宽度
                            path: bounds[i],
                            fillOpacity: 0.3, // 透明度
                            fillColor: '#2887f2',
                            strokeColor: '#2887f2' //边界颜色
                        });
                        this.polygons.push(polygon);
                    }
                }
                this.map.add(this.polygons);
                this.map.setFitView(this.polygons); //视口自适应
            });
        },
        getAddress(points) {
            //获取准确地址
            let geocoder = new AMap.Geocoder({ radius: 1000 });
            geocoder.getAddress(points, (status, result) => {
                if (status === 'complete' && result.regeocode) {
                    this.districtMask(result.regeocode.addressComponent.district);
                } else {
                    this.map.remove(this.polygons);
                }
            });
        },
        getPoin(resolve) {
            this.$http.get('/sc-community/assets/tree/community/findCompanyCommunityTree').then(({ data, status, msg }) => {
                if (status == 0) {
                    let arrs = [];
                    this.fitersValue(arrs, data);
                    this.centet = this.getPointsCenter(arrs);
                    resolve && resolve(true);
                }
            });
        },
        getLoc(resolve) {
            this.$http.get('/sc-user-center/user/findUserArea').then(({ data, status, msg }) => {
                if (status == 0) {
                    this.centet[0] = data.lng;
                    this.centet[1] = data.lat;
                    resolve && resolve(true);
                }
            });
        },
        getPointsCenter(points) {
            var point_num = points.length; //坐标点个数
            var X = 0,
                Y = 0,
                Z = 0;
            for (let i = 0; i < points.length; i++) {
                if (points[i] == '') {
                    continue;
                }
                var lat, lng, x, y, z;
                lat = (parseFloat(points[i].latitude) * Math.PI) / 180;
                lng = (parseFloat(points[i].longitude) * Math.PI) / 180;
                x = Math.cos(lat) * Math.cos(lng);
                y = Math.cos(lat) * Math.sin(lng);
                z = Math.sin(lat);
                X += x;
                Y += y;
                Z += z;
            }
            X = X / point_num;
            Y = Y / point_num;
            Z = Z / point_num;
            var tmp_lng = Math.atan2(Y, X);
            var tmp_lat = Math.atan2(Z, Math.sqrt(X * X + Y * Y));

            return [(tmp_lng * 180) / Math.PI, (tmp_lat * 180) / Math.PI];
            return [
                Math.floor(((tmp_lng * 180) / Math.PI) * 1000000) / 1000000,
                Math.floor(((tmp_lat * 180) / Math.PI) * 1000000) / 1000000
            ];
        },
        fitersValue(arrs, value) {
            let thisValue = this.globalCommunity.value;
            value.map((item) => {
                if (item.type == 'org') {
                    if (!!item.children) {
                        this.fitersValue(arrs, item.children);
                    }
                } else {
                    if (!!thisValue && thisValue.includes(item.parentId)) {
                        arrs.push(item);
                    }
                }
            });
        }
    },
    destroyed() {
        this.map && this.map.destroy();
    },
    created() {
        new Promise((resolve) => {
            this.getPoin(resolve);
        }).then(() => {
            new Promise((resolve) => {
                if (!!AMap) {
                    resolve(true);
                }
            }).then(() => {
                this.init();
            });
        });
    }
};
</script>
<style scoped lang="scss">
@import '@assets/css/public-style.scss';
.mapItems {
    height: 100%;
    position: relative;
    color: white;
    .topSelect {
        position: absolute;
        top: rem(15);
        left: 0;
        padding: 0 rem(15);
        width: 100%;
    }
}
#mapInit {
    width: 100%;
    height: 100%;
    /deep/ .amap-marker-label {
        background: rgba(0, 0, 0, 0.5);
        text-align: center;
        min-width: rem(80);
        min-height: rem(20);
        line-height: rem(20);
        box-shadow: 0px 2px 10px 0px rgba(66, 70, 86, 0.08);
        border: 0 none;
        white-space: nowrap;
        box-shadow: 0 0 5px 0rgba (0, 0, 0, 0.3);
    }
}
</style>