<template>
  <m-grid
    :template="['title title title', 'left . right']"
    columns="16vw auto 49vw"
    rows="0.4rem auto"
    gap="0.05rem"
  >
    <m-title area="title"> 南东城运{{ title }} </m-title>
    <m-map ref="map" @complete="handleComplete" @event="handleMapClick" />
    <m-animate enter="fadeInLeft" leave="fadeOutLeft">
      <LeftSection
        area="left"
        :info="buildingInfo"
        @select="onSelectBuilding"
      />
    </m-animate>
    <m-animate enter="fadeInRight" leave="fadeOutRight">
      <RightSection area="right" @select="focus" />
    </m-animate>
    <!-- <div class="btns">
      <div
        v-for="btn in btns"
        :key="btn.key"
        :class="{ on: btn.key === curBtn }"
        @click="handleClick(btn.key)"
      >
        <p>{{ btn.name }}</p>
      </div>
    </div> -->
    <SiteSelector />
    <div class="operates">
      <a-tooltip placement="right">
        <img
          :src="curMapType === '2D' ? d3 : d2"
          draggable="false"
          @click="switchMapType(curMapType === '2D' ? '3D' : '2D')"
        />
        <template #title>
          切换为{{ curMapType === '2D' ? '3D' : '2D' }}
        </template>
      </a-tooltip>
      <a-tooltip placement="right">
        <img
          draggable="false"
          src="@/assets/images/map-btn5.png"
          @click="rotateAngle"
        />
        <template #title>旋转90度</template>
      </a-tooltip>
      <a-tooltip placement="right">
        <img
          draggable="false"
          src="@/assets/images/map-btn4.png"
          @click="showMonitor = true"
        />
        <template #title>电瓶车入梯报警</template>
      </a-tooltip>
      <!-- <a-tooltip placement="right">
        <img
          draggable="false"
          src="@/assets/images/map-btn6.png"
          @click="showCommunityPoints"
        />
        <template #title>
          {{ isCommunityPointsShowNow ? '隐藏' : '显示' }}小区点
        </template>
      </a-tooltip> -->
      <a-tooltip placement="right">
        <img
          draggable="false"
          src="@/assets/images/zoom-in.png"
          @click="zoomMap('in')"
        />
        <template #title> 放大地图 </template>
      </a-tooltip>
      <a-tooltip placement="right">
        <img
          draggable="false"
          src="@/assets/images/zoom-out.png"
          @click="zoomMap('out')"
        />
        <template #title> 缩小地图 </template>
      </a-tooltip>
    </div>
    <m-modal
      v-model="showMonitor"
      title="电瓶车入梯监控"
      width="30%"
      offset="-70%"
    >
      <div>
        <VideoComponent :video-src="video" />
        <div class="alarm-btn" @click="handleAlarm">报警</div>
      </div>
    </m-modal>
    <m-drawer v-model="showDrawer" width="32vw">
      <m-card :title="drawerInfo.key">
        <div class="drawer-info">
          <p class="title">[ {{ drawerInfo.relationName }} ]</p>
          <div v-if="drawerInfo.afterPhoto">
            <p>整改后</p>
            <img
              :src="
                drawerInfo.afterPhoto
                  .split(',')[0]
                  .replace('https://zhongbang.omniview.pro/', prefix)
                  .replace('http://zhongbang.omniview.pro/', prefix)
              "
            />
          </div>
          <div v-if="drawerInfo.beforPhoto">
            <p>整改前</p>
            <img
              :src="
                drawerInfo.beforPhoto
                  .split(',')[0]
                  .replace('https://zhongbang.omniview.pro/', prefix)
                  .replace('http://zhongbang.omniview.pro/', prefix)
              "
            />
          </div>
        </div>
      </m-card>
    </m-drawer>
  </m-grid>
</template>

