<template>
  <div id="elevatorMapContainer">
    <template v-if="curStreetData.name && curStreet">
      <Collapse :value="[curStreet]" class="menu" accordion>
        <Panel v-for="street in streetList" :key="street" :name="street">
          <span>
            {{curStreetData.name}}小区列表
            <a class="back-btn" @click="backToMainPage">返回</a>
          </span>
          <div slot="content" class="community-list">
            <div v-for="(item, i) in curCommunity" :key="item.name + i">
              <Button
                @click="handleView(item)"
                size="small"
                type="text"
                long>
                {{item.name}}
              </Button>
              <a @click="handleDetail(item)">详情</a>
            </div>
          </div>
        </Panel>
      </Collapse>
      <div class="icon-tooltip">
        <p><span />不具备条件</p>
        <p><span />改造后具备条件</p>
        <p><span />已具备条件</p>
        <p><img src="@/assets/images/than500.gif"/>已有居民表达同意加装</p>
        <p><img src="@/assets/images/notice.gif"/>已公告加梯幢</p>
      </div>
    </template>
    <template v-if="!curStreet">
      <Collapse class="menu" accordion>
        <Panel>
          街镇列表
          <div slot="content" class="community-list">
            <div v-for="(item, i) in Object.keys(streetDic)" :key="item + i">
              <Button
                @click="toWhichStreet(streetDic[item])"
                size="small"
                type="text"
                long>
                {{streetDic[item]}}
              </Button>
            </div>
          </div>
        </Panel>
      </Collapse>
    </template>
    <Drawer :closable="false" width="24%" v-model="detailDrawer">
      <div slot="header">
        <h2>{{detailDrawerData.community}}</h2>
        <p style="font-weight:normal;color:#666;margin-top:.5rem;">{{detailDrawerData.buildingNo}}</p>
      </div>
      <div class="drawer-content">
        <div>
          <p class="title">加装条件</p>
          <div class="condition" :style="$com.switchColor(detailDrawerData.color)"/>
        </div>
        <div>
          <p class="title">居民意愿度</p>
          <!-- <p class="title">加装可能性</p> -->
          <img v-for="i in $com.switchStarNum(detailDrawerData.intention)" :key="i" class="star" src="@/assets/images/star1.png"/>
        </div>
        <div>
          <p class="title">加装意愿收集</p>
          <p class="sub-title"><span>已投/应投</span><span>{{Math.round((detailDrawerData.agree + detailDrawerData.disagree) / detailDrawerData.totUnit * 100)}}%</span></p>
          <img class="bar" :src="require(`@/assets/images/${$com.switchImg((detailDrawerData.agree + detailDrawerData.disagree) / detailDrawerData.totUnit)}.png`)"/>
          <p class="sub-title"><span>同意/不同意</span><span>{{Math.round(detailDrawerData.ratio * 100)}}%</span></p>
          <img class="bar" :src="require(`@/assets/images/${$com.switchImg(detailDrawerData.ratio)}.png`)"/>
        </div>
        <div>
          <p class="title">加装情况</p>
          <span class="status"><img src="@/assets/images/signed.png"/>{{$com.switchStatus(detailDrawerData.status)}}</span>
        </div>
      </div>
    </Drawer>
    <Modal v-model="detailModal" width="90%" :footer-hide="true">
      <Table v-if="detailModal" :columns="columns" :data="detailData" size="small" :max-height="tableHeight"/>
    </Modal>
  </div>
</template>

