<template>
  <n-drawer
    to="#main"
    :show="show"
    :on-update:show="close"
    width="2.8rem"
    :mask-closable="false"
  >
    <n-drawer-content title="筛选" closable>
      <div class="content">
        <div class="tabs">
          <div :class="{ on: curTab === 'tag' }" @click="curTab = 'tag'">
            标签筛选
          </div>
          <div :class="{ on: curTab === 'geo' }" @click="curTab = 'geo'">
            地理筛选
          </div>
        </div>
        <n-collapse
          v-show="curTab === 'tag'"
          id="tag-filter"
          :default-expanded-names="['1', '2']"
        >
          <template #arrow>
            <n-icon size=".1rem">
              <CaretForward />
            </n-icon>
          </template>
          <n-collapse-item title="党组织" name="1">
            <div class="list">
              <div
                v-for="item in organization"
                :key="item.name"
                :title="item.name"
              >
                <n-checkbox v-model:checked="item.checked" size="small">{{
                  item.name
                }}</n-checkbox>
                <div
                  v-show="item.checked"
                  class="export"
                  @click.prevent="handleExport('organization', item.name)"
                >
                  导出详表
                  <n-icon size=".1rem">
                    <svg-icon :data="exportIcon" original />
                  </n-icon>
                </div>
              </div>
            </div>
          </n-collapse-item>
          <n-collapse-item title="党员" name="2">
            <div class="list">
              <div v-for="item in member" :key="item.name" :title="item.name">
                <n-checkbox v-model:checked="item.checked" size="small">{{
                  item.name
                }}</n-checkbox>
                <div
                  v-show="item.checked"
                  class="export"
                  @click.prevent="handleExport('member', item.name)"
                >
                  导出详表
                  <n-icon size=".1rem">
                    <svg-icon :data="exportIcon" original />
                  </n-icon>
                </div>
              </div>
            </div>
          </n-collapse-item>
        </n-collapse>
        <div v-show="curTab === 'geo'" id="geo-filter">
          <p class="nav">
            <span v-if="curPath.length > 1" class="pre" @click="toPreStep">
              <n-icon size=".08rem">
                <ArrowBack />
              </n-icon>
              上一页 |
            </span>
            <template v-if="curPath.length > 0">
              <span v-for="(n, i) in curPath" :key="n">
                <span v-if="i !== 0">/</span>
                <b v-if="i === curPath.length - 1">{{ n }}</b>
                <template v-else>{{ n }}</template>
              </span>
            </template>
            <b v-else>社区</b>
          </p>
          <n-tabs v-model:value="curGeo" type="line" size="small">
            <n-tab-pane name="社区" tab="社区" class="geo-list">
              <div
                v-for="(item, i) in list1"
                :key="i"
                :class="{ on: curArea === item }"
                @click="setArea(item)"
              >
                <p>
                  <n-icon class="dot" size=".08rem">
                    <svg-icon :data="dot" />
                  </n-icon>
                  {{ item }}
                </p>
                <span class="next" @click="areaNext(item)">
                  下一级
                  <n-icon class="icon" size=".1rem" color="#dd505E">
                    <ArrowForward />
                  </n-icon>
                </span>
              </div>
            </n-tab-pane>
            <n-tab-pane name="居委" tab="居委" class="geo-list">
              <div
                v-for="(item, i) in list2"
                :key="i"
                :class="{ on: curCommittee === item }"
                @click="setCommittee(item)"
              >
                <p>
                  <n-icon class="dot" size=".08rem">
                    <svg-icon :data="dot" />
                  </n-icon>
                  {{ item }}
                </p>
                <span class="next" @click="committeeNext(item)">
                  下一级
                  <n-icon class="icon" size=".1rem" color="#dd505E">
                    <ArrowForward />
                  </n-icon>
                </span>
              </div>
            </n-tab-pane>
            <n-tab-pane name="小区" tab="小区" class="geo-list">
              <div
                v-for="(item, i) in list3"
                :key="i"
                :class="{ on: curCommunity === item }"
                @click="setCommunity(item)"
              >
                <p>
                  <n-icon class="dot" size=".08rem">
                    <svg-icon :data="dot" />
                  </n-icon>
                  {{ item }}
                </p>
                <span class="next" @click="communityNext(item)">
                  下一级
                  <n-icon class="icon" size=".1rem" color="#dd505E">
                    <ArrowForward />
                  </n-icon>
                </span>
              </div>
            </n-tab-pane>
          </n-tabs>
        </div>
      </div>
    </n-drawer-content>
  </n-drawer>
</template>

<script lang="ts" setup>
import store from '@/store'
import { computed, onMounted, ref, watch } from 'vue'
import { useFetchOrg, useFetchMember } from '@/hooks/useFetch'
import useExportFile from '@/hooks/useExportFile'
import { CaretForward, ArrowBack, ArrowForward } from '@vicons/ionicons5'
import exportIcon from '@images/export.svg'
import dot from '@images/dot.svg'

const show = computed(() => store.state.showFilterDrawer)
const close = () => store.commit('SET_FILTER_DRAWER', false)

const curTab = ref('tag')

const organization = ref<{ name: string; checked: boolean }[]>([])
const getOrgTags = async () => {
  const res = (
    await useFetchOrg({
      a: 'id,count',
      keys: '标签',
    })
  )?.filter((e: any) => !!e['标签'])
  organization.value = res.map((item: any) => ({
    name: item['标签'],
    checked: false,
  }))
}

