<template>
  <m-animate enter="fadeInLeft" leave="fadeOutLeft" :duration="300">
    <div v-if="show" class="container">
      <n-collapse
        id="basic-info"
        arrow-placement="right"
        default-expanded-names="1"
        accordion
      >
        <template #arrow>
          <n-icon size=".08rem">
            <CaretForward />
          </n-icon>
        </template>
        <n-collapse-item name="1">
          <div class="info-wrapper">
            <div class="sum">
              <div v-for="item in sumList" :key="item.name">
                <p>
                  <m-count class="count" :value="item.value" />
                  <span>{{ item.unit }}</span>
                </p>
                <p>{{ item.name }}</p>
              </div>
            </div>
            <div class="box">
              <p class="title">关系在街道党员分类</p>
              <div class="content">
                <div class="pie">
                  <m-pie :option="pieOption" :dataset="data1" />
                </div>
                <div>
                  <div v-for="(item, i) in data1.source" :key="item.name">
                    <p>
                      <i class="dot" :style="`background:${color1[i]}`" />
                      {{ item.name }}
                    </p>
                    <p>
                      <span><m-count :value="item.ratio" /> %</span>
                      <span><m-count :value="item.value" /> 位</span>
                    </p>
                  </div>
                </div>
              </div>
            </div>
            <div class="box">
              <p class="title">党组织分类</p>
              <div class="content">
                <div class="pie">
                  <m-pie
                    :option="{ ...pieOption, color: color2 }"
                    :dataset="data2"
                  />
                </div>
                <div>
                  <div v-for="(item, i) in data2.source" :key="item.name">
                    <p>
                      <i class="dot" :style="`background:${color2[i]}`" />
                      {{ item.name }}
                    </p>
                    <p>
                      <span><m-count :value="item.ratio" /> %</span>
                      <span><m-count :value="item.value" /> 个</span>
                    </p>
                  </div>
                </div>
              </div>
            </div>
            <div class="box">
              <p class="title">关系在街道党员年龄分布</p>
              <div class="content">
                <m-line :option="lineOption" :dataset="data3" />
              </div>
            </div>
          </div>
        </n-collapse-item>
      </n-collapse>
      <m-animate enter="fadeInUp" leave="fadeOutDown" :duration="200">
        <div v-if="visible" class="tag-box">
          <span
            v-for="tag in tagList"
            :key="tag.name"
            :class="{ on: tag.key === curTagKey }"
            @click="clickTag(tag.key)"
            >{{ tag.name }}</span
          >
        </div>
      </m-animate>
    </div>
  </m-animate>
</template>

<script lang="ts" setup>
import { ChartTypes } from '@/components/MyComponent'
import { ref, PropType, computed, onMounted } from 'vue'
import { CaretForward } from '@vicons/ionicons5'
import { useFetchOrg, useFetchMember } from '@/hooks/useFetch'
import store from '@/store'
import dayjs from '@/util/dayjs'

const show = computed(() => store.state.showBasicInfo)
const props = defineProps({
  visible: {
    type: Boolean as PropType<boolean>,
    default: true,
  },
})

const visible = computed(() => props.visible)

const sumList = ref([
  { name: '党组织', value: 0, unit: '个' },
  { name: '关系在街道内党员', value: 0, unit: '位' },
  { name: '街道居民党员', value: 0, unit: '位' },
])
const getSumList = async () => {
  const orgNum =
    (
      await useFetchOrg({
        a: 'id,count',
        keys: '是否虚拟组织',
      })
    )?.find((e: any) => !e['是否虚拟组织'])?.__aggregate__ || 0
  const member = await useFetchMember({
    a: 'id,count',
    keys: '是否居住在花木街道',
  })
  const inHuamu =
    member?.find((e: any) => e['是否居住在花木街道'])?.__aggregate__ || 0
  const notInHuamu =
    member?.find((e: any) => !e['是否居住在花木街道'])?.__aggregate__ || 0

  sumList.value = [
    { name: '党组织', value: orgNum, unit: '个' },
    { name: '关系在街道内党员', value: inHuamu + notInHuamu, unit: '位' },
    { name: '街道居民党员', value: inHuamu, unit: '位' },
  ]
}

