<template>
  <div class="main">
    <m-title area="title" :editable="false"> 静安智慧房管 </m-title>
    <m-grid
      v-if="layout.boxNum > 0"
      :template="layout.template"
      columns="1fr 1.5fr 1fr"
      :rows="`${layout.rows}`"
    >
      <Map ref="mapRef" @event="onMapClick" @complete="onMapComplete" />
      <div
        v-for="(_, index) in new Array(layout.boxNum)"
        :key="index"
        class="box"
        :area="`box${index + 1}`"
      >
        <m-animate enter="zoomIn" leave="zoomOut">
          <component
            :is="componentList[components[index]]"
            v-if="!!components[index] && !fullScreen"
          />
        </m-animate>
      </div>
    </m-grid>
    <m-modal v-model="showModal" title="选择展示屏">
      <div class="list-content">
        <div v-for="item in list" :key="item.id" class="item">
          <p>{{ item.configName }}</p>
          <p>{{ item.updateTime }}</p>
          <n-button
            size="tiny"
            type="info"
            ghost
            dashed
            @click="switchDataView(item)"
          >
            查看
          </n-button>
        </div>
      </div>
    </m-modal>
  </div>
  <MapBtns
    :full-screen="fullScreen"
    :is-default-screen="isDefaultScreen"
    :only-one-view="onlyOneView"
    @touch="handleMapBtnsEvents"
  />
  <m-modal v-model="showCommunityDrawer" title="小区档案" width="80%">
    <CommunityInfo :info="communityDetail" />
  </m-modal>
  <m-modal v-model="showElevatorDrawer" title="多层住宅电梯加装" width="50%">
    <ElevatorInfo :info="elevatorDetail" />
  </m-modal>
  <m-modal v-model="showSafetyDrawer" title="房屋安全排查结果" width="50%">
    <SafetyInfo :info="safetyDetail" />
  </m-modal>
  <m-modal v-model="showSearchModal" title="搜索小区">
    <SearchView @select="onSelectCommunity" />
  </m-modal>
</template>

<script lang="ts" setup>
import useLayout from '@/hooks/useLayout'
import useComponent from '@/hooks/useComponent'
import { onMounted, ref, shallowRef } from 'vue'
import { ajax, api } from '@/ajax'
import { NSpace, NButton } from 'naive-ui'
import SearchView from './components/search-view.vue'
import CommunityInfo from './components/community-info.vue'
import ElevatorInfo from './components/elevator-info.vue'
import SafetyInfo from './components/safety-info.vue'
import MapBtns from './components/map-btns.vue'
import Map from './components/map.vue'
import { bus } from '@/utils/component-list'
import store from '@/store'
import c1 from '@/assets/images/c1.png'
import c2 from '@/assets/images/c2.png'
import c3 from '@/assets/images/c3.png'
import c4 from '@/assets/images/c4.png'
import c5 from '@/assets/images/c5.png'
import c6 from '@/assets/images/c6.png'
import CommunityIcon from '@/assets/images/init-point.png'
import BlueOn from '@/assets/images/blue-on.gif'

const mapRef = shallowRef<any>(null)
const { layout } = useLayout()
const { components, componentList } = useComponent()
const list = ref<any[]>([])
const showModal = ref(false)
const defaultConfig = {
  layout: {
    template: ['box1 . box3', 'box2 . box4', 'box2 . box5'],
    rows: '1fr 1fr 0.7fr',
    boxNum: 5,
  },
  components: {
    '0': 'A015',
    '1': 'A016',
    '2': 'A017',
    '3': 'A018',
    '4': 'A019',
  },
}
const onlyOneView = ref(false) // 目前是否为特定id的url大屏
function initConfig() {
  if (window.location.hash) {
    const id = window.location.hash.split('/')?.[1]
    ajax
      .get({
        url: api.CONFIGS,
        params: { id },
      })
      .then((res) => {
        const config = res?.data?.content?.[0] || {}
        switchDataView(config)
      })
    onlyOneView.value = true
    return
  }
  layout.value = defaultConfig.layout
  components.value = defaultConfig.components
  isDefaultScreen.value = true
}
onMounted(initConfig)

const isDefaultScreen = ref(true)
function switchDataView({ id, configJson }) {
  const config = JSON.parse(configJson)
  config?.layout && (layout.value = config.layout)
  config?.components && (components.value = config.components)
  showModal.value = false
  isDefaultScreen.value = false
  window.location.hash = `#/${id}`
}

const fullScreen = ref(false)
const showSearchModal = ref(false)

