<template>
  <n-drawer
    to="#main"
    :show="show"
    :on-update:show="closeDrawer"
    width="2.8rem"
    :mask-closable="false"
  >
    <n-drawer-content closable>
      <template #header>
        <div class="head">
          <n-icon class="back" size=".2rem" @click="back">
            <ArrowBack />
          </n-icon>
          楼宇
        </div>
      </template>
      <div class="content">
        <p class="name">{{ path.join('') }}</p>
        <div v-if="showBuildingDetail" class="building">
          <div class="nav">
            <p :title="curBuilding['楼宇名称']">
              {{ curBuilding['楼宇名称'] }}
            </p>
            <span @click="showBuildingDetail = false">
              返回
              <n-icon size=".09rem">
                <ArrowDown />
              </n-icon>
            </span>
          </div>
          <div v-if="floors && floors.length > 0" class="floors">
            <div v-for="(item, i) in floors" :key="i">
              <div class="title">
                <p>{{ item.floor }}</p>
                <div>
                  <span>户数：{{ item.room }} </span>
                  <span>党员数：{{ item.member }}</span>
                </div>
              </div>
              <n-carousel :show-arrow="item.length > 4">
                <div
                  v-for="(_, segmentIndex) in new Array(
                    Math.ceil(item.rooms.length / 4),
                  )"
                  :key="segmentIndex"
                  class="rooms"
                >
                  <div
                    v-for="(room, index) in item.rooms.slice(
                      segmentIndex * 4,
                      segmentIndex + 4,
                    )"
                    :key="index"
                    class="room"
                  >
                    <div class="members">
                      <n-popover
                        v-for="(m, n) in room.members"
                        :key="n"
                        class="member-info-popover"
                        placement="left"
                        flip
                        trigger="click"
                      >
                        <template #trigger>
                          <n-icon class="icon" size=".1rem">
                            <svg-icon :data="member" original />
                          </n-icon>
                        </template>
                        <MemberInfo :data="m" />
                      </n-popover>
                    </div>
                    <p>{{ room['房间号'] }}</p>
                  </div>
                </div>
              </n-carousel>
            </div>
          </div>
          <n-empty v-else style="margin-top: 0.2rem" size="small" />
        </div>
        <div v-else class="list">
          <div
            v-for="(item, i) in list"
            :key="i"
            :class="{
              on: (curBuilding && curBuilding['楼宇名称']) === item['楼宇名称'],
            }"
            @click="setBuilding(item)"
          >
            <p :title="item['楼宇名称']">
              <n-icon class="dot" size=".08rem">
                <svg-icon :data="dot" />
              </n-icon>
              {{ item['楼宇名称'] }}
            </p>
            <span class="next" @click.prevent.stop="buildingNext(item)">
              下一级
              <n-icon class="icon" size=".1rem" color="#dd505E">
                <ArrowForward />
              </n-icon>
            </span>
          </div>
        </div>
      </div>
    </n-drawer-content>
  </n-drawer>
</template>

<script lang="ts" setup>
import { computed, onMounted, PropType, ref, watch } from 'vue'
import store from '@/store'
import dot from '@images/dot.svg'
import { ArrowForward, ArrowBack, ArrowDown } from '@vicons/ionicons5'
import member from '@images/member.svg'
import { useFetchRoom, useFetchMember } from '@/hooks/useFetch'
import MemberInfo from './member-info.vue'

const props = defineProps({
  list: {
    type: Array as PropType<any[]>,
    default: () => [],
  },
  path: {
    type: Array as PropType<any[]>,
    default: () => [],
  },
  resetInfo: {
    type: Function as PropType<() => any>,
    default: null,
  },
  close: {
    type: Function as PropType<() => any>,
    default: null,
  },
})
const emit = defineEmits(['building'])

const show = computed(() => store.state.showBuildingDrawer)
const curBuilding = ref<any>(null)
const showBuildingDetail = ref(false)

const back = () => {
  props.resetInfo && props.resetInfo()
  showBuildingDetail.value = false
  curBuilding.value = null
  store.commit('SET_BUILDING_DRAWER', false)
  store.commit('SET_SHOW_TAG', true)
}
const closeDrawer = () => {
  back()
  props.close && props.close()
  // TODO 清除撒点
}

const setBuilding = (building: any, causedByNext?: boolean) => {
  let query = store.state.filterPath
  const buildingQuery = `paths @ "所属楼宇" && string @ "${building['号']}"`
  if (
    (curBuilding.value && curBuilding.value['楼宇名称']) ===
      (building && building['楼宇名称']) &&
    !causedByNext
  ) {
    curBuilding.value = null
    query = query.replace(',' + buildingQuery, '')
  } else {
    if (query.includes('所属楼宇')) {
      const arr = query.split(',')
      const index = arr.findIndex((e) => e.includes('所属楼宇'))
      arr.splice(index, 1, buildingQuery)
      query = arr.join(',')
    } else {
      query += ',' + buildingQuery
    }
    curBuilding.value = building
  }
  store.dispatch('getBasicInfo', query)
  emit('building', curBuilding.value?.OBJECTID || null)
}
const floors = ref<any[]>([])