<script>
const {AMap} = window
import axios from 'axios'
export default {
  name: 'PudongElevatorMap',
  data() {
    return {
      map: null,
      detailDrawer: false,
      detailDrawerData: {},
      mapConfig: {
        resizeEnable: true,
        rotateEnable: true,
        pitchEnable: true,
        showLabel: true,
        zoom: 15,
        pitch: 50,
        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'],
      },
      streetList: [],
      curStreetPolygon: null,
      curStreet: null,
      markerCollection: [],
      detailModal: false,
      columns: [
        {
          title: '小区',
          key: 'name',
          minWidth: 150,
          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: [],
      streetDic: {
        beicai: '北蔡',
        caolu: '曹路',
        chuansha: '川沙',
        datuan: '大团',
        dongming: '东明',
        gaodong: '高东',
        gaoqiao: '高桥',
        gaoxing: '高行',
        hangtou: '航头',
        heqing: '合庆',
        huamu: '花木',
        hudong: '沪东',
        huinan: '惠南',
        jinqiao: '金桥',
        jinyang: '金杨',
        kangqiao: '康桥',
        laogang: '老港',
        lujiazui: '陆家嘴',
        nanhui: '南汇新城',
        nanmatou: '南码头',
        nicheng: '泥城',
        puxing: '浦兴',
        sanlin: '三林',
        shanggang: '上钢',
        shuyuan: '书院',
        tangqiao: '塘桥',
        tangzhen: '唐镇',
        wanxiang: '万祥',
        weifang: '潍坊',
        xinchang: '新场',
        xuanqiao: '宣桥',
        yangjing: '洋泾',
        zhangjiang: '张江',
        zhoupu: '周浦',
        zhuqiao: '祝桥',
        zhoujiadu: '周家渡',
      },
      curStreetData: {},
      buildingData: {
        community: [],
        building: [],
      },
      eleDataSource: [],
    }
  },
  mounted() {
    this.$nextTick(this.initMap)
  },
  methods: {
    initMap(area) {
      this.map = new AMap.Map('elevatorMapContainer', this.mapConfig)
      this.addController()
      this.initMenu()
    },
    addController() { // 添加地图控制器
      this.map.addControl(new AMap.ControlBar({
        showZoomBar: false,
        showControlButton: true,
        position: {
          right: '10px',
          top: '10px',
        }
      }))
      // this.map.on('click', e => {
      //   console.log(e.lnglat.getLng() + ',' + e.lnglat.getLat())
      // })
    },
    async initMenu() { // 初始化列表菜单
      const streets = Object.keys(this.streetDic)
      if (this.$route.query && this.$route.query.name) { // 判断路由有街镇则显示该街镇列表
        const streetName = this.$route.query.name
        /** ----请求电梯加装数据----- */
        const {data} = await axios.get(`http://211.136.105.193/apiv2/service-report/public/elv/consentRate?strName=${streetName}`)
        this.eleDataSource = data && data.data && data.data.content // 请求
        /** ---------------------- */
        const result = streets.find(key => streetName.indexOf(this.streetDic[key]) >= 0) // 取得相符的街镇数据
        this.streetList = [result]
        this.$nextTick(() => { // 为了展开默认街镇小区列表
          this.curStreet = result
          this.initStreet()
        })
      }
    },
    initStreet() { // 初始化街镇
      const streetData = require(`@/mock/${this.curStreet}.js`).default
      this.curStreetData = streetData
      this.map.setZoomAndCenter(15, streetData.location)
      this.highlightArea(streetData)
    },
    highlightArea(area) { // 高亮区域
      if (this.$route.query && this.$route.query.community) return
      if (!area.path || area.path <= 0) return
      if (this.curStreetPolygon) { // 先清除已存在的高亮区域
        this.map.clearMap()
      }
      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
      this.map.add([polygon])
    },
    handleDetail({name}) {
      this.detailData = this.buildingData.building.filter(item => {
        const buildingName = item.name && (item.name + '').replace('(补)', '').replace('（补）', '')
        return buildingName.indexOf(name) >= 0 || (item.buildingNo + '').indexOf(name) >= 0
      })
      this.detailModal = true
    },
    initLayers() { // 配置地图图层信息
      if (!this.curStreetData.name) return
      const communityList = [...this.curCommunity, ...this.curBuildingData]
      const buildingOptions = {
        areas: communityList.map(community => {
          if (community.type != 'building') {
            new AMap.Polygon({ // 上色小区的底板颜色
              zIndex: 10,
              bubble: false,
              fillColor: 'green',
              fillOpacity: 0.2,
              strokeWeight: 1,
              path: community.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(community)
            })
          }
          return {
            rejectTexture:true, // 是否屏蔽自定义地图的纹理
            color1: this.$com.switchBuildingColor(community.level)[0], // 楼顶颜色
            color2: this.$com.switchBuildingColor(community.level)[1], // 楼面颜色
            path: community.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, // 咱们自定义的建筑物上色图层
      ])
    },
    handleView({name, address, location}) { // 点击列表小区名或者地图小区图块事件
      this.map.setZoomAndCenter(18, location)
      // this.addMarker(name) // 07-01移至watch中
      this.showInfoTips(null, location, {title: name, content: address})
    },
    addMarker(name) { // 点击小区后展示各楼栋的marker
      // this.map.remove(this.markerCollection) // 移除之前的marker // 07-01注释 为了初始化的时候就全部显示
      const markerCollection = []
      // const {data} = await axios.get('http://yapi.omniview.pro/mock/279/public/elv/consentRate')
      // const mock = [{
      //   'unitNo': '20号',
      //   'streetId': '12345',
      //   'streetName': '街道',
      //   'sectId': '123123',
      //   'sectName': '浦东龙阳花苑',
      //   'unitId': '112',
      //   'unitAddr': '门牌地址',
      //   'totUnit': 33,//应投
      //   'ratio': 0.15233445,//同意率
      //   'agree': 10,//同意
      //   'disagree': 10, //不同意
      //   'status' : '2'
      // }]
      const communityName = name && (name + '').replace('(补)', '').replace('（补）', '')
      const datasource = this.eleDataSource.filter(e => e.sectName.indexOf(communityName) >= 0 || communityName.indexOf(e.sectName) >= 0) // 筛选出返回数据中的相关小区数据
      this.markerCollection = this.initMarker(name, datasource)
      this.map.add(this.markerCollection)
    },
    addSpecialMarker() { // 添加地图中特殊的标志点（已公告、同意率>50%等）
      const markers = []
      this.eleDataSource.forEach(item => {
        if (item.ratio >= 0.5) { // 同意率>50%
          const communityName = item.sectName && (item.sectName + '').replace('(补)', '').replace('（补）', '')
          const cur = this.buildingData.building.find(e => {
            const name = e.name && (e.name + '').replace('(补)', '').replace('（补）', '')
            return (communityName.indexOf(name) >= 0 || name.indexOf(communityName) >= 0) && ((e.buildingNo + '').indexOf(item.unitNo) >= 0 || item.unitNo.indexOf(e.buildingNo) >= 0) && (e.lon && e.lat)
          }) // 查找出返回数据中的同一幢楼栋数据
          if (!cur) return
          const marker = new AMap.Marker({
            position: [cur.lon, cur.lat],
            offset: new AMap.Pixel(-10, -65),
            icon: new AMap.Icon({
              size: [20, 30],
              image: require('@/assets/images/than500.gif'),
            }),
            extData: {
              community: cur.name,
              buildingNo: cur.buildingNo,
              intention: cur.intention,
              lon: cur.lon,
              lat: cur.lat,
              color: cur.color,
              ...item
            },
          }).on('click', e => {
            this.detailDrawer = true
            this.detailDrawerData = marker.getExtData()
            const {lon, lat} = this.detailDrawerData
            this.showInfoTips(e, [e.lnglat.getLng(), e.lnglat.getLat()], marker.getExtData(), this.addPrism(lon, lat))
          })
          markers.push(marker)
        }
        if (item.status == '1') { // 状态为已公告
          const communityName = item.sectName && (item.sectName + '').replace('(补)', '').replace('（补）', '')
          const cur = this.buildingData.building.find(e => {
            const name = e.name && (e.name + '').replace('(补)', '').replace('（补）', '')
            return (communityName.indexOf(name) >= 0 || name.indexOf(communityName) >= 0) && (e.buildingNo && e.buildingNo.indexOf(item.unitNo) >= 0 || item.unitNo.indexOf(e.buildingNo) >= 0) && (e.lon && e.lat)
          }) // 查找出返回数据中的同一幢楼栋数据
          if (!cur) return
          const marker = new AMap.Marker({
            position: [cur.lon, cur.lat],
            offset: new AMap.Pixel(-10, -65),
            icon: new AMap.Icon({
              size: [20, 30],
              image: require('@/assets/images/notice.gif'),
            }),
            extData: {
              community: cur.name,
              buildingNo: cur.buildingNo,
              intention: cur.intention,
              lon: cur.lon,
              lat: cur.lat,
              color: cur.color,
              ...item
            },
          }).on('click', e => {
            this.detailDrawer = true
            this.detailDrawerData = marker.getExtData()
            const {lon, lat} = this.detailDrawerData
            this.showInfoTips(e, [e.lnglat.getLng(), e.lnglat.getLat()], marker.getExtData(), this.addPrism(lon, lat))
          })
          markers.push(marker)
        }
      })
      this.map.add(markers)
    },
    initMarker(name, buildingDatas) { // 初始化添加楼栋图标，返回图标集合
      const markerCollection = []
      const configMarker = item => {
        const buildingName = item.name && (item.name + '').replace('(补)', '').replace('（补）', '')
        if (buildingName.indexOf(name) < 0 && (item.buildingNo + '').indexOf(name) < 0) return // （筛选出点击的小区的楼栋）楼栋的小区名和name一致则往下走
        // const curObj = buildingDatas.find(e => e.unitAddr.indexOf(item.buildingNo) >= 0 || item.buildingNo.indexOf(e.unitAddr) >= 0) // 查找出返回数据中的同一幢楼栋数据
        const curObj = buildingDatas.find(e => e.unitNo.indexOf(item.buildingNo + '') >= 0 || (item.buildingNo + '').indexOf(e.unitNo) >= 0) // 查找出返回数据中的同一幢楼栋数据

        if (!curObj) return
        if (curObj.ratio < 0.25) return
        if(item && item.lon && item.lat && item.intention) {
          const marker = new AMap.Marker({
            position: [item.lon, item.lat],
            icon: new AMap.Icon({
              size: [20, 15],
              image: require(`@/assets/images/${this.$com.switchIcon(curObj.ratio)}.png`),
            }),
            extData: {
              community: item.name,
              buildingNo: item.buildingNo,
              intention: item.intention,
              lon: item.lon,
              lat: item.lat,
              color: item.color,
              ...curObj
            },
          }).on('click', e => {
            this.detailDrawer = true
            this.detailDrawerData = marker.getExtData()
            const {lon, lat} = this.detailDrawerData
            this.showInfoTips(e, [e.lnglat.getLng(), e.lnglat.getLat()], marker.getExtData(), this.addPrism(lon, lat))
          })
          markerCollection.push(marker)
        }
      }
      this.buildingData.building.forEach(configMarker) // 遍历楼栋数据逐一设置图标
      return markerCollection
    },
    showInfoTips(e, location, data, prism = null) { // 地图显示浮窗信息
      let infoWindow = null
      if (data.title && data.content) { // 展示小区信息
        infoWindow = new AMap.InfoWindow({
          content: `
            <div>
              <b>${data.title}</b>
              <p>${data.content || '暂无其他信息'}</p>
            </div>
          `
        })
      } else { // 展示楼栋信息
        const img = require(`@/assets/images/${this.$com.switchImg(data.ratio)}.png`)
        infoWindow = new AMap.InfoWindow({
          content: `
            <div>
              <b>${data.community}</b>
              <p style="margin:0.5rem 0;">${data.community} ${data.buildingNo}</p>
              <p style="display:flex;align-items:center;justify-content:space-between;">
                <img style="width:80%;height:2rem;margin:0.5rem 0;" src='${img}'"/>
                <b style="color:#34a2ff;">${Math.round(data.ratio * 100)}%</b>
              </p>
            </div>
          `
        }).on('close', e => {
          if (!prism) return
          prism.clear()
        })
      }
      infoWindow.open(this.map, location)
    },
    addPrism(lon, lat, height = 300, color = 'rgba(100,150,230,0.7)') { // 添加立体遮罩
      const LENGTH = 0.00015
      const po1 = [Number(lon) + LENGTH, lat]
      const po2 = [lon, Number(lat) + LENGTH]
      const po3 = [Number(lon) - LENGTH, lat]
      const po4 = [lon, Number(lat) - LENGTH]
      const paths = [po1, po2, po3, po4, po1]

      const object3d = new AMap.Object3DLayer()
      this.map.add(object3d)
      const prism = new AMap.Object3D.Prism({
        path: paths.map(path => new AMap.LngLat(path[0], path[1])),
        height,
        color,
      })
      prism.transparent = true
      object3d.add(prism)
      return object3d
    },
    toWhichStreet(name) {
      this.$router.replace({
        path: '/',
        query: {
          name,
        }
      })
      location.reload()
    },
    backToMainPage() {
      this.$router.replace({path: '/'})
      location.reload()
    },
  },
  computed: {
    tableHeight() {
      return screen.height / 2
    },
    curCommunity() { // 小区列表大致颜色
      if (this.$route.query && this.$route.query.community) {
        const {community} = this.$route.query
        return [...this.curStreetData.community].filter(item => item.name.indexOf(community) >= 0 || community.indexOf(item.name) >= 0)
      }
      return [...this.curStreetData.community]
    },
    curBuildingData() { // 附加的自描的楼栋
      if (this.$route.query && this.$route.query.community) {
        const {community} = this.$route.query
        return [...this.buildingData.community].filter(item => item.name.indexOf(community) >= 0 || community.indexOf(item.name) >= 0)
      }
      return [...this.buildingData.community]
    },
  },
  watch: {
    async curStreet(cur) { // 监控转换后的路由街镇名来获取匹配数据
      if (!cur) return
      const {data} = await axios.get(`${this.$api.STATIC_URL}/mock/${cur}-building.json`)
      this.buildingData = data || {
        community: [],
        building: [],
      }
      this.initLayers()
      this.curCommunity.forEach(item => {
        this.addMarker(item.name)
      })
      this.addSpecialMarker() // TODO 是否先清除之前的？
      if (this.$route.query && this.$route.query.community) { // 如果有输入小区名则直接聚焦该小区
        this.handleView(this.curCommunity[0])
      }
    }
  }
}
</script>

<style lang="stylus" scoped>
#elevatorMapContainer
  width 100%
  height 100%
  resize both
  position relative
  .back-btn
    float right
    margin-right 1rem
  .menu
    position absolute
    width 18%
    text-align left
    top 1rem
    left 1rem
    z-index 100
    .community-list
      >div
        display flex
        justify-content space-between
        a
          display block
          min-width 5rem
          text-align right
  .tab-menu
    position absolute
    top 1rem
    left calc(18% + 2rem)
    z-index 100
    background #fff
.drawer-content
  >div
    margin-bottom 2rem
    .title
      font-size 1rem
      font-weight bold
      margin-bottom .5rem
    .sub-title
      display flex
      justify-content space-between
      margin .5rem 0
      span
        font-size .9rem
        color #666
        &:last-child
          font-weight bold
          color #34a2ff
    .condition
      width 50%
      height 3rem
      background #8fd618
      border-radius .2rem
    img.star
      width 10%
      margin-right 5%
    img.bar
      width 100%
      height 2rem
    .status
      display flex
      align-items center
      img
        width 3rem
        height @width
        margin-right 1rem
.icon-tooltip
  position absolute
  top 1rem
  left calc(18% + 2rem)
  z-index 100
  p
    display flex
    align-items center
    color #000
    font-weight bold
    margin-bottom 1rem
    text-align left
    span
      display inline-block
      width 4rem
      height 2rem
      margin-right 1rem
    &:nth-child(1)
      span
        background #c60101
    &:nth-child(2)
      span
        background #f6e102
    &:nth-child(3)
      span
        background #95f500
    img
      width 1.5rem
      height auto
      margin 0 2rem 0 1.5rem
</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
.tab-menu
  .ivu-tabs-bar
    margin-bottom 0
  .ivu-tabs-nav
    .ivu-tabs-tab
      &:last-child
        margin-right 0
</style>