function handleMapBtnsEvents(key: string) {
  switch (key) {
    case 'list':
      ajax
        .get({
          url: api.CONFIGS,
          params: { configStatus: '1', pageSize: 9000 },
        })
        .then((res) => {
          list.value = res?.data?.content || []
          showModal.value = true
        })
      break
    case 'home':
      window.history.replaceState(
        null,
        '',
        window.location.pathname + window.location.search,
      ) // 移除hash
      initConfig()
      break
    case 'full':
      fullScreen.value = !fullScreen.value
      break
    case 'in':
      mapRef.value?.zoomIn()
      break
    case 'out':
      mapRef.value?.zoomOut()
      break
    case 'search':
      showSearchModal.value = true
      break
    case 'reset':
      onMapComplete()
      mapRef.value?.setCommunityPoints()
      break
    default:
      break
  }
}

let pointsLayer: any
bus.on('addPoints', (data) => {
  addPoints(data)
})
bus.on('communityList', (data) => {
  store.commit('SET_COMMUNITY_LIST', data)
})
bus.on('elevatorInfo', (data) => {
  elevatorDetail.value = data
  showElevatorDrawer.value = true
})
function onMapComplete() {
  addPoints({ data: store.state.communityList, icon: CommunityIcon, size: 6 })
}

function addPoints(data) {
  mapRef.value?.remove(pointsLayer)
  pointsLayer = mapRef.value?.addPoints(data)
  mapRef.value?.focus([-1931.2637583608503, 4334.0159596985895], { zoom: 4 })
}

const showCommunityDrawer = ref(false)
const communityDetail = ref<{ [key: string]: any }>({})
const showElevatorDrawer = ref(false)
const elevatorDetail = ref<{ [key: string]: any }>({})
const showSafetyDrawer = ref(false)
const safetyDetail = ref<{ [key: string]: any }>({})

const onMapClick = async ({
  _key = null,
  unitId = null,
  sectId = null,
} = {}) => {
  if (unitId) {
    if (_key === 'elevator') {
      elevatorDetail.value =
        (
          await ajax.get({
            url: api.ELEVATOR,
            params: {
              unitId_in: unitId,
            },
          })
        )?.data?.content?.[0] || {}
      showElevatorDrawer.value = true
    } else if (_key === 'safety') {
      safetyDetail.value =
        (
          await ajax.get({
            url: api.RISK_BUILDINGS,
            params: {
              unitId_in: unitId,
            },
          })
        )?.data?.content?.[0] || {}
      showSafetyDrawer.value = true
    }
  } else if (sectId) {
    const data =
      (
        await ajax.get({
          url: api.GET_COMMUNITY.replace('{id}', sectId),
        })
      )?.data?.content || {}
    communityDetail.value = {
      ...(data?.cmInfo || {}),
      ...(data?.caoInfo || {}),
      ...data,
    }
    showCommunityDrawer.value = true
  }
}
const onSelectCommunity = async (data: any) => {
  const { stKind } = data
  let icon = c6
  if (stKind == '01') {
    icon = c1
  } else if (stKind == '07' || stKind == '05') {
    icon = c2
  } else if (stKind == '11') {
    icon = c3
  } else if (stKind == '06') {
    icon = c4
  } else if (stKind == '09') {
    icon = c5
  } else if (stKind == '04') {
    icon = c6
  }
  addPoints({ icon, data: [data], size: 40 })
  showSearchModal.value = false
  mapRef.value?.setCommunityPoints(`SECT_NAME_ = '${data.stNameFrst}'`)
  mapRef.value?.focus([data.minx || data.maxx, data.miny || data.maxy], {
    zoom: 9,
  })
}
// document.addEventListener('dblclick', (e) => {
//   console.log(e.target.attributes[0])
//   console.log('000', document.querySelector('p[data-v-3c367500]'))
//   e.target.innerText = 'test'
// })
</script>

<style lang="stylus" scoped>
@import '../components/MyComponent/main.styl'
.main
  width 100%
  height 100%
  display flex
  flex-direction column
.box
  border-radius .02rem
  background transparent
  $blur(0)
  position relative
  overflow hidden
.list-content
  max-height 60vh
  overflow-y auto
  >.item
    font-size .12rem
    font-weight bold
    display flex
    align-items center
    padding .05rem
    &:nth-of-type(2n+1)
      background rgba(0,0,0,.5)
    &:hover
      background rgba(255,255,255,.2)
    >p
      flex 1
      overflow hidden
      white-space nowrap
      text-overflow ellipsis
      &:nth-of-type(2)
        flex 2
        margin 0 .1rem
</style>