const member = ref<{ name: string; checked: boolean }[]>([])
const getMemberTags = async () => {
  const res = (
    await useFetchMember({
      a: 'id,count',
      keys: '标签',
    })
  )?.filter((e: any) => !!e['标签'])
  const tags: string[] = []
  res.forEach((item: any) => {
    tags.push(...item['标签'])
  })
  member.value = Array.from(new Set(tags)).map((tag: string) => ({
    name: tag,
    checked: false,
  }))
}

const list1 = [
  '牡丹社区',
  'XX社区1',
  'XX社区2',
  'XX社区3',
  'XX社区4',
  'XX社区5',
]
const list2 = [
  '某某居委1',
  '某某居委2',
  '某某居委3',
  '某某居委4',
  '某某居委5',
  '某某居委6',
]
const list3 = [
  '某某小区1',
  '某某小区2',
  '某某小区3',
  '某某小区4',
  '某某小区5',
  '某某小区6',
]

onMounted(() => {
  getOrgTags()
  getMemberTags()
})

const getDetail = async (type: string, name: string) => {
  let res = null
  switch (type) {
    case 'organization':
      res = await useFetchOrg({
        q: `paths @ "标签" && string == "${name}"`,
      })
      break
    case 'member':
      res = await useFetchMember({
        q: `paths @ "标签" && string == "${name}"`,
      })
      break
    default:
      break
  }
  return res
}

const handleExport = async (type: string, name: string) => {
  const res = await getDetail(type, name)
  const data = res.map((item: any) => item.extra)
  useExportFile(data, type === 'organization' ? '党组织名称' : '姓名', name)
}

watch(
  () => organization.value,
  async (data) => {
    const names = data.filter((e) => e.checked).map((e) => e.name)
    const pointData: any[] = []
    const result = await Promise.all(
      names.map((name) => getDetail('organization', name)),
    )
    result.forEach((item: any[]) => pointData.push(...item))
    console.log('organization撒点数据：', pointData)
    // TODO 撒点
  },
  { deep: true },
)
watch(
  () => member.value,
  async (data) => {
    const names = data.filter((e) => e.checked).map((e) => e.name)
    const pointData: any[] = []
    const result = await Promise.all(
      names.map((name) => getDetail('member', name)),
    )
    result.forEach((item: any[]) => pointData.push(...item))
    console.log('member撒点数据：', pointData)
    // TODO 撒点
  },
  { deep: true },
)

const curGeo = ref('社区')
const curArea = ref<string | null>(null)
const curCommittee = ref<string | null>(null)
const curCommunity = ref<string | null>(null)
const setArea = (name: string) => {
  curArea.value = name
  console.log(name, curArea.value)
}
const setCommittee = (name: string) => (curCommittee.value = name)
const setCommunity = (name: string) => (curCommunity.value = name)
const areaNext = (name: string) => {
  setArea(name)
  curGeo.value = '居委'
}
const committeeNext = (name: string) => {
  setCommittee(name)
  curGeo.value = '小区'
}
const communityNext = (name: string) => {
  setCommunity(name)
  store.commit('SET_BUILDING_DRAWER', true)
}
const toPreStep = () => {
  if (curGeo.value === '小区') {
    curCommunity.value = null
    curGeo.value = '居委'
    return
  }
  if (curGeo.value === '居委') {
    curCommittee.value = null
    curGeo.value = '社区'
    return
  }
}
const curPath = computed(() => {
  let result = ''
  curArea.value && (result += curArea.value)
  curArea.value &&
    (result +=
      curGeo.value === '社区' ? '' : `/${curCommittee.value || '居委'}`)
  curCommittee.value &&
    (result +=
      curGeo.value === '居委' ? '' : `/${curCommunity.value || '小区'}`)
  if (!result) return []
  return result.split('/')
})
</script>

<style lang="stylus" scoped>
@import '../../components/MyComponent/main.styl'
.content
  .tabs
    margin .05rem
    $flex-align()
    border-radius .03rem
    border .01rem solid $light-gray
    padding .02rem
    >div
      flex 1
      border-radius inherit
      color $gray
      text-align center
      cursor pointer
      &:hover
      &.on
        background $light-red
        color $red
  .list
    padding .05rem .1rem
    background #f7f7f7
    >div
      border-bottom .01rem solid $light-gray
      padding .08rem 0
      $flex-align()
      justify-content space-between
      .export
        color $red
        cursor pointer
        font-size .08rem
#geo-filter
  .nav
    padding .03rem .1rem
    color #a7afb7
    .pre
      cursor pointer
      &:hover
        color $red
    b
      color #000

  .geo-list
    background #f7f7f7
    >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
</style>
<style lang="stylus">
@import '../../components/MyComponent/main.styl'
.n-drawer-mask
  display none
.n-drawer.n-drawer--right-placement
  top .42rem
  .n-drawer-header
    font-family $font-ping-medium
  .n-drawer-body-content-wrapper
    padding 0
    overflow-x hidden !important
    overflow-y auto !important
  .n-drawer-body
    overflow-y auto
#tag-filter
  .n-collapse-item__header
    padding .05rem
    border-top .01rem solid $light-gray
  .n-collapse-item__content-inner
    padding-top 0
  .n-collapse-item
    border-top none
  .n-checkbox
    width 75%
  .n-checkbox__label
    width 90%
    font-size .09rem
    $text-overflow()
    &:hover
      color #ec7281
  .n-checkbox--checked
    .n-checkbox__label
      color $red

#geo-filter
  .n-tabs
    .n-tabs-wrapper
      padding .03rem .1rem
    .n-tabs-tab
      color #a7afb7
      font-size .1rem
      padding 0
      &:hover
      &.n-tabs-tab--active
        color $red
    .n-tab-pane
      padding .05rem .1rem
      box-sizing border-box
</style>
