import request from '@/helpers/request'
import { state } from '@/state'
import {
  ActionSheet,
  ActionSheetAction,
  Button,
  Empty,
  Grid,
  GridItem,
  Icon,
  Picker,
  Popover,
  Popup,
  showToast,
  Toast
} from 'vant'
import { computed, defineComponent, onMounted, reactive, Transition } from 'vue'
import styles from './index.module.less'
import iconLook from './image/look.svg'
import { useRoute, useRouter } from 'vue-router'
import OEmpty from '@/components/o-empty'
import OSticky from '@/components/o-sticky'
import OHeader from '@/components/o-header'
import CourseItem from './component/CourseItem'
import { courseEmnu } from '@/constant'
import { browser } from '@/helpers/utils'
import OLoading from '@/components/o-loading'
export default defineComponent({
  name: 'lessonCourseware',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const data = reactive({
      loading: true,
      list: [] as any,
      actionShow: false,
      actionName: '课程类型' as string | undefined,
      actionKey: '',
      showRight: route.query.code != 'select' && browser().isTeacher
    })
    const filterData = (list: any[]) => {
      const schoolTerm = {}
      for (let i = 0; i < list.length; i++) {
        if (schoolTerm[list[i].sortNo]) {
          schoolTerm[list[i].sortNo].push(list[i])
        } else {
          schoolTerm[list[i].sortNo] = [list[i]]
        }
      }
      return schoolTerm
    }
    const getList = async () => {
      data.loading = true
      if (route.query.code === 'select') {
        try {
          const res: any = await request.post(
            state.platformApi + `/courseSchedule/getCourseware/${route.query.courseScheduleId}`
          )
          if (Array.isArray(res?.data)) {
            const _data = res.data.map((n: any) => {
              return {
                ...n,
                coverImg: n.coverImg,
                name: n.coursewareName,
                id: n.lessonCoursewareId,
                courseNum: n.coursewareNum
              }
            })
            data.list = filterData(_data)
            console.log('🚀 ~ data.list:', data.list)
          }
        } catch (error) {}
      } else {
        try {
          const res: any = await request.post(state.platformApi + '/courseSchedule/myCourseware')
          if (Array.isArray(res?.data)) {
            const _data = data.actionKey
              ? res.data.filter((n: any) => n.courseTypeCode === data.actionKey)
              : res.data
            data.list = filterData(_data)
          }
        } catch (error) {}
      }
      data.loading = false
    }
    onMounted(() => {
      getList()
    })
    const handleClick = (item: any) => {
      if (route.query.code === 'select') {
        router.push({
          path: '/courseList',
          query: {
            ...route.query,
            id: item.id
          }
        })
        return
      }
      router.push({
        path: '/courseList',
        query: {
          id: item.id
        }
      })
    }

    const actions = computed(() => {
      const _list = Object.entries(courseEmnu).map(([key, value]) => {
        return {
          id: key,
          name: value,
          text: value,
          value: key,
          color: key === data.actionKey ? 'var(--van-primary)' : ''
        }
      })
      _list.unshift({
        id: '',
        name: '课程类型',
        text: '全部',
        value: '',
        color: '' === data.actionKey ? 'var(--van-primary)' : ''
      })
      return _list
    })

    const handleSelect = (action: any) => {
      data.actionKey = action.id
      data.actionName = action.name
      data.actionShow = false
      getList()
    }
    return () => (
      <div
        class={[styles.lessonCourseware, !Object.values(data.list).length && 'emptyRootContainer']}
      >
        <OHeader
          border={false}
          background="rgba(255, 232, 206, 1)"
          color="rgba(124, 61, 18, 1)"
          title="云教材"
        >
          {{
            right: () => (
              <>
                {data.showRight && (
                  <div class={styles.filter} onClick={() => (data.actionShow = true)}>
                    {data.actionName} <Icon style={{ transform: 'rotate(90deg)' }} name="play" />{' '}
                  </div>
                )}
              </>
            )
          }}
        </OHeader>
        <Transition name="van-fade">
          {!data.loading &&
            Object.keys(data.list).map((key: any) => {
              return (
                <CourseItem
                  term={key}
                  list={data.list[key]}
                  onItemClick={(row) => handleClick(row)}
                />
              )
            })}
        </Transition>
        {data.loading && <OLoading />}

        {!data.loading && !Object.values(data.list).length && <OEmpty tips="没有课件" />}
        <Popup position="bottom" round v-model:show={data.actionShow}>
          <Picker
            class="popupBottomSearch"
            columns={actions.value}
            onCancel={() => (data.actionShow = false)}
            onConfirm={({ selectedOptions }) => {
              handleSelect(selectedOptions[0])
            }}
          />
        </Popup>
      </div>
    )
  }
})
