import { get } from 'radash'
import { Activity, StudyTour } from '../core/libs/models'
import { getActivityStatusButtonText } from '../core/utils/common'
import dayjs from 'dayjs'
import { useUserStore } from '../store'
import { storeToRefs } from 'pinia'

/**
 * 游学活动
 */
export const useActivity = (options: globalThis.Ref<Partial<Activity> | Partial<StudyTour>>) => {
  const userStore = useUserStore()
  const { userInfo } = storeToRefs(userStore)
  const applyStartAt = computed(
    () => options.value?.applyStartTime || options.value?.planApplyStartTime,
  )
  const applyEndAt = computed(() => options.value?.applyEndTime || options.value?.planApplyEndTime)
  const startAt = computed(() => options.value?.activityStartTime || options.value?.studyStartTime)
  const endAt = computed(() => options.value?.activityEndTime || options.value?.studyEndTime)
  const listItemButtonText = ref(getActivityStatusButtonText(applyStartAt.value, applyEndAt.value))
  const tooltipShow = ref(true)
  const difference = computed(() =>
    options.value?.needPointsType === '1'
      ? options.value?.needPointsCount - userInfo.value?.level?.point
      : 0,
  )
  const getActivityStatus = () => {
    const now = new Date()
    if (dayjs(now).isBefore(dayjs(applyStartAt.value))) {
      return 'waiting'
    } else if (
      dayjs(now).isAfter(dayjs(applyStartAt.value)) &&
      dayjs(now).isBefore(dayjs(applyEndAt.value))
    ) {
      return 'registering'
    } else if (
      dayjs(now).isAfter(dayjs(applyEndAt.value)) &&
      dayjs(now).isBefore(dayjs(startAt.value))
    ) {
      return 'closed'
    } else if (
      dayjs(now).isAfter(dayjs(startAt.value)) &&
      dayjs(now).isBefore(dayjs(endAt.value))
    ) {
      return 'running'
    } else {
      return 'overdue'
    }
  }
  // 报名未开始、报名中、报名已结束、活动进行中、活动已结束
  const getActivityStatusText = () =>
    ({
      waiting: '报名未开始',
      registering: '报名中',
      closed: '报名已结束',
      running: '活动进行中',
      overdue: '活动已结束',
    })[getActivityStatus()]
  const status = ref(getActivityStatus())
  const statusText = ref(getActivityStatusText())
  const detailButtonText = ref()
  const refresh = () => {
    listItemButtonText.value = getActivityStatusButtonText(applyStartAt.value, applyEndAt.value)
    status.value = getActivityStatus()
    statusText.value = getActivityStatusText()
  }
  watch(
    () => options.value,
    () => {
      console.log(1111)
      refresh()
    },
  )
  return {
    getActivityStatusText: () => getActivityStatusText(),
    status,
    listItemButtonText,
    statusText,
    tooltipShow,
    difference,
    refresh,
    startAt,
    endAt,
  }
}