const color1 = ['#FAADB8', '#C1474F', '#6D2C29']
const color2 = ['#FAADB8', '#DD505E', '#A53D40', '#6D2C29']
const pieOption: ChartTypes.PieOption = {
  color: color1,
  legend: { show: false },
  series: [
    {
      type: 'pie',
      radius: ['60%', '78%'],
      center: ['42%', '60%'],
      label: {
        show: false,
      },
      itemStyle: {
        borderWidth: 3,
        borderColor: '#fff',
      },
    },
  ],
}
const lineOption: ChartTypes.LineOption = {
  color: ['#DD505E'],
  legend: { show: false },
  yAxis: [
    {
      type: 'value',
      // minInterval: 100,
      // maxInterval: 100,
      // interval: 100,
      splitLine: {
        lineStyle: {
          type: 'dashed',
        },
      },
    },
  ],
  xAxis: [
    {
      type: 'category',
      boundaryGap: true,
      axisTick: {
        interval: 0,
      },
      axisLabel: {
        interval: 0,
        color: '#000',
      },
    },
  ],
  series: [
    {
      type: 'line',
      smooth: false,
    },
  ],
}

const data1 = ref({
  dimensions: [
    { name: 'name', displayName: '类型' },
    { name: 'value', displayName: '数量' },
  ],
  source: [],
})
const getData1 = async () => {
  const res = await useFetchMember({
    a: 'id,count',
    keys: '党员类型',
  })
  const total = res.reduce(
    (acc: number, cur: any) => acc + (cur.__aggregate__ || 0),
    0,
  )
  data1.value.source = res.map((item: any) => ({
    name: item['党员类型'],
    value: item.__aggregate__ || 0,
    ratio: Math.round(((item.__aggregate__ || 0) / total) * 100 || 0),
  }))
}

const data2 = ref({
  dimensions: [
    { name: 'name', displayName: '类型' },
    { name: 'value', displayName: '数量' },
  ],
  source: [
    { name: '党委', value: 0, ratio: 0 },
    { name: '党总支', value: 0, ratio: 0 },
    { name: '党支部', value: 0, ratio: 0 },
    { name: '联合党支部', value: 0, ratio: 0 },
  ],
})
const getData2 = async () => {
  const res = (
    await useFetchOrg({
      a: 'id,count',
      keys: '等级',
    })
  )?.filter((e: any) => data2.value.source.some((n) => n.name === e['等级']))
  const total = res.reduce(
    (acc: number, cur: any) => acc + (cur.__aggregate__ || 0),
    0,
  )
  data2.value.source.forEach((item) => {
    const value =
      res.find((e: any) => item.name === e['等级'])?.__aggregate__ || 0
    item.value = value
    item.ratio = Math.round((value / total) * 100)
  })
}

const data3 = ref({
  dimensions: [
    { name: 'name', displayName: '年龄' },
    { name: 'value', displayName: '数量' },
  ],
  source: [
    { name: '18-25岁', value: 0 },
    { name: '26-35岁', value: 0 },
    { name: '36-50岁', value: 0 },
    { name: '50-70岁', value: 0 },
    { name: '70岁以上', value: 0 },
  ],
})
const getData3 = async () => {
  const source = [
    {
      name: '18-25岁',
      range: [
        dayjs().subtract(25, 'year').format('YYYY-MM-DD'),
        dayjs().subtract(18, 'year').format('YYYY-MM-DD'),
      ],
    },
    {
      name: '26-35岁',
      range: [
        dayjs().subtract(35, 'year').format('YYYY-MM-DD'),
        dayjs().subtract(26, 'year').format('YYYY-MM-DD'),
      ],
    },
    {
      name: '36-50岁',
      range: [
        dayjs().subtract(50, 'year').format('YYYY-MM-DD'),
        dayjs().subtract(36, 'year').format('YYYY-MM-DD'),
      ],
    },
    {
      name: '50-70岁',
      range: [
        dayjs().subtract(70, 'year').format('YYYY-MM-DD'),
        dayjs().subtract(50, 'year').format('YYYY-MM-DD'),
      ],
    },
    {
      name: '70岁以上',
      range: [null, dayjs().subtract(71, 'year').format('YYYY-MM-DD')],
    },
  ]
  const res = await Promise.all(
    source.map(({ range }) =>
      useFetchMember({
        a: 'id,count',
        q: range[0]
          ? `paths @ "出生日期" && string >= "${range[0]}",paths @ "出生日期" && string <= "${range[1]}"`
          : `paths @ "出生日期" && string <= "${range[1]}"`,
      }),
    ),
  )
  data3.value.source.forEach(
    (item, i) => (item.value = res[i]?.[0].__aggregate__ || 0),
  )
}