const getMembers = async (data: any) => {
  return Promise.all(
    (
      await useFetchMember({
        q: `paths @ "所属小区" && string == "${data['所属小区']}", paths @ "所属楼宇"  && string @ "${data['所属楼宇']}",paths @ "所属房间" && string == ${data['房间号']}`,
      })
    ).map((item: any) => item.extra),
  )
}

const getRooms = async (query: string) => {
  return Promise.all(
    (
      await useFetchRoom({
        q: query,
      })
    ).map(async (item: any) => {
      return {
        ...item.extra,
        members: await getMembers(item.extra),
      }
    }),
  )
}
const getFloors = async (data: any) => {
  return Promise.all(
    (
      await useFetchRoom({
        a: 'id,count',
        keys: '层数',
        q: `paths @ "所属小区" && string == "${
          props.path[props.path.length - 1]
        }", paths @ "所属楼宇"  string @ "${data['号']}"`,
      })
    ).map(async (item: any) => {
      const rooms = await getRooms(
        `paths @ "所属小区" && string == "${
          props.path[props.path.length - 1]
        }", paths @ "所属楼宇"  && string @ "${
          data['号']
        }",paths @ "层数" && number == ${item['层数']}`,
      )
      let memberAmount = 0
      rooms.forEach((room: any) => (memberAmount += room.members.length))
      return {
        floor: `${item['层数']}F`,
        room: rooms.length || 0,
        member: memberAmount,
        rooms,
      }
    }),
  )
}

const buildingNext = async (building: any) => {
  showBuildingDetail.value = false
  floors.value = await getFloors(building)
  setBuilding(building, true)
  showBuildingDetail.value = true
}
watch(
  () => store.state.buildingDetailByNext,
  (building) => {
    if (!building) return
    buildingNext(building)
  },
  { deep: true },
)
</script>

<style lang="stylus" scoped>
@import '../../components/MyComponent/main.styl'
.head
  $flex-align()
  .back
    cursor pointer
    margin-right .05rem
    border-radius .03rem
    &:hover
      color $red
      background $light-red
.content
  display flex
  flex-direction column
  height 100%
.name
  margin .1rem
.list
  border-top .01rem solid $light-gray
  padding 0 .1rem
  background #f7f7f7
  box-sizing border-box
  flex 1
  overflow-y auto
  >div
    $flex-align()
    justify-content space-between
    border-bottom .01rem solid $light-gray
    padding .06rem 0
    color $font
    cursor pointer
    >p
      flex 1
      $text-overflow()
    &.on
    &:hover
      color $red
      .dot
        color $red
    .dot
      margin 0 .08rem
    .next
      color $red
      cursor pointer
      font-size .09rem
      &:hover
        font-family $font-ping-medium
.building
  display flex
  flex-direction column
  flex 1
  overflow-y auto
  overflow-x hidden
  .nav
    $flex-align()
    justify-content space-between
    padding .08rem
    background #f7f7f7
    box-shadow  0 0.02rem .05rem rgba(0,0,0,0.1)
    p
      font-family $font-ping-medium
      flex 1
      $text-overflow()
    span
      color $red
      font-size .09rem
      cursor pointer
      width .3rem
      white-space nowrap
  .floors
    padding .08rem
    background $light-gray
    flex 1
    overflow-y auto
    >div
      background $white-bg
      border-radius .04rem
      padding .08rem 0
      margin-bottom .08rem
      box-shadow  0 0.02rem .05rem rgba(0,0,0,0.1)
      .title
        $flex-align()
        justify-content space-between
        margin-bottom .05rem
        padding 0 .1rem
        font-family $font-ping-medium
        p
          color $red
        span
          color $font
          font-size .08rem
          margin-left .1rem
      .rooms
        overflow hidden
        white-space nowrap
        padding 0 .1rem
        .room
          width 23%
          border-radius .04rem
          border .01rem solid $light-gray
          display inline-block
          margin-right 1.6%
          .members
            display flex
            flex-wrap wrap
            background $light-red
            height .4rem
            box-sizing border-box
            overflow hidden
            .icon
              padding .04rem
              cursor pointer
              &:hover
              &.on
                color $pink
          p
            text-align center
</style>
<style lang="stylus">
@import '../../components/MyComponent/main.styl'
.floors
  .n-carousel
    .n-carousel__arrow
      width .16rem
      height @width
      color $red
      &.n-carousel__arrow--left
        left -0.01rem
      &.n-carousel__arrow--right
        right -0.01rem
    .n-carousel__dots
      display none
.member-info-popover
  // width 2.8rem
  // min-height 3rem
  // max-height 4rem
  // overflow hidden
  background rgba(249, 250, 250, 0.9) !important
  $blur()
</style>
