<script lang="ts" setup>
import BussApi from '@/api/BussApi';
import { useDayjs } from '@/composables/useDayjs';
import type { Lesson, ScriptFileDestination } from '@/types/api/lesson';
import { extractLessonStage, getLessonSteps } from '@/utils/lesson';
import { computed, onMounted, ref } from 'vue';
import { useMessage, useToast } from 'wot-design-uni';

const message = useMessage()
const toast = useToast()
const dayjs = useDayjs()

type GroupedLessons = { [key: string]: Lesson[] }

const groupedLessons = ref<GroupedLessons>({})

const pickerCourseColumns = ref<string[]>([])
const pickerCourseValue = ref()

const pickerLessonColumns = computed(() => {
  return pickerCourseValue.value ? groupedLessons.value[pickerCourseValue.value].map((lesson: Lesson) => {
    return {
      label: (extractLessonStage(lesson).step === 4 ? '✅ ' : '') + lesson.m_lesson_name,
      value: lesson.id
    }
  }) : []
})
const pickerLessonValue = ref()

const selectedLesson = computed(() => {
  if (!pickerLessonValue.value) return null
  return groupedLessons.value[pickerCourseValue.value].find((lesson: Lesson) => lesson.id === pickerLessonValue.value)
})

const selectedLessonStage = computed(() => {
  if (!selectedLesson.value) return null
  return extractLessonStage(selectedLesson.value)
})

const onCoursePick = ({ value }: { value: string }) => {
  pickerCourseValue.value = value
  pickerLessonValue.value = void 0
}

const onLessonPick = ({ value }: { value: number }) => {
  pickerLessonValue.value = value
}

/**
 * lesson progress modifition steps
 */

const script_file_destination = ref<ScriptFileDestination>('wechat')

const onStep0 = () => {
  message.confirm({
    title: '提交脚本',
    msg: '请确认已经通过微信或平台上传了脚本文件，再确认提交'
  }).then(() => {
    if (!selectedLesson.value?.id) {
      toast.error({
        msg: '参数错误'
      })
      return
    }
    toast.loading({
      msg: '正在提交...'
    })
    BussApi.editCourse(selectedLesson.value.id, {
      script_file: script_file_destination.value,
      script_upload_time: dayjs().unix()
    }).then(res => {
      toast.success({
        msg: '提交成功'
      })
      setTimeout(() => {
        updateLessons()
      }, 1500);
    }).catch(err => {
      toast.error({ msg: err.message })
    })
  })
}

const updateLessons = () => {
  toast.loading({
    msg: '加载中...'
  })
  BussApi.lessons(1, 512).then(res => {
    toast.close()
    const groupData = res.data.sort((a: Lesson, b: Lesson) => {
      return a.id - b.id
    }).reduce((acc: any, cur: any) => {
      if (!acc[cur.course_name]) {
        acc[cur.course_name] = []
      }
      acc[cur.course_name].push(cur)
      return acc
    }, {})
    groupedLessons.value = groupData
    pickerCourseColumns.value = [
      ...Object.keys(groupData)
    ]
  }).catch(err => {
    toast.error({ msg: err.message })
  })
}

onMounted(() => {
  updateLessons()
})
</script>

<template>
  <page-wrapper>
    <div class="shadow-md shadow-op-50 overflow-hidden">
      <wd-picker :columns="pickerCourseColumns" label="课程选择" v-model="pickerCourseValue" @confirm="onCoursePick"
        :columns-height="280" label-width="80px" safe-area-inset-bottom title="课程选择" />
      <wd-picker :columns="pickerLessonColumns" label="微课选择" v-model="pickerLessonValue" @confirm="onLessonPick"
        :columns-height="280" label-width="80px" safe-area-inset-bottom title="微课选择" :disabled="!pickerCourseValue" />
    </div>
    <div class="p-2 pt-4">
      <wd-status-tip v-if="!pickerLessonValue" image="search" tip="请先选择微课" />
      <div v-else class="space-y-6">
        <div>
          <wd-steps :active="selectedLessonStage?.step || 0" align-center>
            <wd-step v-for="(step, index) in getLessonSteps(selectedLesson!, true)" :key="index" :title="step.title"
              :description="(selectedLessonStage?.step || 0 <= index) ? step.description : undefined" />
          </wd-steps>
        </div>
        <div v-if="selectedLessonStage?.step === 0" class="px-2">
          <wd-cell-group>
            <wd-cell title="脚本提交途径" :title-width="'100px'" center custom-class="mb-4">
              <wd-radio-group v-model="script_file_destination" shape="button">
                <wd-radio value="wechat">微信</wd-radio>
                <wd-radio value="qq">QQ</wd-radio>
                <wd-radio value="platform">平台</wd-radio>
              </wd-radio-group>
            </wd-cell>
          </wd-cell-group>

          <wd-button type="primary" block @click="onStep0" custom-class="w-full">提交脚本</wd-button>
        </div>
        <div v-if="selectedLessonStage?.step === 1"></div>
        <div v-if="selectedLessonStage?.step === 2"></div>
        <div v-if="selectedLessonStage?.step === 3"></div>
        <div v-else-if="selectedLessonStage?.step === 4">
          <wd-status-tip image="comment" tip="该微课已完成" />
        </div>
      </div>
    </div>
  </page-wrapper>
</template>

<style scoped></style>