<script lang="ts">
import {
  computed,
  defineComponent,
  onMounted,
  ref,
  nextTick,
  watch,
  onUnmounted,
} from 'vue'
import LeftSection from '@/view/new-community/left.vue'
import RightSection from '@/view/new-community/right.vue'
import SiteSelector from '@/view/community/site-selector.vue'
import VideoComponent from '@/view/components/video-component.vue'
import store from '@/store'
import point from '@/assets/images/point.png'
import point1 from '@/assets/images/point1.png'
import point2 from '@/assets/images/point2.png'
import point3 from '@/assets/images/point3.png'
import point4 from '@/assets/images/point4.png'
import point5 from '@/assets/images/point5.png'
import point6 from '@/assets/images/point6.png'
import point7 from '@/assets/images/point7.png'
import video from '@/assets/images/ele-monitor.mp4'
import { useRoute } from 'vue-router'
import { ajax, api } from '@/ajax'
import { message } from 'ant-design-vue'
import a01 from '@/assets/images/a01.png'
import a02 from '@/assets/images/a02.png'
import a03 from '@/assets/images/a03.png'
import a04 from '@/assets/images/a04.png'
import d2 from '@/assets/images/2d.png'
import d3 from '@/assets/images/3d.png'

export default defineComponent({
  name: 'NewCommunity',
  components: { LeftSection, RightSection, SiteSelector, VideoComponent },
  setup() {
    const buildingList = computed(
      () => store.state.communityInfo.communityList || []
    )
    const curMapType = computed(() => store.state.curMapType)
    const prefix = computed(() => api.SOURCE_URL)
    const rotation = ref(0)
    const rotateAngle = () => {
      rotation.value += 90
      if (rotation.value >= 360) {
        rotation.value = 0
      }
      const result: any = {
        '527635870583459840': {
          zoom: 1,
          center: [121.4642191813353, 31.229242441205542],
        },
        '527635870583459841': {
          zoom: 1,
          center: [121.46537699130965, 31.230185340301105],
        },
      }
      const cur = result[curId.value as string]
      map.value.rotate(cur.center, rotation.value, curMapType.value)
      // map.value.cameraTo({ heading: rotation.value })
    }
    const loading = ref(true)
    const title = computed(
      () => store.state.communityInfo.bigscreenCommunityName
    )
    const communityOptions = computed(() => store.state.communityOptions)
    const route = useRoute()
    const curId = ref<undefined | string>()
    const initData = (id?: string) => {
      store.dispatch('initCommunityData', id)
    }
    const map = ref<any>(null)
    curId.value = (route.query.id as string) || communityOptions.value[0].type
    initData(curId.value)
    store.commit(
      'SET_CURRENT_VIEW',
      communityOptions.value.find((item) => item.type == curId.value)
    ) // 使标题不显示公共的3个按钮
    onMounted(async () => {
      await nextTick()
      map.value.initMap()
    })
    const points = ref<any>(null)
    const initMapPoints = (key: string, data: any[]) => {
      const getIcon = (classification: string, type: string) => {
        if (classification === '摄像头') return point
        if (classification === '为老设施') return point7
        if (type.indexOf('车棚') >= 0) return point2
        if (type.indexOf('充电') >= 0) return point5
        if (type.indexOf('电梯加装') >= 0) return point3
        if (type.indexOf('垃圾箱') >= 0) return point6
        return point4 // 默认为美丽家园-微更新
      }
      const pointData = data.map((item: any) => {
        const position = item.coordinate && item.coordinate.split(',')
        return Object.assign({}, item, {
          name: item.id,
          x: position && +position[0],
          y: position && +position[1],
          icon: getIcon(item.classification, item.relationName),
        })
      })
      points.value = map.value.addPoint({
        key: key,
        size: [100, 500],
        data: pointData,
      })
    }
    function addAllFlags() {
      buildingList.value.forEach((item) => {
        if (!item.x || !item.y) return
        map.value.addFlag({
          id: item.id,
          sectId: item.sectId,
          name: item.sectName,
          x: +item.x,
          y: +item.y,
          z: 30,
        })
      })
      setTimeout(function () {
        document.querySelectorAll('._building-btn')?.forEach(function (el) {
          el.addEventListener('click', addEvent)
        })
      }, 1000)
    }
    function focusCenterAndAddLayer() {
      addAllFlags()
      if (!curId.value) return
      const result: any = {
        '527635870583459840': {
          // 振兴小区
          zoom: 1,
          center: [121.4642191813353, 31.229242441205542],
        },
        '527635870583459841': {
          // 威海路小区
          zoom: 1,
          center: [121.46537699130965, 31.230185340301105],
        },
      }
      const cur = result[curId.value as string]
      map.value.focus(...cur.center, cur.zoom)
      return cur
    }
    function focus(location: any[]) {
      if (!map.value) return
      map.value.focus(...location, 0.5)
    }
    const showDrawer = ref(false)
    const drawerInfo = ref<any>({})
    const handleMapClick = (e: any) => {
      if (e.classification === '微更新') {
        drawerInfo.value = e
        showDrawer.value = true
      } else {
        drawerInfo.value = null
        showDrawer.value = false
      }
    }
    const isCommunityPointsShowNow = ref(false)
    async function showCommunityPoints() {
      isCommunityPointsShowNow.value = !isCommunityPointsShowNow.value
      if (!isCommunityPointsShowNow.value) {
        map.value.hideCommunity()
        return
      }
      store.commit('SET_LOADING', true)
      const { content } = (
        await ajax.get({
          url: api.GET_COMMUNITY_IDS,
          params: { bigscreenCommunityId: curId.value },
          showLoading: false,
        })
      ).data
      map.value.setFilter(content)
      map.value.showCommunity()
      store.commit('SET_LOADING', false)
    }
    const handleComplete = () => {
      // map.value.layer('model_white_zw').visible = false
      loading.value = false
      setTimeout(() => {
        focusCenterAndAddLayer()
      }, 2000)
    }
    watch(
      () => buildingList.value,
      () => {
        if (!map.value) return
        addBuildingPoints()
      },
      { immediate: true }
    )
    let entryPoints: any = []
    async function addBuildingPoints() {
      map.value.remove(entryPoints)
      const pathList: any[] = []
      const entryList: any[] = []
      for (let i = 0; i < buildingList.value.length; i++) {
        const { gis, id, sectId } = buildingList.value[i]
        const paths = (gis && JSON.parse(gis))?.map((e: any) => [+e.x, +e.y])
        if (paths && paths.length > 0) {
          pathList.push({
            key: id,
            paths,
          })
        }
        const entry = (
          (
            await ajax.get({
              url: api.GET_COMMUNITY_FACILITY,
              params: { sectId, pageSize: 1000 },
              showLoading: false,
            })
          ).data?.content || []
        )?.filter((item: any) => item.relationName.includes('入口'))
        entryList.push(...entry)
      }
      entryPoints = map.value.addPoint({
        key: 'entry-points',
        size: 20,
        icon: a04,
        data: entryList,
      })
      // 大楼勾边
      pathList.forEach((item) => {
        map.value.addPolyLine({
          key: item.key,
          paths: item.paths,
        })
      })
    }
    function addEvent() {
      fetchBuildingInfo((this as any).getAttribute('data-id'))
    }
    onUnmounted(() => {
      document.querySelectorAll('._building-btn')?.forEach(function (el) {
        el.removeEventListener('click', addEvent)
      })
    })
    const showMonitor = ref(false)
    const handleAlarm = async () => {
      const res: any = await ajax.post({
        url: api.POST_ALARM,
        params: {
          equipmentAddr: '摄像头',
          equipmentNo: '上海市',
        },
        headers: { AccessCode: '43gh4hjv34j1234bb51j23k4bh' },
      })
      if (res.code == '200' && res.msg === 'success') {
        message.success('短信发送成功！')
      }
    }
    const zoomMap = (type: string) => {
      map.value.zoom(type)
    }
    const onSelectBuilding = (item: any) => {
      map.value.hideFlag()
      if (!item || !item.x || !item.y) return
      buildingList.value
        .filter((e) => e.id != item.id)
        .forEach((item) => {
          if (!item.x || !item.y) return
          map.value.addFlag({
            id: item.id,
            sectId: item.sectId,
            name: item.sectName,
            x: +item.x,
            y: +item.y,
            z: 30,
          })
        })
      map.value.addFlag({
        id: item.id,
        sectId: item.sectId,
        name: item.sectName,
        x: +item.x,
        y: +item.y,
        z: 30,
        style: 'color:gold;font-weight:bold;',
      })
      setTimeout(function () {
        document.querySelectorAll('._building-btn')?.forEach(function (el) {
          el.addEventListener('click', addEvent)
        })
      }, 1000)
    }
    const buildingInfo = ref<any>({})
    async function fetchBuildingInfo(sectId: string) {
      const communityInfo =
        (
          await ajax.get({
            url: api.GET_COMMUNITY,
            params: { sectId },
          })
        )?.data?.content?.[0] || {}
      const roomInfo =
        (
          await ajax.get({
            url: api.GET_BUILDINGS,
            params: { sectId },
          })
        )?.data?.content?.[0] || {}
      buildingInfo.value = { ...communityInfo, ...roomInfo }
    }
    let buildingPoints: any = null
    watch(
      () => store.state.buildingPoints,
      (points) => {
        buildingPoints && map.value.remove(buildingPoints)
        if (!points || points.length === 0) return
        const data: any = []
        points.forEach((item: any) => {
          if (!item.x || !item.y) return
          if (item.classification.includes('为老')) {
            item.icon = a01
          } else if (item.classification.includes('小区')) {
            item.icon = a02
          } else if (item.classification.includes('摄像头')) {
            item.icon = a03
          } else {
            return
          }
          data.push(item)
        })
        buildingPoints = map.value.addPoint({
          key: 'building-points',
          size: 20,
          data,
        })
      }
    )

    function switchMapType(type: string) {
      rotation.value = 0
      store.commit('SET_MAP_TYPE', type)
    }
    watch(
      () => curMapType.value,
      (type) => {
        const result: any = {
          '527635870583459840': {
            zoom: 1,
            center: [121.4642191813353, 31.229242441205542],
          },
          '527635870583459841': {
            zoom: 1,
            center: [121.46537699130965, 31.230185340301105],
          },
        }
        if (type === '2D') {
          map.value.hideFlag()
        } else {
          addAllFlags()
        }
        const cur = result[curId.value as string]
        map.value.focus(...cur.center, cur.zoom, {
          duration: 2.0,
          offset: {
            heading: 0,
            pitch: type === '2D' ? -90 : -35,
            range: 0,
          },
        })
      }
    )
    return {
      d2,
      d3,
      curMapType,
      prefix,
      rotation,
      rotateAngle,
      loading,
      title,
      map,
      focus,
      handleComplete,
      showDrawer,
      drawerInfo,
      handleMapClick,
      // btns,
      // curBtn,
      // handleClick,
      showMonitor,
      video,
      handleAlarm,
      isCommunityPointsShowNow,
      showCommunityPoints,
      zoomMap,
      onSelectBuilding,
      buildingInfo,
      switchMapType,
    }
  },
})
</script>

