<template>
  <n-modal
    :show="show"
    :on-update:show="close"
    :mask-closable="false"
    style="width: 98vw; height: 91vh; transform: translateY(4%)"
    preset="card"
    title="党建活动录入"
  >
    <div class="content">
      <div id="activity-filter">
        <n-form
          :model="model"
          label-placement="left"
          label-width="0.9rem"
          size="small"
          inline
        >
          <n-form-item label="活动内容描述" path="description">
            <n-input
              v-model:value="model.description"
              placeholder="请输入活动描述"
              clearable
            />
          </n-form-item>
          <n-form-item label="活动日期区间" path="dateStart">
            <n-date-picker
              v-model:value="model.dateStart"
              class="date-picker"
              type="date"
              clearable
              size="small"
              :is-date-disabled="disableDateStart"
            />
          </n-form-item>
          <n-form-item path="dateEnd">
            <n-date-picker
              v-model:value="model.dateEnd"
              class="date-picker"
              type="date"
              clearable
              size="small"
              :is-date-disabled="disableDateEnd"
            />
          </n-form-item>
          <!-- <n-form-item label="出席率区间" path="rateStart">
            <n-input-number
              v-model:value="model.rateStart"
              :show-button="false"
              size="small"
              :validator="checkRateStart"
            >
              <template #suffix>%</template>
            </n-input-number>
          </n-form-item>
          <span class="dot">- </span>
          <n-form-item path="rateEnd">
            <n-input-number
              v-model:value="model.rateEnd"
              size="small"
              :show-button="false"
              :validator="checkRateEnd"
            >
              <template #suffix>%</template>
            </n-input-number>
          </n-form-item> -->
          <n-form-item label="标签类别" path="type">
            <n-select
              v-model:value="model.type"
              size="small"
              :options="typeOptions"
              clearable
            />
          </n-form-item>
          <n-form-item>
            <n-button
              color="#dd505e"
              text-color="#fff"
              @click="openNewDrawer(null)"
            >
              <n-icon size=".1rem">
                <Add />
              </n-icon>
              新增活动
            </n-button>
          </n-form-item>
        </n-form>
      </div>
      <div class="list">
        <n-data-table
          class="activity-table"
          :columns="columns"
          :data="activityList"
          :pagination="pagination"
          size="small"
        />
      </div>
    </div>
  </n-modal>
  <n-modal
    v-model:show="deleteConfirm"
    preset="dialog"
    title="操作确认"
    content="请确认是否删除?"
    @positive-click="sureToDelete"
  >
    <template #action>
      <n-space>
        <div class="btn cancel" @click="deleteConfirm = false">取消</div>
        <div class="btn sure" @click="sureToDelete">确定</div>
      </n-space>
    </template>
  </n-modal>
  <NewActivityDrawer :data="activityData" :cb="reFetchList" />
</template>

<script lang="ts" setup>
import store from '@/store'
import { computed, ref, h, watch } from 'vue'
import NewActivityDrawer from './new-activity-drawer.vue'
import { Add } from '@vicons/ionicons5'
import dayjs from '@/util/dayjs'
import { NButton, NTag, useMessage, NSpace } from 'naive-ui'
import { activity } from '@/util/tags'
import { useFetchActivity, useDeleteActivity } from '@/hooks/useFetch'
import useDebounce from '@/hooks/useDebounce'

const message = useMessage()

const activityList = ref([])

const fetchList = useDebounce(async (query?: string) => {
  let q = `paths @ "党组织编号" && string @ "${store.state.auth.code}"`
  query && (q += `,${query}`)
  activityList.value =
    (await useFetchActivity({ q }))?.map((item: any) => ({
      id: item.id,
      ...item.extra,
    })) || []
})
watch(
  () => store.state.auth.code,
  (code) => {
    if (!code) return
    fetchList()
  },
  { immediate: true },
)

function clearData() {
  model.value = {
    description: null,
    dateStart: null,
    dateEnd: null,
    // rateStart: null,
    // rateEnd: null,
    type: null,
  }
}
const reFetchList = () => {
  clearData()
  fetchList()
}
const show = computed(() => store.state.showActivityListModal)
const close = (val: boolean) => {
  store.commit('SET_ACTIVITY_LIST_MODAL', val)
  store.commit('SET_SHOW_BASIC_INFO', true)
  clearData()
}
const model = ref<any>({})
const typeOptions = computed(() => {
  return activity.map((item) => ({
    label: item.name,
    value: item.name,
  }))
})
watch(
  () => model.value,
  (cur) => {
    const query: string[] = []
    cur.description &&
      query.push(`paths @ "活动内容描述" && string @ "${cur.description}"`)
    cur.dateStart &&
      query.push(
        `paths @ "活动日期" && number >= ${+(cur.dateStart + '').slice(0, 10)}`,
      )
    cur.dateEnd &&
      query.push(
        `paths @ "活动日期" && number <= ${+(cur.dateEnd + '').slice(0, 10)}`,
      )
    // cur.rateStart &&
    //   query.push(`paths @ "出席率" && number >= ${cur.rateStart}`)
    // cur.rateEnd && query.push(`paths @ "出席率" && number <= ${cur.rateEnd}`)
    cur.type && query.push(`paths @ "标签类别" && string == "${cur.type}"`)
    fetchList(query.length > 0 ? query.join(',') : undefined)
  },
  { deep: true },
)

const activityData = ref<any>(null)
const openNewDrawer = (data: any = null) => {
  activityData.value = data
  store.commit('SET_NEW_ACTIVITY_DRAWER', true)
}

