<template>
  <n-modal
    :show="show"
    :mask-closable="false"
    style="width: 98vw; transform: translateY(4%)"
  >
    <div id="struct-modal">
      <n-layout class="layout" has-sider>
        <n-layout-sider width="25%" class="side-menu">
          <h2
            :class="{ on: curKey === 'default' }"
            @click.prevent="
              () => {
                setCurKey('default', {
                  key: 'default',
                  label: '中共上海市浦东新区花木街道工作委员会',
                })
                handleExpand([])
              }
            "
          >
            中共浦东新区花木街道工作委员会
          </h2>
          <div class="menu">
            <n-menu
              :options="menus"
              :expanded-keys="expandedKeys"
              :on-update:expanded-keys="handleExpand"
              :value="curKey"
              :on-update:value="setCurKey"
            />
          </div>
        </n-layout-sider>
        <n-layout has-sider>
          <n-layout-sider
            width="25%"
            :collapsed="!showSubordinates"
            :collapsed-width="0"
            collapsed-mode="width"
            class="sub"
          >
            <!-- <p
              v-for="item in subList"
              :key="item.key"
              :class="{ on: subKey === item.key }"
              :title="item.label"
              @click.prevent="setSub(item)"
            >
              {{ item.label }}
            </p> -->
            <n-menu
              :on-update:value="toSetSub"
              class="sub-menu"
              :value="subKey"
              :options="subList"
              :expanded-keys="subExpandedKeys"
              :on-update:expanded-keys="onSubExpand"
            />
          </n-layout-sider>
          <n-layout class="wrapper">
            <n-layout-header class="head">
              <n-space>
                <p>{{ curMenu.label }}</p>
                <template v-if="curMenu?.['标签']">
                  <n-tag
                    v-for="tag in curMenu['标签'].split(',')"
                    :key="tag"
                    :type="organization.find((e) => e.name === tag)?.type"
                    size="small"
                  >
                    {{ tag }}
                  </n-tag>
                </template>
              </n-space>
              <n-icon class="close-btn" size=".2rem" @click.prevent="close">
                <CloseOutline />
              </n-icon>
            </n-layout-header>
            <n-layout-content class="content">
              <div v-if="curKey === 'default'" class="card">
                <div class="row">
                  <span>党工委书记</span>
                  <p>{{ defaultData['书记'] }}</p>
                </div>
                <div class="row">
                  <span>党工委副书记</span>
                  <p>{{ defaultData['副书记'] }}</p>
                </div>
                <div class="row">
                  <span>党组织地址</span>
                  <p>{{ defaultData['党组织地址'] }}</p>
                </div>
                <div class="row">
                  <span>党员数量</span>
                  <p>{{ store.state.basicInfo.sum[1].value }} 位</p>
                </div>
              </div>
              <div v-else-if="curKey === '1'" class="card">
                <div class="row">
                  <span>书记</span>
                  <p>{{ administration['书记'] }}</p>
                </div>
                <div class="row">
                  <span>成员（按姓氏笔画排序）</span>
                  <p>
                    {{ administration['委员'] }}
                  </p>
                </div>
                <div class="row">
                  <span>党组织地址</span>
                  <p>{{ administration['党组织地址'] }}</p>
                </div>
              </div>
              <div v-else-if="curKey === '2'" class="card">
                <div class="flex">
                  <div class="col">
                    <div class="row">
                      <span>党总支书记</span>
                      <p>{{ institution['书记'] }}</p>
                    </div>
                    <div class="row">
                      <span>党组织地址</span>
                      <p>{{ institution['党组织地址'] }}</p>
                    </div>
                    <div class="row">
                      <span>党员数量</span>
                      <p>{{ institution['党员数量'] }} 位</p>
                    </div>
                  </div>
                  <div class="col">
                    <div class="row">
                      <span>党总支委员</span>
                      <p>{{ institution['委员'] || '无' }}</p>
                    </div>
                    <div class="row">
                      <span>党组织联系方式</span>
                      <p>
                        {{
                          institution['联系方式_座机'] ||
                          institution['联系方式_手机'] ||
                          '无'
                        }}
                      </p>
                    </div>
                  </div>
                </div>
              </div>
              <div v-else-if="curKey === '3'" class="card">
                <div class="flex">
                  <div class="col">
                    <div class="row">
                      <span>党委书记</span>
                      <p>{{ communityParty['书记'] }}</p>
                    </div>
                    <div class="row">
                      <span>党委副书记</span>
                      <p>{{ communityParty['党委副书记-专职'] }}</p>
                    </div>
                    <div class="row">
                      <span>党组织联系方式</span>
                      <p>
                        {{
                          communityParty['联系方式_座机'] ||
                          communityParty['联系方式_手机'] ||
                          '无'
                        }}
                      </p>
                    </div>
                    <div class="row">
                      <span>党员数量</span>
                      <p>{{ communityParty['党员数量'] }} 位</p>
                    </div>
                  </div>
                  <div class="col">
                    <div class="row">
                      <span>党委成员</span>
                      <p>
                        {{ communityParty['委员'] }}
                      </p>
                    </div>
                    <div class="row">
                      <span>党委副书记（兼职）</span>
                      <p>{{ communityParty['党委副书记-兼职'] }}</p>
                    </div>
                    <div class="row">
                      <span>党组织地址</span>
                      <p>{{ communityParty['党组织地址'] }}</p>
                    </div>
                  </div>
                </div>
              </div>
              <div
                v-else-if="
                  curKey.split('-').length === 3 && curMenu && curMenu._hasSub
                "
                class="card"
              >
                <div class="flex">
                  <div class="col">
                    <div class="row">
                      <span>党委书记</span>
                      <p>{{ curSubMenu['书记'] }}</p>
                    </div>
                    <div class="row">
                      <span>党组织地址</span>
                      <p>{{ curSubMenu['党组织地址'] }}</p>
                    </div>
                    <div class="row">
                      <span>党员数量</span>
                      <p>
                        {{
                          curSubMenu['党员数量']
                            ? curSubMenu['党员数量'] + ' 位'
                            : '无'
                        }}
                      </p>
                    </div>
                  </div>
                  <div class="col">
                    <div class="row">
                      <span>党委成员</span>
                      <p>{{ curSubMenu['委员'] }}</p>
                    </div>
                    <div class="row">
                      <span>党组织联系方式</span>
                      <p>
                        {{
                          curSubMenu['联系方式_座机'] ||
                          curSubMenu['联系方式_手机'] ||
                          '无'
                        }}
                      </p>
                    </div>
                  </div>
                </div>
              </div>
              <template
                v-else-if="
                  ((curKey.startsWith('2') || curKey.startsWith('3')) &&
                    curKey.split('-').length === 2) ||
                  (curKey.split('-').length === 3 &&
                    (!curMenu || !curMenu._hasSub))
                "
              >
                <div class="card">
                  <div class="flex">
                    <div class="col">
                      <div class="row">
                        <span>{{
                          curMenu['等级'] === '党总支'
                            ? '党总支书记'
                            : '党支部书记'
                        }}</span>
                        <p>{{ curMenu['书记'] }}</p>
                      </div>
                      <div class="row">
                        <span>党组织地址</span>
                        <p>{{ curMenu['党组织地址'] }}</p>
                      </div>
                      <div class="row">
                        <span>党员数量</span>
                        <p>
                          {{
                            curMenu['党员数量']
                              ? curMenu['党员数量'] + ' 位'
                              : '无'
                          }}
                        </p>
                      </div>
                    </div>
                    <div class="col">
                      <div class="row">
                        <span>{{
                          curMenu['等级'] === '党总支'
                            ? '党总支委员'
                            : '支委会成员'
                        }}</span>
                        <p>{{ curMenu['委员'] || '无' }}</p>
                      </div>
                      <div class="row">
                        <span>党组织联系方式</span>
                        <p>
                          {{
                            curMenu['联系方式_座机'] ||
                            curMenu['联系方式_手机'] ||
                            '无'
                          }}
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
                <div v-if="curMenu['等级'].includes('党支部')" class="card">
                  <div class="title">
                    <p>党员详表</p>
                    <n-button type="primary" size="tiny" @click="exportList">
                      <template #icon>
                        <n-icon size=".1rem">
                          <svg-icon :data="exportIcon" original />
                        </n-icon>
                      </template>
                      导出
                    </n-button>
                  </div>
                  <n-data-table
                    class="activity-table"
                    :columns="columns"
                    :data="tableList"
                    :pagination="pagination"
                    size="small"
                  />
                </div>
              </template>
            </n-layout-content>
          </n-layout>
        </n-layout>
      </n-layout>
    </div>
  </n-modal>
