<template>
  <n-drawer
    to="#main"
    :show="show"
    :on-update:show="closeDrawer"
    width="2.8rem"
    :mask-closable="false"
  >
    <n-drawer-content title="党建活动" closable>
      <div class="content">
        <div class="head">
          <p>活动日期</p>
          <n-button
            color="#dd505e"
            text-color="#fff"
            size="tiny"
            @click="showModal"
          >
            活动录入
          </n-button>
        </div>
        <div class="date">
          <div class="name">
            <p>起始日期</p>
            <p>截止日期</p>
          </div>
          <div class="date-wrapper">
            <n-date-picker
              v-model:value="dateRange[0]"
              class="date-picker"
              type="date"
              clearable
              size="small"
              :is-date-disabled="disableDateStart"
            />
            <n-date-picker
              v-model:value="dateRange[1]"
              class="date-picker"
              type="date"
              clearable
              size="small"
              :is-date-disabled="disableDateEnd"
            />
          </div>
        </div>
        <div class="list">
          <div v-for="(item, i) in list" :key="i">
            <div class="title">
              <p>{{ item.title }}</p>
              <span>
                地图显示
                <n-switch v-model:value="item.onMap" size="small">
                  <template #checked>
                    <n-icon size=".1rem">
                      <Checkmark />
                    </n-icon>
                  </template>
                  <template #unchecked>
                    <n-icon size=".1rem">
                      <Close />
                    </n-icon>
                  </template>
                </n-switch>
              </span>
            </div>
            <div class="sum">
              <div>
                <m-count class="count" :value="item.count" /> <span>次</span>
                <p>累计举办次数</p>
              </div>
              <div>
                <m-count class="count" :value="item.people" /> <span>人次</span>
                <p>累计参与人次</p>
              </div>
              <!-- <div>
                <m-count class="count" :value="item.ratio" /> <span>%</span>
                <p>平均出席率</p>
              </div> -->
            </div>
          </div>
        </div>
      </div>
    </n-drawer-content>
  </n-drawer>
  <ActivityListModal />
</template>

<script lang="ts" setup>
import store from '@/store'
import { computed, ref, watch } from 'vue'
import { Checkmark, Close } from '@vicons/ionicons5'
import ActivityListModal from './activity-list-modal.vue'
import { useFetchActivity } from '@/hooks/useFetch'
import dayjs from '@/util/dayjs'

const emit = defineEmits(['close'])
const show = computed(() => store.state.showActivityDrawer)
const closeDrawer = () => {
  store.commit('SET_ACTIVITY_DRAWER', false)
  store.commit('SET_SHOW_BASIC_INFO', true)
  store.commit('SET_SHOW_TAG', true)
  emit('close')
}

watch(
  () => show.value,
  (val) => {
    if (!val) {
      dateRange.value = []
      list.value.forEach((item) => (item.onMap = false))
    }
  },
)

const dateRange = ref<number[]>([])
const list = ref([
  {
    title: '支部党员大会',
    count: 0,
    people: 0,
    ratio: 0,
    onMap: false,
    list: [{}],
  },
  {
    title: '支部委员会',
    count: 0,
    people: 0,
    ratio: 0,
    onMap: false,
    list: [{}],
  },
  {
    title: '楼宇党建相关会议',
    count: 0,
    people: 0,
    ratio: 0,
    onMap: false,
    list: [{}],
  },
  { title: '党课', count: 0, people: 0, ratio: 0, onMap: false, list: [{}] },
  {
    title: '主题党日活动',
    count: 0,
    people: 0,
    ratio: 0,
    onMap: false,
    list: [{}],
  },
])

watch(
  () => store.state.auth.code,
  (code) => {
    if (!code) return
    getList()
  },
  { immediate: true },
)

async function getList(query?: string) {
  const result = [...list.value]
  result.forEach(async (item) => {
    let q = `paths @ "标签类别" && string == "${item.title}",paths @ "党组织编号" && string @ "${store.state.auth.code}"`
    query && (q += `,${query}`)
    const data =
      (
        await useFetchActivity({
          q,
        })
      )?.map((item) => item.extra) || []
    const activityAmount = data.length || 0
    let personAmount = 0
    let rateAmount = 0
    data.forEach((e: any) => {
      personAmount += e['实际参与人数'] || 0
      rateAmount += e['出席率'] || 0
    })
    item.count = activityAmount
    item.people = personAmount
    item.ratio = activityAmount ? rateAmount / activityAmount : 0
    item.list = [...data]
  })
  list.value = [...result]
}

const showModal = () => {
  store.commit('SET_SHOW_BASIC_INFO', false)
  store.commit('SET_ACTIVITY_LIST_MODAL', true)
}

watch(
  () => dateRange.value,
  ([start, end]) => {
    const query: string[] = []
    start &&
      query.push(
        `paths @ "活动日期" && number >= ${+(start + '').slice(0, 10)}`,
      )
    end &&
      query.push(`paths @ "活动日期" && number <= ${+(end + '').slice(0, 10)}`)
    getList(query.join(','))
  },
  { deep: true },
)
const disableDateStart = (ts: number) => {
  const cur = dayjs(ts)
  const start = dayjs('1900-01-01')
  if (dateRange.value[1]) {
    const end = dayjs(dateRange.value[1])
    return !cur.isAfter(start) || !cur.isBefore(end)
  }
  return !cur.isAfter(start)
}
const disableDateEnd = (ts: number) => {
  const cur = dayjs(ts)
  let start = dayjs('1900-01-01')
  if (dateRange.value[0]) {
    start = dayjs(dateRange.value[0])
  }
  return !cur.isAfter(start)
}

watch(
  () => list.value,
  async (list) => {
    const points: any[] = []
    list
      .filter((item) => item.onMap)
      .forEach((item) => points.push(...item.list))
    store.commit('SET_MAP_POINTS', points)
  },
  { deep: true },
)
</script>

<style lang="stylus" scoped>
@import '../../components/MyComponent/main.styl'
.content
  display flex
  flex-direction column
  .head
    padding 0 .12rem
    $flex-align()
    justify-content space-between
    font-family $font-ping-medium
    margin .05rem 0
  .date
    padding 0 .1rem .1rem
    border-bottom .01rem solid $light-gray
    .name
      display flex
      >p
        flex 1
        color $font
        padding-left .02rem
    .date-wrapper
      display flex
      justify-content space-between
      >.date-picker
        width 48%
  .list
    flex 1
    background #f7f7f7
    padding .08rem
    >div
      border-radius .04rem
      background #fff
      box-shadow 0 .02rem .06rem 0 rgba(0,0,0,0.1)
      padding .05rem .07rem
      box-sizing border-box
      margin-bottom .07rem
      .title
        $flex-align()
        justify-content space-between
        margin .05rem 0
        p
          font-family $font-ping-medium
        span
          font-size .08rem
          color $font
      .sum
        $flex-align()
        justify-content space-between
        margin .03rem 0
        >div
          width 49%
          border .01rem solid $light-gray
          border-radius .04rem
          padding .03rem .08rem
          box-sizing border-box
          .count
            color $red
            font-family $font-din
            font-size .14rem
            margin-right .03rem
          span
            font-size .08rem
          p
            color $font
            font-size .09rem
</style>
<style lang="stylus">
.n-date-picker
  .n-input
    background #f9fafb
</style>
