<template>
  <div id="container">
    <Collapse v-model="curStreet" @on-change="handleSelect" class="menu" accordion>
      <Panel v-for="street in streetList" :key="street" :name="street">
        {{areaList[street].name}}小区列表
        <div slot="content" class="community-list">
          <div v-for="(item, index) in areaList[street].community" :key="item.name + index" style="display:flex;justify-content:space-between;">
            <Button
              @click="handleView(item)"
              size="small"
              type="text"
              long>
              {{item.name}}
            </Button>
            <a @click="handleDetail(item)" style="display:block;min-width:5rem;text-align:right;">详情</a>
          </div>
        </div>
      </Panel>
    </Collapse>
    <Modal v-model="detailModal" width="90%" :footer-hide="true">
      <Table :columns="columns" :data="detailData" size="small" :max-height="tableHeight"/>
    </Modal>
  </div>
</template>

<script>
const {AMap} = window
const star1 = require('@/assets/images/star1.png')
const star2 = require('@/assets/images/star2.png')
const star3 = require('@/assets/images/star3.png')
import {mockCommunity, mockBuilding} from '@/mock/index.js'
export default {
  name: 'Test',
  data() {
    return {
      map: null,
      buildingOptions: {
        hideWithoutStyle:false,//是否隐藏设定区域外的楼块
        areas:[
          { //围栏1
            //visible:false,//是否可见
            rejectTexture:true,//是否屏蔽自定义地图的纹理
            color1: 'ff99ff00',//楼顶颜色
            color2: 'ff999900',//楼面颜色
            path: [
              [121.498447,31.217582],
              [121.498466,31.218851],
              [121.497402,31.218943],
              [121.497423,31.217595],
            ]
          },
          {
            rejectTexture:true,//是否屏蔽自定义地图的纹理
            color1: 'ffcc0000',//楼顶颜色
            color2: 'ffaa0000',//楼面颜色
            path: [
              [121.497898,31.217932],
              [121.498456,31.217945],
              [121.498445,31.218445],
              [121.49791,31.218376],
            ]
          },
          {
            rejectTexture:true,//是否屏蔽自定义地图的纹理
            color1: 'ffffff00',//楼顶颜色
            color2: 'ffffcc00',//楼面颜色
            path: [
              [121.498696,31.218295],
              [121.498679,31.217744],
              [121.499197,31.217747],
              [121.499243,31.218324],
            ]
          },
        ]
      },
      mapConfig: {
        resizeEnable: true,
        rotateEnable:true,
        pitchEnable:true,
        showLabel: true,
        zoom: 15,
        pitch:0,
        rotation:45,
        viewMode:'3D',//开启3D视图,默认为关闭
        buildingAnimation:true,//楼块出现是否带动画
        expandZoomRange:true,
        zooms: [10,20],
        center: [121.544379, 31.221517], // 浦东新区
        showIndoorMap:false,
        // mapStyle:'amap://styles/light',
        features:['bg','road'],
      },
      areaList: mockCommunity,
      buildingList: mockBuilding,
      streetList: [],
      curStreetPolygon: null,
      curStreet: null,
      markerList: [],
      detailModal: false,
      columns: [
        {
          title: '小区',
          key: 'name',
          minWidth: 100,
          fixed: 'left',
          align: 'center',
        },
        {
          title: '楼栋号',
          key: 'buildingNo',
          minWidth: 100,
          fixed: 'left',
          align: 'center',
        },
        {
          title: '房屋性质',
          key: 'type',
          minWidth: 100,
          align: 'center',
        },
        {
          title: '房龄',
          key: 'age',
          minWidth: 100,
          align: 'center',
        },
        {
          title: '层高',
          key: 'high',
          minWidth: 100,
          align: 'center',
        },
        {
          title: '4层以上是否有70岁以上老人',
          key: 'hasOld',
          minWidth: 130,
          align: 'center',
        },
        {
          title: '4层以上是否有行动不便的残障人员',
          key: 'hasDisabled',
          minWidth: 150,
          align: 'center',
        },
        {
          title: '是否已有业主发起加梯动员',
          key: 'hasMobilizatin',
          minWidth: 130,
          align: 'center',
        },
        {
          title: '楼内邻里关系是否和睦',
          key: 'hasPeace',
          minWidth: 130,
          align: 'center',
        },
        {
          title: '楼内业主自住率是否高于80%',
          key: 'hasSelf',
          minWidth: 130,
          align: 'center',
        },
        {
          title: '一楼是否非居',
          key: 'hasNonliving',
          minWidth: 130,
          align: 'center',
        },
        {
          title: '是否有地下层',
          key: 'hasUnderground',
          minWidth: 130,
          align: 'center',
        },
        {
          title: '占用车道',
          key: 'hasLane',
          minWidth: 100,
          align: 'center',
        },
        {
          title: '占用绿化',
          key: 'hasGreening',
          minWidth: 100,
          align: 'center',
        },
        {
          title: '占用车位',
          key: 'hasParking',
          minWidth: 100,
          align: 'center',
        },
        {
          title: '楼间距',
          key: 'spacing',
          minWidth: 100,
          align: 'center',
        },
        {
          title: '连廊长度',
          key: 'corridorLength',
          minWidth: 100,
          align: 'center',
        },
        {
          title: '居民意愿',
          key: 'intention',
          minWidth: 100,
          align: 'center',
        },
      ],
      detailData: [],
    }
  },
  mounted() {
    this.$nextTick(this.initMap)
  },
  methods: {
    initMap(area) {
      this.map = new AMap.Map('container', this.mapConfig)
      // this.initLayers()
      this.addController()
      // this.addMarker()
      this.addEvents()
      this.highlightPudong()
      this.initMenu()
    },
    initMenu() {
      const streets = Object.keys(this.areaList)
      if (this.$route.query && this.$route.query.name) { // 判断路由有街镇则显示该街镇列表，没街镇显示所有街镇列表
        const streetName = this.$route.query.name
        let result = null
        streets.forEach(street => {
          if (streetName.indexOf(this.areaList[street].name) >= 0) {
            result = street
          }
        })
        this.streetList = [result]
        this.$nextTick(() => { // 为了展开默认街镇小区列表
          this.curStreet = result
          this.handleSelect([this.curStreet])
        })
      } else {
        this.streetList = streets
      }
    },
    handleView({name, address, location}) {
      this.map.setZoomAndCenter(18, location)
      this.showDetail(null, location, {title: name, content: address})
      this.addMarker(name)
    },
    handleDetail({name}) {
      if (!this.buildingList[`${this.curStreet}Building`]) return
      this.detailData = this.buildingList[`${this.curStreet}Building`].building.filter(item => item.name.indexOf(name) >= 0)
      this.detailModal = true
    },
    handleSelect(key) {
      if (!key || key.length <= 0) return
      this.map.setZoomAndCenter(15, this.areaList[key[0]].location)
      if (this.curStreetPolygon) {
        // this.map.remove(this.curStreetPolygon) // 移除之前的街镇区域底色
        this.map.clearMap()
      }
      this.initLayers(key)
      this.highlightArea(this.areaList[key[0]])
    },
    initLayers(street = null) { // 添加基础图层和建筑物图层
      const keys = Object.keys(this.areaList)
      if (keys.length <= 0) return
      const communityList = []
      if (street) {
        communityList.push(...this.areaList[street].community)
        if (this.buildingList[`${street}Building`]) {
          communityList.push(...this.buildingList[`${street}Building`].community) // 添加个别不同色的，手动上色的楼栋
        }
      } else {
        keys.forEach(key => {
          communityList.push(...this.areaList[key].community)
        })
      }
      const buildingOptions = {
        areas: communityList.map(item => {
          if (item.type != 'building') {
            new AMap.Polygon({
              zIndex: 10,
              bubble:false,
              fillColor: 'green',
              fillOpacity:0.2,
              strokeWeight:1,
              path: item.path,
              map:this.map
            }).on('click', e => {
              const location = [e.lnglat.getLng(), e.lnglat.getLat()]
              console.log(e.lnglat.getLng() + ',' + e.lnglat.getLat())
              // this.handleView(item)
            })
          }
          return {
            rejectTexture:true,//是否屏蔽自定义地图的纹理
            color1: this.$com.switchBuildingColor(item.level)[0],//楼顶颜色
            color2: this.$com.switchBuildingColor(item.level)[1],//楼面颜色
            path: item.path || []
          }
        })
      }
      const buildingLayer = new AMap.Buildings({zIndex:130,merge:false,sort:false,zooms:[10,20]})
      buildingLayer.setStyle(buildingOptions)
      this.map.setLayers([
        new AMap.TileLayer({}),
        buildingLayer
      ])

      // 框起的建筑物区域底板颜色(不写则无底色，不影响建筑颜色)
      // new AMap.Polygon({
      //   bubble:false,
      //   fillColor: 'green',
      //   fillOpacity:0.2,
      //   strokeWeight:1,
      //   path: buildingOptions.areas[0].path,
      //   map:this.map
      // }).on('click', e => {
      //   const location = [e.lnglat.getLng(), e.lnglat.getLat()]
      //   this.map.setZoomAndCenter(18.8, location)
      // })
      // new AMap.Polygon({
      //   bubble:true,
      //   fillOpacity:0.2,
      //   strokeWeight:1,
      //   path:this.buildingOptions.areas[1].path,
      //   map:this.map
      // })
    },
    addController() { // 添加地图控制器
      this.map.addControl(new AMap.ControlBar({
        showZoomBar:false,
        showControlButton:true,
        position:{
          right:'10px',
          top:'10px'
        }
      }))
    },
    addMarker(name) {
      this.map.remove(this.markerList) // 移除之前的marker
      if (!this.buildingList[`${this.curStreet}Building`]) return
      const whichImage = (intention) => {
        if (intention.indexOf('一') >= 0) {
          return {
            src: star1,
            size: [10, 15],
          }
        } else if (intention.indexOf('二') >= 0 || intention.indexOf('两') >= 0) {
          return {
            src: star2,
            size: [15, 15],
          }
        } else if (intention.indexOf('三') >= 0) {
          return {
            src: star3,
            size: [20, 15],
          }
        }
      }
      const markerList = []
      this.buildingList[`${this.curStreet}Building`].building.forEach(item => {
        if(item.name.indexOf(name) >= 0 && item.lon && item.lat && item.intention) {
          const image = whichImage(item.intention)
          const style = {
            img:image.src,
            size:image.size,//可见区域的大小
            fitZoom:18,//最合适的级别
            scaleFactor:2,//地图放大一级的缩放比例系数
            maxScale:1.4,//最大放大比例
            minScale:0.8//最小放大比例
          }
          const marker = new AMap.ElasticMarker({
            position: [item.lon, item.lat],
            zooms:[16,20],
            extData: {
              title: item.buildingNo,
              content: `居民意愿度:${item.intention}`
            },
            styles:[
              {
                icon:{
                  ancher:[0,30],//锚点
                  ...style,
                }
              },
              {
                icon:{
                  ancher:[0,45],//锚点
                  ...style,
                }
              },
              {
                icon:{
                  ancher:[0,60],//锚点
                  ...style,
                }
              },
              {
                icon:{
                  ancher:[0,80],//锚点
                  ...style,
                }
              },
              {
                icon:{
                  ancher:[0,100],//锚点
                  ...style,
                }
              }
            ],
            zoomStyleMapping: {
              16:0,
              17:1,
              18:2,
              19:3,
              20:4,
            }
          }).on('click', e => {
            const location = [e.lnglat.getLng(), e.lnglat.getLat()]
            this.showDetail(e, location, marker.getExtData())
          })
          markerList.push(marker)
        }
      })
      this.map.add(markerList)
      this.markerList = markerList
      // new AMap.Marker({
      //   map: this.map,
      //   position: [121.498973,31.218018],
      //   extData: {
      //     title: '测试点击',
      //     content: '测试额外附加数据',
      //   },
      //   icon: new AMap.Icon({
      //     size: new AMap.Size(30, 30),  //图标大小
      //     image: require('@/assets/images/attorney.png'),
      //     // imageOffset: new AMap.Pixel(0, -60)
      //   })
      // }).on('click', e => {
      //   const location = [e.lnglat.getLng(), e.lnglat.getLat()]
      //   this.showDetail(e, location, marker.getExtData())
      // })
    },
    showDetail(e, location, data) {
      // TODO
      const infoWindow = new AMap.InfoWindow({
        content: `
            <div>
              <b>${data.title}</b>
              <p>${data.content || '暂无其他信息'}</p>
            </div>
          `
      })
      infoWindow.open(this.map, location)
    },
    addEvents() {
      this.map.on('click', e => {
        const location = [e.lnglat.getLng(), e.lnglat.getLat()]
        // this.map.setZoomAndCenter(18.8, location)
        console.log(e.lnglat.getLng() + ',' + e.lnglat.getLat())
      })
    },
    highlightArea(area) {
      if (!area.path || area.path <= 0) return
      const polygon = new AMap.Polygon({
        zIndex: 1,
        strokeWeight: 3,
        strokeStyle:'dashed',
        path: area.path,
        fillOpacity: 0.2,
        fillColor: '#80d8ff',
        strokeColor: '#0091ea'
      }).on('click', e => {
        console.log(e.lnglat.getLng() + ',' + e.lnglat.getLat())
      })
      this.curStreetPolygon = polygon

      // const outer = [
      //   new AMap.LngLat(-360,90,true),
      //   new AMap.LngLat(-360,-90,true),
      //   new AMap.LngLat(360,-90,true),
      //   new AMap.LngLat(360,90,true),
      // ]
      // const holes = [area.path]
      // const pathArray = [
      //   outer
      // ]
      // pathArray.push.apply(pathArray,holes)
      // const polygon1 = new AMap.Polygon( {
      //   pathL:pathArray,
      //   //线条颜色，使用16进制颜色代码赋值。默认值为#006600
      //   strokeColor: 'rgb(20,164,173)',
      //   strokeWeight: 4,
      //   //轮廓线透明度，取值范围[0,1]，0表示完全透明，1表示不透明。默认为0.9
      //   strokeOpacity:0.5,
      //   //多边形填充颜色，使用16进制颜色代码赋值，如：#FFAA00
      //   fillColor: 'rgba(255,255,255,0.3)',
      //   //多边形填充透明度，取值范围[0,1]，0表示完全透明，1表示不透明。默认为0.9
      //   fillOpacity: 1,
      //   //轮廓线样式，实线:solid，虚线:dashed
      //   strokeStyle:'dashed',
      //   /*勾勒形状轮廓的虚线和间隙的样式，此属性在strokeStyle 为dashed 时有效， 此属性在
      //       ie9+浏览器有效 取值：
      //       实线：[0,0,0]
      //       虚线：[10,10] ，[10,10] 表示10个像素的实线和10个像素的空白（如此反复）组成的虚线
      //       点画线：[10,2,10]， [10,2,10] 表示10个像素的实线和2个像素的空白 + 10个像素的实
      //       线和10个像素的空白 （如此反复）组成的虚线*/
      //   strokeDasharray:[10,2,10]
      // })
      // polygon1.setPath(pathArray)
      // this.map.add(polygon1)

      this.map.add([polygon])
    },
    highlightPudong() {
      // new AMap.DistrictSearch({
      //   level: 'district',
      //   subdistric: 1,
      // }).search('浦东新区', (status, result) => {
      //   console.log('---浦东新区街镇---', result.districtList[0].districtList)
      // })

      // 给浦东新区添加蓝色遮罩
      // new AMap.DistrictSearch({
      //   level: 'district',
      //   extensions: 'all',
      //   subdistric: 1,
      // }).search('浦东新区', (staus, result) => {
      //   var bounds = result.districtList[0].boundaries
      //   var polygon = new AMap.Polygon({
      //     strokeWeight: 1,
      //     path: bounds[0],
      //     fillOpacity: 0.4,
      //     fillColor: '#80d8ff',
      //     strokeColor: '#0091ea'
      //   })
      //   this.map.add([polygon])
      // })

      // 只显示浦东新区，其他置灰
      // new AMap.DistrictSearch({
      //   extensions:'all',
      //   subdistrict:0
      // }).search('浦东新区',(status,result) => {
      //   // 外多边形坐标数组和内多边形坐标数组
      //   const outer = [
      //     new AMap.LngLat(-360,90,true),
      //     new AMap.LngLat(-360,-90,true),
      //     new AMap.LngLat(360,-90,true),
      //     new AMap.LngLat(360,90,true),
      //   ]
      //   const holes = result.districtList[0].boundaries

      //   const pathArray = [
      //     outer
      //   ]
      //   pathArray.push.apply(pathArray,holes)
      //   const polygon = new AMap.Polygon( {
      //     pathL:pathArray,
      //     //线条颜色，使用16进制颜色代码赋值。默认值为#006600
      //     strokeColor: 'rgb(20,164,173)',
      //     strokeWeight: 4,
      //     //轮廓线透明度，取值范围[0,1]，0表示完全透明，1表示不透明。默认为0.9
      //     strokeOpacity:0.5,
      //     //多边形填充颜色，使用16进制颜色代码赋值，如：#FFAA00
      //     fillColor: 'rgba(255,255,255,0.3)',
      //     //多边形填充透明度，取值范围[0,1]，0表示完全透明，1表示不透明。默认为0.9
      //     fillOpacity: 1,
      //     //轮廓线样式，实线:solid，虚线:dashed
      //     strokeStyle:'dashed',
      //     /*勾勒形状轮廓的虚线和间隙的样式，此属性在strokeStyle 为dashed 时有效， 此属性在
      //         ie9+浏览器有效 取值：
      //         实线：[0,0,0]
      //         虚线：[10,10] ，[10,10] 表示10个像素的实线和10个像素的空白（如此反复）组成的虚线
      //         点画线：[10,2,10]， [10,2,10] 表示10个像素的实线和2个像素的空白 + 10个像素的实
      //         线和10个像素的空白 （如此反复）组成的虚线*/
      //     strokeDasharray:[10,2,10]
      //   })
      //   polygon.setPath(pathArray)
      //   this.map.add(polygon)
      // })
    },
  },
  computed: {
    tableHeight() {
      return screen.height / 2
    }
  }
}
</script>

<style lang="stylus" scoped>
#container
  width 100%
  height 100%
  resize both
  position relative
  cursor auto
  .menu
    position absolute
    width 18%
    text-align left
    top 1rem
    left 1rem
    z-index 100
    max-height 90vh
    overflow-y auto
</style>
<style lang="stylus">
.amap-logo
.amap-copyright
  display none !important
.amap-icon
  img
    width 100%
    height 100%
.menu
  .ivu-collapse-content
    max-height 80vh
    overflow-y auto
    overflow-x hidden
    padding 0 1rem
    .ivu-collapse-content-box
      padding 1rem 0
      button
        text-align left
        font-size 1rem
</style>