</template>

<script lang="ts" setup>
import store from '@/store'
import { computed, h, onMounted, ref, watch } from 'vue'
import PartyIcon from './party-icon.vue'
import exportIcon from '@images/export.svg'
import { CloseOutline } from '@vicons/ionicons5'
import { useFetchOrg, useFetchMember } from '@/hooks/useFetch'
import { organization } from '@/util/tags'
import useExportFile from '@/hooks/useExportFile'

const show = computed(() => store.state.showStructModal)
const close = () => {
  store.commit('SET_STRUCT_MODAL', false)
  store.commit('SET_SHOW_BASIC_INFO', true)
  store.commit('SET_SHOW_TAG', true)
  clear()
}
function clear() {
  subKey.value = null
  curSubMenu.value = {}
  expandedKeys.value = []
  subExpandedKeys.value = []
  curMenu.value = { label: '中共浦东新区花木街道工作委员会', key: 'default' }
  curKey.value = 'default'
}

function renderIcon() {
  return () => h(PartyIcon)
}
const defaultData = ref<any>({}) // 中共上海市浦东新区花木街道工作委员会
const administration = ref<any>({}) // 行政党组
const institution = ref<any>({}) // 机关事业单位党总支
const communityParty = ref<any>({}) // 社区党委
const belongToInstitution = ref<any[]>([])
const belongToCommunityParty = ref<any[]>([])

