<script lang="ts" setup>
import ModalAuthentication from '~/components/ModalAuthentication.vue'
import SlideCreateCourse from '~/components/SlideCreateCourse.vue'
import { useFetchWrapped } from '~/composables/useFetchWrapped'

const toast = useToast()
const modal = useModal()
const slide = useSlideover()
const loginState = useLoginState()

const deletePending = ref(false)
const page = ref(1)

const {
  data: courseList,
  refresh: refreshCourseList,
} = useAsyncData(
  () => useFetchWrapped<
    req.gen.CourseGenList & AuthedRequest,
    BaseResponse<PagedData<resp.gen.CourseGenItem>>
  >('App.Digital_Convert.GetList', {
    token: loginState.token!,
    user_id: loginState.user.id,
    to_user_id: loginState.user.id,
    page: page.value,
    perpage: 16,
  }), {
    watch: [page],
  },
)

const onCreateCourseClick = () => {
  slide.open(SlideCreateCourse, {
    onSuccess: () => {
      refreshCourseList()
    },
  })
}

const onCourseDelete = (task_id: string) => {
  if (!task_id) return
  deletePending.value = true
  useFetchWrapped<
    req.gen.CourseGenDelete & AuthedRequest,
    BaseResponse<resp.gen.CourseGenDelete>
  >('App.Digital_Convert.Delete', {
    token: loginState.token!,
    user_id: loginState.user.id,
    to_user_id: loginState.user.id,
    task_id,
  }).then(res => {
    if (res.ret === 200) {
      toast.add({
        title: '删除成功',
        description: '已删除任务记录',
        color: 'green',
        icon: 'i-tabler-check',
      })
    } else {
      toast.add({
        title: '删除失败',
        description: res.msg || '未知错误',
        color: 'red',
        icon: 'i-tabler-alert-triangle',
      })
    }
  }).finally(() => {
    deletePending.value = false
    refreshCourseList()
  })
}

const beforeLeave = (el: any) => {
  el.style.width = `${ el.offsetWidth }px`
  el.style.height = `${ el.offsetHeight }px`
}

const leave = (el: any, done: Function) => {
  el.style.position = 'absolute'
  el.style.transition = 'none' // 取消过渡动画
  el.style.opacity = 0 // 立即隐藏元素
  done()
}

onMounted(() => {
  const i = setInterval(refreshCourseList, 1000 * 5)
  onBeforeUnmount(() => clearInterval(i))
})
</script>

<template>
  <div>
    <div class="p-4 pb-0">
      <BubbleTitle subtitle="VIDEOS" title="我的微课视频">
        <template #action>
          <UButton
            :trailing="false"
            color="primary"
            icon="i-tabler-plus"
            label="新建微课"
            size="md"
            variant="solid"
            @click="() => {
              if (!loginState.is_logged_in) {
                modal.open(ModalAuthentication)
                return
              }
              onCreateCourseClick()
            }"
          />
        </template>
      </BubbleTitle>
      <GradientDivider/>
    </div>
    <Transition name="loading-screen">
      <div
        v-if="courseList?.data.items.length === 0"
        class="w-full py-20 flex flex-col justify-center items-center gap-2"
      >
        <Icon class="text-7xl text-neutral-300 dark:text-neutral-700" name="i-tabler-photo-hexagon"/>
        <p class="text-sm text-neutral-500 dark:text-neutral-400">
          没有记录
        </p>
      </div>
      <div v-else class="p-4">
        <div class="relative grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4 fhd:grid-cols-5 gap-4">
          <TransitionGroup
            name="card"
            @beforeLeave="beforeLeave"
            @leave="leave"
          >
            <AigcGenerationCGTaskCard
              v-for="(course, index) in courseList?.data.items"
              :key="course.task_id || 'unknown' + index"
              :course="course"
              @delete="(task_id: string) => onCourseDelete(task_id)"
            />
          </TransitionGroup>
        </div>
        <div class="flex justify-end mt-4">
          <UPagination v-model="page" :max="9" :page-count="16" :total="courseList?.data.total || 0"/>
        </div>
      </div>
    </Transition>
  </div>
</template>

<style scoped>

</style>