<!-- mapui-->
<template>
<div class='map'>
    <div id="container">加载数据，请稍候...</div>
    <div class="leftNavBox">
        <div class="searchBox">
            <el-select size="small" @change="searchPro()" filterable v-model="form.province" placeholder="选择省">
                <el-option label="--请选择--" value=""></el-option>
                <el-option
                    v-for="item in provinceList"
                    :key="item.adcode"
                    :label="item.name"
                    :value="item.adcode">
                </el-option>
            </el-select>
            <el-select size="small" @change="searchCity()" filterable v-model="form.city" placeholder="选择市">
                <el-option label="--请选择--" value=""></el-option>
                <el-option
                    v-for="item in cityList"
                    :key="item.adcode"
                    :label="item.name"
                    :value="item.adcode">
                </el-option>
            </el-select>
            <el-select size="small" @change="searchDis()" filterable v-model="form.district" placeholder="选择区">
                <el-option label="--请选择--" value=""></el-option>
                <el-option
                    v-for="item in districtList"
                    :key="item.adcode"
                    :label="item.name"
                    :value="item.adcode">
                </el-option>
            </el-select>
        </div>
        <div class="listBox">
            <div class="projectSearch">
                <div>项目列表</div>
                <div>
                    <el-input
                        size="small"
                        placeholder="请输入项目名称"
                        v-model="input"
                        suffix-icon="el-icon-search"
                        @change='getEquipList'
                        clearable>
                    </el-input>
                </div>
            </div>
            <div class="inner">
                <div class="scroll">
                    <el-scrollbar>
                    <div class="equipList">
                        <div class="item"
                        @click="equipLocate(item)"
                        @dblclick="enterBase(item.uid)" 
                        v-for="item in mapData" :key="item.uuid">
                            <img src="../../../../static/images/baseIcon.png" width="25px" alt="">
                            {{item.projectname}}
                        </div>
                        <div class="item noDate" v-if="!mapData.length">暂无数据</div>
                    </div>
                    </el-scrollbar>
                </div>   
            </div>
        </div>
    </div>