onMounted(async () => {
  defaultData.value = (
    await useFetchOrg({
      q: 'paths @ "党组织名称" && string == "中共上海市浦东新区花木街道工作委员会"',
    })
  )?.[0]?.extra
  administration.value = (
    await useFetchOrg({
      q: 'paths @ "党组织名称" && string == "行政党组"',
    })
  )?.[0]?.extra
  institution.value = (
    await useFetchOrg({
      q: 'paths @ "党组织名称" && string == "中共花木街道机关事业单位总支部委员会"',
    })
  )?.[0]?.extra
  communityParty.value = (
    await useFetchOrg({
      q: 'paths @ "党组织名称" && string == "社区党委"',
    })
  )?.[0]?.extra

  belongToInstitution.value = (
    await useFetchOrg({
      q: 'paths @ "上级党组织名称" && string == "中共花木街道机关事业单位总支部委员会"',
    })
  )?.map((item: any, i: number) => {
    const data = item.extra
    return {
      ...data,
      label: data['党组织名称'].replace('中共浦东新区花木街道', ''),
      key: '2-' + (i + 1),
    }
  })
  belongToCommunityParty.value = (
    await useFetchOrg({
      q: 'paths @ "上级党组织名称" && string == "社区党委"',
    })
  )?.map((item: any, i: number) => {
    const data = item.extra
    return {
      ...data,
      label: data['党组织名称'].replace('中共花木街道', '').replace('中共', ''),
      key: '3-' + (i + 1),
    }
  })
  const data = belongToCommunityParty.value
  const bigSixChildren: any[] = []
  const twoNewChildren: any[] = []
  const datasource = data.filter((item: any) => item['是否虚拟组织']) || []
  data.forEach((item: any) => {
    if (item['是否虚拟组织']) return
    if (item['类别'] === '居民区') {
      bigSixChildren.push(item)
    } else if (item['类别'] === '两新') {
      twoNewChildren.push(item)
    } else {
      datasource.push(item)
    }
  })
  const bigSix = datasource.find((e: any) =>
    e['党组织名称']?.includes('六大社区党委'),
  )
  const twoNew = datasource.find((e: any) => e['党组织名称']?.includes('两新'))

  bigSix.children = await Promise.all(
    bigSixChildren.map(async (e: any, i: number) => {
      const children = await checkHasChildren(e)
      const result = {
        ...e,
        label: e['党组织名称'].replace('中共花木街道', '').replace('中共', ''),
        key: bigSix.key + '-' + (i + 1),
      }
      if (children && children.length > 0) {
        result._hasSub = true
        result.subList = children.map((child: any, index: number) => ({
          ...child,
          label: child['党组织名称']
            .replace('浦东新区花木街道', '')
            .replace('中共', ''),
          key: result.key + '-' + (index + 1),
        }))
      }
      return result
    }),
  )
  twoNew.children = await Promise.all(
    twoNewChildren.map(async (e: any, i: number) => {
      const children = await checkHasChildren(e)
      const result = {
        ...e,
        label: e['党组织名称'].replace('中共花木街道', '').replace('中共', ''),
        key: twoNew.key + '-' + (i + 1),
      }
      if (children && children.length > 0) {
        result._hasSub = true
        result.subList = children.map((child: any, index: number) => ({
          ...child,
          label: child['党组织名称']
            .replace('浦东新区花木街道', '')
            .replace('中共', ''),
          key: result.key + '-' + (index + 1),
        }))
      }
      return result
    }),
  )
  belongToCommunityParty.value = datasource
})

