import request from '@/helpers/request'
import { state } from '@/state'
import { Tab, Tabs, DropdownMenu, DropdownItem, List } from 'vant'
import {
  computed,
  defineComponent,
  onMounted,
  reactive,
  Transition,
  ref
} from 'vue'
import styles from './index.module.less'
import { useRouter, useRoute } from 'vue-router'
import ColHeader from '@/components/col-header'
import TheSticky from '@/components/the-sticky'
import bgImg from '../../images/bg.png'
import Search from '@/components/col-search'
import CourseItem from './component/CourseItem'
import ColResult from '@/components/col-result'
import { browser } from '@/helpers/utils'
import { postMessage } from '@/helpers/native-message'

export default defineComponent({
  name: 'lessonCourseware',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const params = reactive<{
      keyword: string
      albumId: string
      subjectList: any[]
      page: number
    }>({
      keyword: (route.query.search as string) || '',
      albumId: route.query.albumId as string,
      subjectList: [],
      page: 1
    })
    const loading = ref(false)
    const finished = ref(false)
    const isError = ref(false)
    const subjectOptValue = ref('')
    const subjectOpt = ref<any[]>([])
    enum courseEmnu {
      PERCUSSION_SINGLE = '打击乐',
      FLUTE_SINGLE = '长笛',
      SAX_SINGLE = '萨克斯',
      CLARINET_SINGLE = '单簧管',
      TRUMPET_SINGLE = '小号',
      TROMBONE_SINGLE = '长号',
      HORN_SINGLE = '圆号',
      BARITONE_TUBA_SINGLE = '上低音号-大号',
      MUSIC_THEORY = '乐理',
      INSTRUMENTAL_ENSEMBLE = '合奏',
      EUPHONIUM_SINGLE = '上低音号',
      TUBA_SINGLE = '大号'
    }
    const getSelectCondition = async () => {
      try {
        const res = await request.post(
          `/api-student/tenantAlbumMusic/selectCondition`,
          {
            data: {
              subjectType: 'COURSEWARE',
              tenantAlbumId: params.albumId
            }
          }
        )
        if (res.code === 200) {
          subjectOpt.value = [
            {
              text: '全部教材',
              value: ''
            },
            ...(res.data?.courseTypeList || []).map(item => {
              return {
                text: courseEmnu[item],
                value: item
              }
            })
          ]
        }
      } catch {
        //
      }
    }
    function onSearch(value: string) {
      params.page = 1
      params.keyword = value
      params.subjectList = []
      FetchList()
    }
    function handleOnRefresh() {
      params.page = 1
      params.subjectList = []
      FetchList()
    }
    const FetchList = async () => {
      loading.value = true
      isError.value = false

      try {
        const res = await request.post(`/api-student/tenantAlbumMusic/page`, {
          data: {
            courseTypeCode: subjectOptValue.value,
            keyword: params.keyword,
            albumId: params.albumId,
            subjectType: 'COURSEWARE',
            page: params.page,
            rows: 20
          }
        })
        if (params.subjectList?.length > 0 && res.data.pageNo === 1) {
          return
        }
        const result = (params.subjectList || []).concat(res.data?.rows || [])
        params.subjectList = result
        params.page = res.data.pageNo + 1
        finished.value = res.data.pageNo >= res.data.totalPage
      } catch (error) {
        isError.value = true
      }
      loading.value = false
    }
    onMounted(async () => {
      loading.value = true
      await getSelectCondition()
      if (params.albumId) {
        await FetchList()
      } else {
        loading.value = false
      }
    })
    return () => {
      return (
        <>
          <div class={styles.sticky}>
            <TheSticky>
              <ColHeader
                hideHeader={false}
                background="transparent"
                isFixed={false}
                border={false}
                title={'云课堂'}
                color="#131415"
              ></ColHeader>
              <Search
                class={styles.search}
                onSearch={onSearch}
                type="tenant"
                placeholder={'请输入教材关键词'}
                background="transparent"
                inputBackground="transparent"
                // leftIcon={iconSearch}
                v-slots={{
                  left: () =>
                    subjectOpt.value.length > 1 && (
                      <DropdownMenu class={styles.dropdownMenuSub}>
                        <DropdownItem
                          titleClass={styles.titleActive}
                          v-model={subjectOptValue.value}
                          options={subjectOpt.value}
                          onChange={handleOnRefresh}
                        >
                          <div></div>
                        </DropdownItem>
                      </DropdownMenu>
                    )
                }}
              />
            </TheSticky>
            <img class={styles.bgImg} src={bgImg} />
          </div>

          <div class={styles.alumnList}>
            <List
              loading={loading.value}
              finished={finished.value}
              finished-text={''}
              onLoad={FetchList}
              error={isError.value}
              immediateCheck={false}
            >
              {params.subjectList.length ? (
                <CourseItem
                  class={[styles.courseItem]}
                  list={params.subjectList.map(item => {
                    return {
                      name: item.musicSheetName,
                      coverImg: item.titleImg,
                      id: item.id
                    }
                  })}
                  onItemClick={row => {
                    if (browser().isApp) {
                      const url = `${location.origin}/tenant/#/courseList?id=${row.id}&albumId=${params.albumId}`
                      postMessage({
                        api: 'openWebView',
                        content: {
                          url,
                          orientation: 1,
                          isHideTitle: false
                        }
                      })
                    } else {
                      router.push({
                        path: '/courseList',
                        query: {
                          id: row.id,
                          albumId: params.albumId
                        }
                      })
                    }
                  }}
                />
              ) : (
                !loading.value && (
                  <ColResult
                    tips="暂无教材"
                    classImgSize="CERT"
                    btnStatus={false}
                  />
                )
              )}
            </List>
          </div>
        </>
      )
    }
  }
})