</div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
export default {
//import引入的组件需要注入到对象中才能使用
components: {},
data() {
//这里存放数据
return {
    map:null,
    data:[],
    mapData:[],
    topAdcodes:[100000],//全国区划编码
    center:[116.3683244,39.915085],
    zoom:4.5,
    // 搜索
    form:{
        province:'',
        city:'',
        district:'',
    },
    provinceList:[],
    cityList:[],
    districtList:[],
    district:null,
    input:'',
    polygons:[],
    distCluster:null,
    pointSimplifierIns:null,
};
},
//监听属性 类似于data概念
computed: {},
//监控data中的数据变化
watch: {},
//方法集合
methods: {
    initMap(){
         //创建地图
            var that = this
            this.map = new AMap.Map('container', {
                center:that.center,
                zoom: that.zoom
            });
            AMapUI.loadUI(['control/BasicControl'], function(BasicControl) {
                //缩放控件，显示Zoom值
                that.map.addControl(new BasicControl.Zoom({
                    position: 'rb',
                    showZoomNum: true
                }));
            });
                //加载相关组件
            AMapUI.load(['ui/geo/DistrictCluster', 'lib/$','ui/misc/PointSimplifier'], function(DistrictCluster, $,PointSimplifier) {

                //启动页面
                that.initPage(DistrictCluster, $,PointSimplifier);
            });
    },
    initPage(DistrictCluster, $,PointSimplifier) {
        var that = this;
        //创建组件实例
        this.pointSimplifierIns = new PointSimplifier({
            map: this.map, //关联的map
            zIndex:113,
            autoSetFitView: false,
            compareDataItem: function(a, b, aIndex, bIndex) {
                //数据源中靠后的元素优先，index大的排到前面去
                // return aIndex > bIndex ? -1 : 1;
            },
            getPosition: function(item) {
                if (!item.lnglat) {
                    return null;
                }
                //返回经纬度
                return [parseFloat(item.lnglat[0]), parseFloat(item.lnglat[1])];
            },
            getHoverTitle: function(dataItem, idx) {
                //返回数据项的Title信息，鼠标hover时显示
                // return '序号: ' + idx;
                // console.log(dataItem);
                
                return '<div style="font-size:14px">' + dataItem.projectname+'</div>';
            },
            renderOptions: {
                 //点的样式
                pointStyle: {
                    //绘制点占据的矩形区域
                    content: function(ctx, x, y, width, height) {
                       ctx.moveTo(x, y); //移动到左上角
						ctx.lineTo(x + 25, y);  //连接到右上角
                       ctx.lineTo(x, y+height/1.5);  //连接到右上角
                       ctx.lineTo(x, y + height);//连接到右下角
                       ctx.lineTo(x, y + height); //连接到左下角
                       ctx.lineTo(x, y);//连接到左上角
                    },
                    //宽度
                    width: 33,
                    //高度
                    height: 30,
                    fillStyle: 'red',
                    lineWidth: 1,
                    offset:['0', '-100%'],
                    strokeStyle: '#000'
                },
            }
        });
        this.pointSimplifierIns.setData(this.mapData)
        this.pointSimplifierIns.on('pointClick',(e,point)=>{
            this.$store.commit('setData',{
                name:'plantProtectionUserId',
                val:point.data.uid
            })
            that.$router.push('/plantGuard/base')
        })
        this.distCluster = new DistrictCluster({
            map: that.map, //所属的地图实例
            zIndex:13,
            autoSetFitView: false,
            topAdcodes: that.topAdcodes,
            getPosition: function(item) {
                if (!item.lnglat) {
                    return null;
                }
                //返回经纬度
                return [parseFloat(item.lnglat[0]), parseFloat(item.lnglat[1])];
            },
            renderOptions: {
                // clusterMarkerKeepConsistent: false, //marker的位置随交互变化
                featureStyle: {
                    fillStyle: 'rgba(102,170,0,0.5)', //填充色
                    lineWidth: 2, //描边线宽
                    strokeStyle: '#4e6ef2', //描边色
                    //鼠标Hover后的样式
                    hoverOptions: {
                        fillStyle: 'rgba(78,110,242,0.4)'
                    }
                },
                // 特定区划级别的默认样式
                featureStyleByLevel: {
                    //全国
                    country: {
                        fillStyle: 'rgba(78,110,242,0)'
                    },
                    //省
                    province: {
                        fillStyle: 'rgba(78,110,242,0)'
                    },
                    //市
                    city: {
                        fillStyle: 'rgba(78,110,242,0)'
                    },
                    //区县
                    district: {
                        fillStyle:'rgba(78,110,242,0)'
                    }
                },
                getClusterMarker: function(feature, dataItems, recycledMarker) {

                    //不是当前feature，直接返回null
                    if(dataItems.length){
                        var container, title, body, nodeClassNames = {
                            title: 'amap-ui-district-cluster-marker-title',
                            body: 'amap-ui-district-cluster-marker-body',
                            container: 'amap-ui-district-cluster-marker'
                        };
                        
                        console.log(recycledMarker);
                        if (recycledMarker) {
                        console.log(recycledMarker.getContent());

                            container = recycledMarker.getContent();

                            title = $(container).find('.' + nodeClassNames.title)[0];

                            body = $(container).find('.' + nodeClassNames.body)[0];

                        } else {

                            container = document.createElement('div');

                            title = document.createElement('span');

                            title.className = nodeClassNames.title;

                            body = document.createElement('span');

                            body.className = nodeClassNames.body;

                            container.appendChild(title);

                            container.appendChild(body);
                        }
                        console.log(feature.properties);
                        
                        var props = feature.properties,
                            routeNames = [];

                        var classNameList = [nodeClassNames.container, 'level_' + props.level, 'adcode_' + props.adcode];

                        container.className = classNameList.join(' ');

                        if (routeNames.length > 0) {

                            routeNames.push(props.name);

                            container.setAttribute('title', routeNames.join('>'));

                        } else {
                            container.removeAttribute('title');
                        }

                        $(title).html(props.name);
                        $(body).html(dataItems.length);

                        var resultMarker = recycledMarker || new AMap.Marker({
                            topWhenClick: true,
                            offset: new AMap.Pixel(-20, -30),
                            content: container
                        });
                        console.log(container);
                        console.log(resultMarker);
                        
                        return resultMarker;
                    }
                }
            },
        });
            //监听区划面的点击
        this.distCluster.on('clusterMarkerClick', function(e, feature) {

           console.log(e)
           console.log(feature)
           console.log(that);
            //重绘
            //distCluster.renderLater();
        });
        // window.distCluster = distCluster;


        $('<div id="loadingTip">加载数据，请稍候...</div>').appendTo(document.body);
        $.get('https://a.amap.com/amap-ui/static/data/10w.txt', (csv)=>{

            $('#loadingTip').remove();

        // var data = [
        //     "113.665412,34.757975",
        //     "113.671767,34.815528",
        //     "113.671867,34.825528",
        //     "113.735978,34.728131",
        //     "120.412618,36.382612",
        //     "112.985037,23.15046",
        //     "126.687123,45.787618"
        //     ]
            var data = csv.split('\n').slice(0,1000);
            // that.data = data
            this.distCluster.setData(that.data);

        });
    },
    getEquipList() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=user.login.user_project_addr",
        data: this.qs.stringify({
            projectname:this.input
        })
      }).then(res => {
        if (res.data.message == ""){
            this.data = res.data.data.user_project;
            this.mapData = res.data.data.user_project;
            this.$nextTick(()=>{
                this.initMap()
            })
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    districtFun(){
        this.map = new AMap.Map('container', {
            resizeEnable: true,
            center: [116.30946, 39.937629],
            zoom: 3
        });
        //行政区划查询
        var opts = {
            subdistrict: 1,   //返回下一级行政区
            showbiz:false  //最后一级返回街道信息
        };
        this.district = new AMap.DistrictSearch(opts);//注意：需要使用插件同步下发功能才能这样直接使用
        this.district.search('中国', (status, result)=>{
            if(status=='complete'){
                this.getData(result.districtList[0],'country');
            }
        });
    },
    getData(data,level) {
        console.log(data);
        var bounds = data.boundaries;
        if (bounds) {
            for (var i = 0, l = bounds.length; i < l; i++) {
                var polygon = new AMap.Polygon({
                    map: this.map,
                    zIndex:5,
                    bubble:true,
                    strokeWeight: 2,
                    strokeColor: 'red',
                    fillOpacity: 0.2,
                    path: bounds[i]
                });
                this.polygons.push(polygon);
            }
            this.map.setFitView();//地图自适应
        }

        var subList = data.districtList;
        //清空下一级别的下拉列表
        if (level === 'country') {
            console.log('country');
            
            this.provinceList = subList;
            this.cityList = []
            this.districtList = [];
            this.form.province=''
            this.form.city=''
            this.form.district=''
        } else if (level === 'province') {
            console.log('province');
            this.cityList = subList;
            this.districtList = [];
            this.form.city=''
            this.form.district=''
        } else if (level === 'city') {
            console.log('city');
            this.districtList = subList;
            this.form.district=''
        }

        console.log(subList);
        // if (subList) {
        //     var contentSub = new Option('--请选择--');
        //     var curlevel = subList[0].level;
        //     var curList =  document.querySelector('#' + curlevel);
        //     curList.add(contentSub);
        //     for (var i = 0, l = subList.length; i < l; i++) {
        //         var name = subList[i].name;
        //         var levelSub = subList[i].level;
        //         var cityCode = subList[i].citycode;
        //         contentSub = new Option(name);
        //         contentSub.setAttribute("value", levelSub);
        //         contentSub.center = subList[i].center;
        //         contentSub.adcode = subList[i].adcode;
        //         curList.add(contentSub);
        //     }
        // }
        
    },
    searchPro(){
        var keyword = this.form.province; //关键字 
        console.log(this.form.province);
        console.log(this.form.city);
        console.log(this.form.district);
        if(!keyword){
            this.cityList = []
            this.districtList = [];
            this.form.city=''
            this.form.district='';
            this.mapData=this.data;
            this.pointSimplifierIns.setData(this.mapData)
        }else{
            this.distCluster.getClusterRecord(keyword,(error, result)=>{
                // console.log(result);
                //获取此区域下的数据点
                this.mapData = [];
                result.dataItems.forEach((item) => {
                    this.mapData.push(item.dataItem)
                });
                this.$nextTick(()=>{
                    this.pointSimplifierIns.setData(this.mapData)
                })
            })
        }
        // if(this.form.province||this.form.city||this.form.district){
        //     this.distCluster.setData([])
        // }else{
        //     this.distCluster.setData(this.data)
        // }
        this.search('province',keyword)
        
    },
    searchCity(){
        var keyword = this.form.city || this.form.province; //关键字 
        this.distCluster.getClusterRecord(keyword,(error, result)=>{
            // console.log(result);
            //获取此区域下的数据点
            this.mapData = [];
            result.dataItems.forEach((item) => {
                this.mapData.push(item.dataItem)
            });
            this.$nextTick(()=>{
                this.pointSimplifierIns.setData(this.mapData)
            })
        })
        this.search('city',keyword)
    },
    searchDis(){
        var keyword = this.form.district ||this.form.city; //关键字 
        this.distCluster.getClusterRecord(keyword,(error, result)=>{
            // console.log(result);
            //获取此区域下的数据点
            this.mapData = [];
            result.dataItems.forEach((item) => {
                this.mapData.push(item.dataItem)
            });
            this.$nextTick(()=>{
                this.pointSimplifierIns.setData(this.mapData)
            })
        })
        
        this.search('district',keyword)
    },
    search(levelSub,keyword) {
        //清除地图上所有覆盖物
        for (var i = 0, l = this.polygons.length; i < l; i++) {
            this.polygons[i].setMap(null);
        }
        console.log(this.distCluster);
        // this.distCluster.setData([
            // "113.665412,34.757975",
            // "113.671767,34.815528",
            // "113.671867,34.825528",
            // "113.735978,34.728131",
            // "120.412618,36.382612",
            // "112.985037,23.15046",
            // "126.687123,45.787618"
        // ])
 
        
        if(!keyword){
            return;
        }

        this.district.setLevel(levelSub); //行政区级别
        this.district.setExtensions('all');
        //行政区查询
        //按照adcode进行查询可以保证数据返回的唯一性
        this.district.search(keyword,(status, result)=>{
            if(status === 'complete'){
                this.getData(result.districtList[0],levelSub);
            }
        });
    },
    equipLocate(item){
        this.map.setCenter(item.lnglat);
        this.map.setZoom(10)
    },
    enterBase(id){
        this.$store.commit('setData',{
            name:'plantProtectionUserId',
            val:id
        })
        this.$router.push('/plantGuard/base')
    }
},
//生命周期 - 创建完成（可以访问当前this实例）
created() {

},
//生命周期 - 挂载完成（可以访问DOM元素）
mounted() {
    this.getEquipList()
    this.districtFun()
},
beforeCreate() {}, //生命周期 - 创建之前
beforeMount() {}, //生命周期 - 挂载之前
beforeUpdate() {}, //生命周期 - 更新之前
updated() {}, //生命周期 - 更新之后
beforeDestroy() {}, //生命周期 - 销毁之前
destroyed() {}, //生命周期 - 销毁完成
activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style scoped lang='less'>
.map,#container{
    width: 100%;
    height: 100%;
}
.leftNavBox{
    position: absolute;
    left: 100px;
    top: 160px;
    bottom:0;
    /deep/.el-select{
        width: 1.4rem;
    }
    .listBox{
        position: relative;
        overflow: hidden;
        width: 4.25rem;
        height: 90%;
        margin-top: 16px;
        border-radius: 6px;
        background: rgba(255,255,255,.58);
        box-shadow: 0px 3px 9px 0px #a7a7a7;
        .projectSearch{
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: .15rem;
            background: #182037;
            color: #fff;
            font-size: .175rem;
            border-radius: 6px 6px 0 0;
            /deep/.el-input{
                width: 2.5rem;
            }
        }
        .inner{
            position: absolute;
            top: 57px;
            bottom: -18px;
            left: 0;
            right: 0;
            .scroll{
                height: 100%;
                overflow: auto;
                .equipList{
                    .item{
                        padding: .175rem;
                        color: #454545;
                        font-size: .175rem;
                        // background: red;
                        cursor: pointer;
                        img{
                            vertical-align: middle;
                            margin-right: 2px;
                        }
                        &:hover{
                            background: #182037;
                            color: #fff;
                        }
                    }
                    .noDate{
                        text-align: center;
                    }
                    .item.active{
                        background: darkblue;
                    }
                }
            }
            .scroll {
                height: 100%;
                overflow-y: hidden;
                }
                .el-scrollbar{
                height: 100%;
                }
                .el-scrollbar__bar{
                &.is-vertical{
                    width:100px;//滚动条宽度
                }
                }
                .el-scrollbar__wrap{
                overflow-y: auto;
                overflow-x:hidden;
                }
                .el-scrollbar__thumb {
                // 可设置滚动条颜色
                background: red;
            }
        }
    }
}
 .amap-layers .amap-markers{
    z-index: 320 !important;
}
</style>