<style lang="stylus" scoped>
@import '../components/MyComponent/main.styl'
.operates
  position fixed
  right calc(49vw + .1rem)
  bottom 0
  z-index 999
  img
    display block
    width .2rem
    height @width
    margin-bottom .05rem
    cursor pointer
    transition transform .3s ease
    $blur()
    background rgba(0,0,0,.6)
    &:hover
      transform-origin right top
      transform scale(1.2)
.drawer-info
  height 81vh
  overflow-x hidden
  overflow-y auto
  .title
    color $blue
    font-size .14rem
    font-family $font-zcool
    margin-bottom .1rem
  >div
    display flex
    margin-bottom .1rem
    >p
      width .25rem
      padding 0 .05rem
      $center()
      border .01rem solid $primary-border
    img
      flex 1
  img
    width 3rem
.btns
  position fixed
  z-index 9999
  width 35vw
  left 16vw
  bottom .1rem
  display flex
  justify-content space-around
  >div
    min-width 1.1rem
    text-align center
    background url('@/assets/images/map-btn-bg.png') 100% / 100% 100% no-repeat
    font-family $font-zcool
    font-size .18rem
    color #ccc
    cursor pointer
    opacity .8
    transition all .3s ease-in-out
    position relative
    p
      transform translateY(-40%)
    &:hover
      color #fff
      opacity 1
    &.on
      color #fff
      opacity 1
      p
        -webkit-box-reflect below -0.17rem linear-gradient(transparent, rgba(255,255,255,.6))
      &:after
        content ''
        display block
        position absolute
        height .06rem
        bottom 0
        left 0
        right 0
        background rgba(91,213,255,.4)
        box-shadow 0 0 0.1rem 0.02rem rgba(91,213,255,.5)
.alarm-btn
  display inline-block
  width 1rem
  padding .06rem 0
  margin-left 50%
  transform translateX(-50%)
  text-align center
  font-size .12rem
  font-weight bold
  cursor pointer
  z-index 1
  position relative
  color #fff
  background hsl(236,32%,26%)
  overflow hidden
  transition color .2s ease-in-out
  &:before
    content ''
    z-index -1
    position absolute
    top 50%
    left @top
    width 1em
    height @width
    border-radius 50%
    background $edge
    transform-origin center
    transform translate3d(-50%, -50%, 0) scale3d(0,0,0)
    transition transform .25s ease-in-out
  &:hover
    color #161616
    &:before
      transform translate3d(-50%, -50%, 0) scale3d(15, 15, 15)
</style>