async function checkHasChildren(data: any) {
  return (
    await useFetchOrg({
      q: `paths @ "上级党组织名称" && string == "${data['党组织名称']}"`,
    })
  )?.map((e: any) => e.extra)
}

const menus = computed(() => [
  { label: '行政党组', key: '1', icon: renderIcon() },
  {
    label: '机关事业单位党总支',
    key: '2',
    icon: renderIcon(),
    children: belongToInstitution.value,
  },
  {
    label: '社区党委',
    key: '3',
    icon: renderIcon(),
    children: belongToCommunityParty.value,
  },
])

const subList = ref<any[]>([])

const expandedKeys = ref<string[]>([])
const handleExpand = (val: string[]) => {
  if (expandedKeys.value.length === 0 || val.length === 0) {
    expandedKeys.value = val
  } else if (val[val.length - 1].startsWith(expandedKeys.value[0])) {
    expandedKeys.value = val
  } else {
    expandedKeys.value = [val[val.length - 1]]
  }
  if (expandedKeys.value.length === 1 && expandedKeys.value[0].includes('-')) {
    expandedKeys.value = []
    subExpandedKeys.value = []
    subKey.value = null
    curMenu.value = { label: '中共浦东新区花木街道工作委员会', key: 'default' }
    curKey.value = 'default'
    return
  }
  if (expandedKeys.value.length === 0) return
  curKey.value = expandedKeys.value[0]
  const cur = menus.value.find((e) => e.key === curKey.value)
  subKey.value = null
  if (cur) {
    curMenu.value = cur
    subExpandedKeys.value = []
    subKey.value = null
  }
}

const curKey = ref<string | null>('default')
const subKey = ref<string | null>(null)
const curMenu = ref<any>({
  label: '中共浦东新区花木街道工作委员会',
  key: 'default',
})
const curSubMenu = ref<any>({})
const setCurKey = (val: string, item: any) => {
  curKey.value = val
  curMenu.value = item
  subKey.value = null
  if (val === 'default' || val === '1') handleExpand([])
}
watch(
  () => curMenu.value,
  async (data) => {
    if (!data) return
    if (data && data._hasSub) {
      if (data.subList && data.subList.length > 0) {
        await Promise.all(
          data.subList.map(async (item: any) => {
            const children =
              (
                await useFetchOrg({
                  q: `paths @ "上级党组织名称" && string @ "${item['党组织名称']}"`,
                })
              )?.map((e: any, i: number) => ({
                ...e.extra,
                key: item.key + '-' + (i + 1),
                label: e.extra['党组织名称']
                  .replace('浦东新区花木街道', '')
                  .replace('中共', ''),
              })) || []
            if (children && children.length > 0) {
              item.children = children
            }
          }),
        )
        subList.value = data.subList
      } else {
        subList.value = []
      }
      curSubMenu.value = data
    }
    tableList.value =
      (
        await useFetchMember({
          q: `paths @ "所属党组织名称" && string == "${data['党组织名称']}"`,
        })
      )?.map((item: any) => item.extra) || []
  },
)