const deleteConfirm = ref(false)
const curRow = ref<any>(null)
const columns = [
  { title: '活动名称', key: '活动名称' },
  {
    title: '活动日期',
    key: '活动日期',
    render(row: any) {
      return h(
        'span',
        {},
        {
          default: () =>
            row['活动日期']
              ? dayjs(+(row['活动日期'] + '000')).format('YYYY-MM-DD')
              : '',
        },
      )
    },
  },
  {
    title: '标签类别',
    key: '标签类别',
    render(row: any) {
      let tagType = row['标签类别'] || []
      if (typeof tagType === 'string') {
        tagType = [tagType]
      }
      const types = tagType.map((tag: string) => ({
        type: activity?.find((e) => e.name === tag)?.type || 'default',
        name: tag,
      }))
      return h(NSpace, () => [
        ...types.map((item, i) =>
          h(
            NTag,
            {
              key: i,
              size: 'small',
              type: item.type as
                | 'default'
                | 'error'
                | 'primary'
                | 'info'
                | 'success'
                | 'warning',
            },
            { default: () => item.name },
          ),
        ),
      ])
    },
  },
  { title: '活动地址', key: '活动地址' },
  {
    title: '出席率',
    key: '出席率',
    render(row: any) {
      return h(
        'span',
        {},
        { default: () => (row['出席率'] ? `${row['出席率']}%` : '') },
      )
    },
  },
  {
    title: '参与人数',
    key: '实际参与人数',
    render(row: any) {
      return h(
        'span',
        {},
        {
          default: () =>
            row['实际参与人数'] ? `${row['实际参与人数']}人` : '',
        },
      )
    },
  },
  {
    title: ' ',
    key: 'actions',
    render(row: any) {
      return h(
        'div',
        { style: { display: 'flex', justifyContent: 'flex-end' } },
        [
          h(
            NButton,
            {
              size: 'tiny',
              type: 'primary',
              color: 'transparent',
              tag: 'a',
              textColor: '#3d7fe9',
              onClick: () => openNewDrawer({ ...row, _mode: 'view' }),
            },
            { default: () => '查看' },
          ),
          h(
            NButton,
            {
              size: 'tiny',
              type: 'primary',
              color: 'transparent',
              tag: 'a',
              textColor: '#3d7fe9',
              onClick: () => openNewDrawer({ ...row, _mode: 'modify' }),
            },
            { default: () => '修改' },
          ),
          h(
            NButton,
            {
              size: 'tiny',
              type: 'primary',
              color: 'transparent',
              tag: 'a',
              textColor: '#dd505E',
              onClick: () => {
                deleteConfirm.value = true
                curRow.value = row
              },
            },
            { default: () => '删除' },
          ),
        ],
      )
    },
  },
]
const pagination = {
  pageSize: 10,
}

const sureToDelete = async () => {
  await useDeleteActivity({
    id: [curRow.value.id],
  })
  deleteConfirm.value = false
  fetchList()
  message.success('删除成功')
}

const disableDateStart = (ts: number) => {
  const cur = dayjs(ts)
  const start = dayjs('1900-01-01')
  let end = dayjs()
  if (model.value.dateEnd) {
    end = dayjs(model.value.dateEnd)
  }
  return !cur.isAfter(start) || !cur.isBefore(end)
}
const disableDateEnd = (ts: number) => {
  const cur = dayjs(ts)
  let start = dayjs('1900-01-01')
  const end = dayjs()
  if (model.value.dateStart) {
    start = dayjs(model.value.dateStart)
  }
  return !cur.isAfter(start) || !cur.isBefore(end)
}
// const checkRateStart = (val: number) => {
//   const start = 0
//   let end = 100
//   if (model.value.rateEnd) {
//     end = model.value.rateEnd
//   }
//   return val >= start && val <= end
// }
// const checkRateEnd = (val: number) => {
//   let start = 0
//   const end = 100
//   if (model.value.rateStart) {
//     start = model.value.rateStart
//   }
//   return val >= start && val <= end
// }
</script>

<style lang="stylus" scoped>
@import '../../components/MyComponent/main.styl'
.content
  height 100%
  background #ededed
  border-radius .06rem
  #activity-filter
    background #fafafa
    padding .2rem .05rem 0
    .dot
      margin-right .15rem
      font-size .14rem
      color $gray
  .list
    padding .08rem
    .activity-table
      font-size .08rem
.btn
  font-size .1rem
  box-sizing border-box
  padding .03rem .2rem
  border-radius .03rem
  cursor pointer
  &:hover
    box-shadow 0 0 .06rem rgba(0,0,0,0.3)
  &.cancel
    border .01rem solid $light-gray
  &.sure
    color #fff
    background $blue
</style>
<style lang="stylus">
@import '../../components/MyComponent/main.styl'
.n-modal.n-card
  .n-card-header
    background $white-bg
    box-shadow  0 0.02rem .05rem rgba(0,0,0,0.1)
    font-family $font-ping-medium
    border-radius inherit
    z-index 2
  .n-card__content
    padding 0
#activity-filter
  .n-select
    width 1.4rem
  .n-input-number
    width .8rem
    .n-input-wrapper
      padding-right 0
      .n-input__suffix
        background #f3f4f7
        border-left .01rem solid $light-gray
        padding 0 .05rem
  .n-form-item-label
    font-size .1rem
    color $font
  .n-date-picker
    width 1rem
    .n-input
      background #fff
.activity-table
  .n-scrollbar-container
    border-radius .06rem
.n-dialog
  .n-dialog__content
    margin-left .3rem
  .n-dialog__icon
    color #F2A70D
  .n-button.n-button--primary-type
    background $blue
    .n-button__border
      border none
</style>