onMounted(() => {
  getSumList()
  getData1()
  getData2()
  getData3()
})

const curTagKey = ref<string | null>(null)
const tagList = [
  { name: '机关事业单位党组织', key: '机关事业单位' },
  { name: '居民区党组织', key: '居民区' },
  { name: '“两新”党组织', key: '两新' },
]
const clickTag = async (key: string) => {
  if (key === curTagKey.value) {
    curTagKey.value = null
    // TODO 删除地图撒点
    return
  }
  curTagKey.value = key
  const res = await useFetchOrg({
    q: `paths @ "类别" && string == "${key}"`,
  })
  console.log(`类别-${key}-撒点：`, res)
  // TODO 地图撒点
}
</script>

<style lang="stylus" scoped>
@import '../../components/MyComponent/main.styl'
.container
  position fixed
  top .48rem
  left .05rem
  width 3rem
#basic-info
  width 100%
  background $bg
  border-radius .02rem
  $blur()
  .info-wrapper
    height 82vh
    box-sizing border-box
    padding .03rem .08rem
    display flex
    flex-direction column
    .sum
      display flex
      justify-content space-between
      margin-bottom .04rem
      >div
        background $white-bg
        width 32%
        border-radius .04rem
        padding .03rem .05rem
        box-sizing border-box
        font-size .09rem
        p
          &:last-child
            color $gray
        .count
          color $red
          font-size .2rem
          margin-right .05rem
    .box
      background $white-bg
      border-radius .04rem
      padding .05rem .03rem
      box-sizing border-box
      margin .04rem 0
      flex 1
      display flex
      flex-direction column
      overflow hidden
      .title
        font-family $font-ping-medium
        margin-left 6%
      .content
        flex 1
        display flex
        justify-content space-around
        overflow hidden
        >div
          &.pie
            width 1.4rem
            height 1rem
          &:last-child
            display flex
            flex-direction column
            justify-content center
          .dot
            display inline-block
            width .04rem
            height @width
            border-radius 50%
            margin-right .04rem
            margin-bottom .02rem
          span
            font-family $font-din
            margin-left .12rem
            margin-right .2rem
            &:last-child
              float right
.tag-box
  background $bg
  $blur()
  width 100%
  height .3rem
  position absolute
  left 0
  margin-top .05rem
  border-radius .02rem
  display flex
  justify-content space-between
  padding .05rem .08rem
  box-sizing border-box
  >span
    $flex-align()
    $text-overflow()
    justify-content center
    background #fff
    border-radius .03rem
    cursor pointer
    font-size .09rem
    width 32%
    &:hover
    &.on
      background $light-red
      color $red
      box-shadow 0 0 .04rem rgba(0,0,0,.5)
</style>
<style lang="stylus">
@import '../../components/MyComponent/main.styl'
#basic-info
  .n-collapse-item__header
    position relative
    display flex
    height .3rem
    border-radius .02rem
    padding 0 .12rem
    font-family $font-ping-medium
    font-size .14rem
    .n-collapse-item__header-main
      justify-content flex-end
    &:before
      position absolute
      left 0.12rem
      content '基本情况'
      height 0.14rem
      border-left 0.02rem solid #dd505e
      padding-left 0.05rem
      display flex
      align-items center
  .n-collapse-item__content-inner
    padding 0
</style>