const showSubordinates = computed(
  () => curMenu.value?._hasSub || !!subKey.value,
)
const subExpandedKeys = ref<string[]>([])
function setSub(data: any) {
  if (!data) {
    subKey.value = null
    curMenu.value = null
    return
  }
  subKey.value = data && data.key
  curMenu.value = data
}
const toSetSub = (_: unknown, item: any) => setSub(item)
function onSubExpand(keys: string[]) {
  if (subExpandedKeys.value.length === 0 || keys.length === 0) {
    subExpandedKeys.value = keys
  } else if (keys[keys.length - 1].startsWith(subExpandedKeys.value[0])) {
    subExpandedKeys.value = keys
  } else {
    subExpandedKeys.value = [keys[keys.length - 1]]
  }
  if (subExpandedKeys.value.length === 0) return
  const cur = subList.value.find((e) => e.key === subExpandedKeys.value[0])
  setSub(cur)
}

const columns = [
  { title: '姓名', key: '姓名' },
  { title: '性别', key: '性别' },
  { title: '民族', key: '民族' },
  { title: '所属党组织', key: '所属党组织名称' },
]
const tableList = ref<any[]>([])
const pagination = {
  pageSize: 10,
}

const exportList = () => {
  useExportFile(tableList.value, '姓名', `${curMenu.value.label}党员详表`)
}
</script>

<style lang="stylus" scoped>
@import '../../components/MyComponent/main.styl'
#struct-modal
  position relative
  font-size .1rem
  height 90vh
  border-radius .05rem
  .layout
    background inherit
    border-radius inherit
    width 100%
    height 100%
  .side-menu
    z-index 5
    height 100%
    box-shadow .01rem 0 .03rem rgba(0,0,0,0.3)
    h2
      border-radius .05rem
      padding .08rem
      margin .16rem .16rem 0
      font-size .14rem
      color $red
      cursor pointer
      &:hover
      &.on
        background $light-red
  .head
    $flex-align()
    justify-content space-between
    padding 0 .2rem
    box-shadow 0 .01rem .03rem rgba(0,0,0,0.3)
    z-index 1
    height .5rem
    box-sizing border-box
    p
      font-size .14rem
      font-family $font-ping-medium
      margin-right .2rem
    .close-btn
      color $font
      cursor pointer
  .content
    background #ededed
    flex 1
    box-sizing border-box
    padding .12rem
    .card
      box-sizing inherit
      padding .08rem .16rem
      border-radius .05rem
      background #fafafa
      margin-bottom .1rem
      .title
        $flex-align()
        justify-content space-between
        margin-bottom .1rem
        p
          font-family $font-ping-medium
          font-size .12rem
      .flex
        display flex
      .col
        flex 1
      .row
        margin-bottom .1rem
        padding-left .05rem
        p
          font-family $font-ping-medium
        span
          color $font
  .sub
    width 100%
    height 100%
    background #f7f7f7
    box-shadow .01rem 0 .03rem rgba(0,0,0,0.3)
    z-index 3
    box-sizing border-box
    padding .1rem 0
    // p
    //   padding .1rem
    //   font-size .09rem
    //   color $font
    //   cursor pointer
    //   $text-overflow()
    //   &:hover
    //   &.on
    //     color $red
</style>
<style lang="stylus">
@import '../../components/MyComponent/main.styl'
#struct-modal
  .side-menu
    display flex
    flex-direction column
    .menu
      flex 1
      overflow-y auto
  .n-menu
    .n-menu-item-content-header
      z-index 1
    >.n-submenu
      >.n-submenu-children
        .n-menu-item-content-header
          font-size .11rem
        .n-submenu-children
          .n-menu-item-content-header
            font-size .09rem
    &.sub-menu
      .n-menu-item-content
        padding .1rem .2rem !important
        .n-menu-item-content-header
          font-size .09rem
      .n-submenu-children
        .n-menu-item-content
          padding-left .35rem !important
    .n-menu-item-content--child-active
      &:before
        content ""
        position absolute
        left 8px
        right 8px
        top 0
        bottom 0
        pointer-events none
        border-radius .05rem
        transition background .3s
        background $light-red
  .wrapper
    .n-layout-scroll-container
      display flex
      flex-direction column
</style>
