import {
  computed,
  defineComponent,
  onMounted,
  reactive,
  ref,
  watch,
  nextTick
} from 'vue'
import {
  Image,
  Tabs,
  Tab,
  List,
  Button,
  Popup,
  Dialog,
  Sticky,
  Picker,
  DropdownMenu,
  DropdownItem,
  Tag
} from 'vant'
import styles from './index.module.less'
import TheSticky from '@/components/the-sticky'
import ColHeader from '@/components/col-header'
// import { useWindowScroll, useEventListener } from '@vueuse/core'
import request from '@/helpers/request'
// import iconMenu from './images/icon-menu.png'
// import iconRightTop from './images/icon-right-top.png'
import Search from '@/components/col-search'
import iconAlbumCover from '../../images/icon-album-cover.png'
import iconTimer from './images/icon-timer.png'
import iconArrow from './images/icon-arrow.png'
import { state as baseState, setLogout } from '@/state'
import Song from '../component/song'
import { useRoute, useRouter } from 'vue-router'
import ColResult from '@/components/col-result'
import { moneyFormat } from '@/helpers/utils'
import { orderStatus } from '@/views/order-detail/orderStatus'
import { postMessage } from '@/helpers/native-message'
import { browser } from '@/helpers/utils'
// Import Swiper Vue.js components
// import Swiper core and required modules
import { Pagination } from 'swiper/modules'
import { Swiper, SwiperSlide } from 'swiper/vue'
// Import Swiper styles
import 'swiper/css'
import 'swiper/css/pagination'
import CourseItem from '../lessonCourseware/component/CourseItem'


export default defineComponent({
  name: 'train-tool',
  setup() {
    const sessionStorageToolSubject =
      sessionStorage.getItem('tool-subject-type')
    const toolSubject =
      sessionStorageToolSubject && JSON.parse(sessionStorageToolSubject)
    sessionStorage.removeItem('tool-subject-type')

    const route = useRoute()
    const router = useRouter()
    const tabsRef = ref()
    const background = ref<string>('rgba(55, 205, 177, 0)')
    // const color = ref<string>('#fff')
    const state = reactive({
      userId: '',
      details: {} as any,
      buy: route.query.buy as any,
      albumId: route.query.albumId || null,
      activeTab:
        toolSubject?.activeTab || route.query.subjectType || 'COURSEWARE', // 有缓存 默认用缓存,之后用请求头，最后默认
      initLoadPage: false,
      showLoading: false,
      loadingAlbum: false,
      loading: false,
      finished: false,
      isError: false,
      list: [] as any,
      popupStatus: false,
      // selectMember: {} as any, // 购买的月份
      ensembleCounts: false,
      musicCounts: false,
      subjectCounts: false,
      coursewareCounts: false,
      tenantAlbumStatus: 0 as any,
      ablumStatus: false,
      heightV: 0,
      hasBuyStatus: true, // 是否能继续购买
      albumList: [] as any, // 专辑列表
      initialSlide: 0,
      subjectStatus: false,
      openStatus: false,
      teacherSubjectId: null as any,
      teacherSubjectName: null as any,
      teacherSubjectIndex: 0,
      subjectList: [] // 声部列表
    })
    // const params = reactive({
    //   keyword: (route.query.search as string) || '',
    //   subjectType: subjectType,
    //   page: 1,
    //   subjectId: null,
    //   albumId: route.query.albumId,
    //   albumName: '',
    //   level: '',
    //   type: '',
    //   title: title
    // })
    const searchObj = ref<any>({
      COURSEWARE: {},
      SUBJECT: {},
      MUSIC: {},
      ENSEMBLE: {}
    })
    const searchRef = ref()
    const params = reactive({
      keyword: toolSubject?.keyword || null as any,
      // subjectType: '',
      subjectId: toolSubject?.subjectId ||null,
      // albumId: route.query.albumId,
      // albumName: '',
      level: toolSubject?.level ||'',
      type: toolSubject?.type ||'',
      courseTypeCode: '',
      // title: '',
      page: 1,
      rows: 20
    })
    const apiSuffix = ref(
      baseState.platformType === 'STUDENT' ? '/api-student' : '/api-teacher'
    )

    const isSingleAlbum = computed(() => {
      const query = route.query
      if (query.taId || (query.albumId && state.buy === '1')) {
        return true
      } else {
        return false
      }
    })

    const isSearchStatus = computed(() => {
      const obj = searchObj.value[state.activeTab]
      let status = false
      if (state.activeTab === 'COURSEWARE') {
        if (obj.courseTypeList && obj.courseTypeList.length > 0) {
          status = true
        }
      } else {
        if (obj.subjects && obj.subjects.length > 0) {
          status = true
        }
        if (obj.levelList && obj.levelList.length > 0) {
          status = true
        }
        if (obj.typeList && obj.typeList.length > 0) {
          status = true
        }
      }
      return status
    })

    const getDetails = async () => {
      state.loadingAlbum = true
      try {
        // tenantGroupAlbum/buyAlbumInfo
        // 当我的曲目过来的时候才走单个查询
        if (state.albumId && state.buy === '1') {
          let url = apiSuffix.value + '/userTenantAlbumRecord/detail'
          if (state.albumId) {
            url = url + '?albumId=' + state.albumId
          }
          const { data } = await request.post(url)
          state.albumList = [data || {}]
          state.details = data || {}
        } else {
          const url =
            apiSuffix.value +
            `/tenantGroupAlbum/buyAlbumInfo?tenantGroupAlbumId=${
              route.query.taId || ''
            }`
          //&tenantAlbumId=${state.albumId || ''}
          // if (state.albumId) {
          //   url = url + '?albumId=' + state.albumId
          // }
          const { data } = await request.get(url)
          state.albumList = data || []
          if (state.albumList.length > 0) {
            let index = 0
            // 以缓存为优先 其次 请求头 state.albumId
            if (toolSubject?.tenantGroupAlbumId || state.albumId) {
              index = state.albumList.findIndex(item => {
                return toolSubject?.tenantGroupAlbumId
                  ? (baseState.platformType === 'STUDENT'
                      ? item.tenantGroupAlbumId
                      : item.id) === toolSubject?.tenantGroupAlbumId
                  : item.id == state.albumId // 这里不全等 因为state.albumId为字符串 id为number
              })
              index < 0 && (index = 0)
            }
            state.initialSlide = index //默认展示第几个
            state.details = state.albumList[index] // 有缓存  就用缓存里面的数据
          } else {
            // state.albumList
            if (!browser().isApp) {
              Dialog.alert({
                title: '提示',
                message: '该教程不可购买',
                confirmButtonText: '确定',
                confirmButtonColor: '#2dc7aa'
              }).then(() => {
                if (browser().isApp) {
                  postMessage({ api: 'back' })
                } else {
                  setLogout()
                  router.replace({
                    path: '/login' as any,
                    query: {
                      returnUrl: '/train-tool',
                      ...route.query
                    }
                  })
                }
              })
            }
          }
        }
      } catch {
        //
      }
      state.loadingAlbum = false
    }

    const getSelectCondition = async (type: string) => {
      // 判断是否已经查询过数据
      if (Object.keys(searchObj.value[type]).length > 0) {
        return
      }
      const { data } = await request.post(
        `${apiSuffix.value}/tenantAlbumMusic/selectCondition`,
        {
          data: {
            subjectId: state.teacherSubjectId,
            subjectType: type,
            tenantAlbumId: state.details.id
          }
        }
      )
      searchObj.value[type] = data || {}
    }

    watch(
      () => state.details,
      () => {
        state.ensembleCounts = state.details?.ensembleCounts ? true : false
        state.subjectCounts = state.details?.subjectCounts ? true : false
        state.musicCounts = state.details?.musicCounts ? true : false
        state.coursewareCounts = state.details?.coursewareCounts ? true : false
        if (state.details.buyTimesFlag) {
          if (state.details.buyedTimes >= state.details.buyTimes) {
            state.hasBuyStatus = false
          } else {
            state.hasBuyStatus = true
          }
        } else {
          state.hasBuyStatus = true
        }
      }
    )
    let listController
    const FetchList = async (hideLoading = false) => {
      if (!state.details.id) {
        return
      }
      if (listController) {
        listController.abort()
      }
      state.loading = true
      state.isError = false
      const tempParams = {
        ...params,
        //   level: '',
        // type: '',
        // subjectId: params.subjectId
        albumId: state.details.id || null,
        subjectType: state.activeTab
      } as any

      // 老师端默认查询声部
      if (baseState.platformType === 'TEACHER') {
        // const users = baseState.user.data
        tempParams.subjectId = state.teacherSubjectId || null
      }

      try {
        listController = new AbortController()
        const { signal } = listController
        const { data } = await request.post(
          `${apiSuffix.value}/tenantAlbumMusic/page`,
          {
            hideLoading,
            data: tempParams,
            signal
          }
        )
        if (state.list.length > 0 && data.pageNo === 1) {
          return
        }
        state.list = state.list.concat(data.rows || [])
        params.page = data.pageNo + 1
        // showContact.value = state.list.length > 0
        state.loading = false
        state.finished = data.pageNo >= data.totalPage
        params.page = data.pageNo + 1
      } catch (error) {
        state.isError = true
      }
      state.loading = false
    }

    const getSubjectList = async () => {
      try {
        const res = await request.get('/api-tenant/open/subject/queryPage', {
          params: { page: 1, rows: 9999, queryType: 'list' }
        })
        const result = res.data.rows || []
        result.forEach((item: any) => {
          item.text = item.name
        })
        state.subjectList = result || []
        const index = state.subjectList.findIndex(
          (item: any) => item.id == state.teacherSubjectId
        )
        state.teacherSubjectIndex = index === -1 ? 0 : index
      } catch (e) {
        console.log(e)
      }
    }

    /** 设置声部 */
    const operatoinCatchSubjectInfo = (
      type: 'set' | 'get',
      params?: {
        defaultSubject: string
        defaultSubjectName: string
        userId: string | number
      }
    ) => {
      if (type === 'set') {
        localStorage.setItem(
          'trainTool-teacherSubjectInfo',
          JSON.stringify(params)
        )
      } else if (type === 'get') {
        const result = localStorage.getItem('trainTool-teacherSubjectInfo')
        return result ? JSON.parse(result) : null
      }
    }

    // 获取信息
    const activeTypeParams = async () => {
      if (state.activeTab === 'COURSEWARE') {
        await getSelectCondition(state.activeTab)
      } else if (['SUBJECT', 'MUSIC', 'ENSEMBLE'].includes(state.activeTab)) {
        await getSelectCondition(state.activeTab)
      }
    }

    const onSearch = (value?: string) => {
      params.page = 1
      // state.finished = false
      params.keyword = value
      state.list = []
      FetchList()
    }
    onMounted(async () => {
      // useEventListener(document, 'scroll', evt => {
      //   const { y } = useWindowScroll()
      //   if (y.value > 20) {
      //     background.value = `rgba(255, 255, 255)`
      //   } else {
      //     background.value = 'transparent'
      //   }
      // })

      // 老师端默认查询声部
      if (baseState.platformType === 'TEACHER') {
        const users = baseState.user.data
        state.userId = users.userId
        const catchSubject = operatoinCatchSubjectInfo('get')
        if (catchSubject && users.userId === catchSubject.userId) {
          state.teacherSubjectId = catchSubject.defaultSubject || null
          state.teacherSubjectName = catchSubject.defaultSubjectName || null
        } else {
          state.teacherSubjectId = users.defaultSubject || null
          state.teacherSubjectName = users.defaultSubjectName || null
        }

        operatoinCatchSubjectInfo('set', {
          defaultSubject: state.teacherSubjectId,
          defaultSubjectName: state.teacherSubjectName,
          userId: state.userId
        })
      }

      state.loading = true
      state.loadingAlbum = true
      state.initLoadPage = true
      await getDetails()
      await FetchList()
      if (baseState.platformType === 'TEACHER') {
        getSubjectList()
      }

      activeTypeParams()
      state.initLoadPage = false
      state.loadingAlbum = false
      state.loading = false

      // 为了处理 swiper 会不显示的问题
      document.body.scrollIntoView()
      window.scrollTo(1, 0)
    })
    function handleChangeActiveTab() {
      state.showLoading = true
      state.activeTab = state.details?.coursewareCounts
        ? 'COURSEWARE'
        : state.details?.subjectCounts
        ? 'SUBJECT'
        : state.details?.musicCounts
        ? 'MUSIC'
        : 'ENSEMBLE'
      setTimeout(() => {
        state.showLoading = false
      }, 0);
    }
    const onSubmit = async () => {
      const album = state.details
      const details = state.details
      orderStatus.orderObject.orderType = 'TENANT_ALBUM'
      orderStatus.orderObject.orderName = details.name
      orderStatus.orderObject.orderDesc = details.name
      orderStatus.orderObject.actualPrice = album.actualPrice
      // orderStatus.orderObject.recomUserId = route.query.recomUserId || 0
      // orderStatus.orderObject.activityId = route.query.activityId || 0
      orderStatus.orderObject.orderNo = ''
      orderStatus.orderObject.orderList = [
        {
          orderType: 'TENANT_ALBUM',
          goodsName: details.name,
          actualPrice: album.actualPrice,
          price: album.actualPrice,
          ...details,
          ...album
        }
      ]

      const res = await request.post('/api-student/userOrder/getPendingOrder', {
        data: {
          goodType: 'TENANT_ALBUM',
          bizId: details.id
        }
      })

      const result = res.data
      if (result) {
        state.popupStatus = false
        Dialog.confirm({
          title: '提示',
          message: '您有一个未支付的订单，是否继续支付？',
          theme: 'round-button',
          className: 'confirm-button-group',
          cancelButtonText: '取消订单',
          confirmButtonText: '继续支付'
        })
          .then(async () => {
            orderStatus.orderObject.orderNo = result.orderNo
            orderStatus.orderObject.actualPrice = result.actualPrice
            orderStatus.orderObject.discountPrice = result.discountPrice
            orderStatus.orderObject.paymentConfig = {
              ...result.paymentConfig,
              paymentVendor: result.paymentVendor,
              paymentVersion: result.paymentVersion
            }

            routerTo()
          })
          .catch(() => {
            Dialog.close()
            // 只用取消订单，不用做其它处理
            cancelPayment(result.orderNo)
          })
      } else {
        routerTo()
      }
    }
    const routerTo = () => {
      const album = state.details
      sessionStorage.setItem(
        'tool-subject-type',
        JSON.stringify({
          activeTab: state.activeTab,
          tenantGroupAlbumId:
            baseState.platformType === 'STUDENT'
              ? state.details.tenantGroupAlbumId
              : state.details.id, // 老师用专辑id当唯一值
          level: params.level,
          type: params.type,
          subjectId: params.type,
          keyword: params.keyword
        })
      )
      router.push({
        path: '/orderDetail',
        query: {
          orderType: 'TENANT_ALBUM',
          album: album.id
        }
      })
    }

    const cancelPayment = async (orderNo: string) => {
      try {
        await request.post('/api-student/userOrder/orderCancel/v2', {
          data: {
            orderNo
          }
        })
      } catch {
        //
      }
    }
    return () => (
      <div class={styles.trainTool}>
        {!state.loading && !state.details.id && state.buy != '1' ? (
          <>
            <TheSticky
              class={styles.theSticky}
              position="top"
              onBarHeight={(height: any) => {
                state.heightV = Math.floor(height)
              }}
            >
              <ColHeader border={false} isFixed={false} />
            </TheSticky>
            {!state.loading && (
              <div
                class={styles.colResultBox}
                style={{
                  height: 'calc(100vh - var(--header-height))',
                  display: 'flex',
                  alignItems: 'center'
                }}
              >
                <ColResult
                  tips="暂无教程"
                  classImgSize="SMALL"
                  btnStatus={false}
                />
              </div>
            )}
          </>
        ) : (
          !state.loadingAlbum && (
            <>
              <TheSticky
                class={styles.theSticky}
                position="top"
                onBarHeight={(height: any) => {
                  state.heightV = Math.floor(height)
                }}
              >
                <ColHeader
                  background={background.value}
                  border={false}
                  isFixed={false}
                  hideHeader={route.query.taId ? true : false}
                  // color={color.value}
                  // backIconColor="white"
                >
                  {{
                    right: () =>
                      baseState.platformType === 'TEACHER' && (
                        <div
                          class={styles.changeSubjectSection}
                          onClick={() => {
                            state.subjectStatus = true
                          }}
                        >
                          <span class={styles.subjectName}>
                            {state.teacherSubjectName}
                          </span>
                          <img
                            class={state.subjectStatus && styles.active}
                            src={iconArrow}
                          />
                        </div>
                      )
                  }}
                </ColHeader>
              </TheSticky>

              {/* <img class={styles.bgImg} src={state.details?.coverImg} /> */}
              <div class={styles.musicContent}></div>
              <div class={styles.bg}>
                <div class={styles.alumWrap}>
                  {isSingleAlbum.value ? (
                    <div class={styles.singleAlbum}>
                      <div class={styles.img}>
                        {state.details?.buyTimesFlag && (
                          <span class={styles.quota}>
                            限购:{state.details?.buyedTimes}/
                            {state.details?.buyTimes}次
                          </span>
                        )}
                        <Image
                          class={styles.image}
                          width="100%"
                          height="100%"
                          fit="cover"
                          src={state.details?.coverImg || iconAlbumCover}
                          errorIcon={iconAlbumCover}
                        />
                        <div class={styles.iconPian}></div>
                      </div>
                    </div>
                  ) : (
                    state.albumList &&
                    state.albumList.length > 0 && (
                      <Swiper
                        initialSlide={state.initialSlide}
                        watchSlidesProgress={true}
                        slidesPerView={'auto'}
                        centeredSlides={true}
                        modules={[Pagination]}
                        pagination={{ clickable: true }}
                        onSlideChange={(swiper: any) => {
                          if(state.initLoadPage) return
                          params.subjectId = null
                          params.keyword = null
                          params.level = ''
                          params.type = ''
                          params.courseTypeCode = ''
                          searchObj.value = {
                            COURSEWARE: {},
                            SUBJECT: {},
                            MUSIC: {},
                            ENSEMBLE: {}
                          }
                          state.details = state.albumList[swiper.activeIndex]
                          // 等tab渲染完了之后再切换 不然tab会自动重新赋值
                          nextTick(async() => {
                            // 当有初始值的时候不刷新
                            // if (state.initialSlide) {
                            //   state.initialSlide = 0
                            //   return
                            // }
                            handleChangeActiveTab()
                            // console.log(tabsRef.value, state.activeTab)
                            tabsRef.value && tabsRef.value.resize()
                            // console.log(state.activeTab, 'activeTab')
                            activeTypeParams()
                            params.page = 1
                            state.list = []
                            await FetchList(true)
                          })
                        }}
                      >
                        {state.albumList.map((album: any) => (
                          <SwiperSlide>
                            <div class={styles.img}>
                              {album.buyTimesFlag && (
                                <span class={styles.quota}>
                                  限购{album.buyedTimes}/{album.buyTimes}次
                                </span>
                              )}
                              <Image
                                class={styles.image}
                                width="100%"
                                height="100%"
                                fit="cover"
                                src={album?.coverImg || iconAlbumCover}
                                errorIcon={iconAlbumCover}
                              />
                              <div class={styles.iconPian}></div>
                            </div>
                          </SwiperSlide>
                        ))}
                      </Swiper>
                    )
                  )}

                  <div class={styles.alumDes}>
                    <div class={[styles.alumTitle, 'van-ellipsis']}>
                      {state.details?.name}
                    </div>
                    <div
                      class={[styles.des, 'van-multi-ellipsis--l2']}
                      style={{
                        height: '32px',
                        lineHeight: '16px'
                      }}
                    >
                      {state.details?.describe}
                    </div>
                  </div>

                  {state.buy != '1' && baseState.platformType === 'STUDENT' && (
                    <div class={styles.albumPriceGroup}>
                      <div class={styles.albumTimer}>
                        <img src={iconTimer} class={styles.iconTimer} />
                        <span>有效期：{state.details?.purchaseNum || 0}天</span>
                      </div>
                      <div class={styles.albumPriceList}>
                        {(state.details?.originalPrice || 0) >
                          (state.details?.actualPrice || 0) && (
                          <del class={styles.originPrice}>
                            原价：¥
                            {moneyFormat(state.details?.originalPrice || 0)}
                          </del>
                        )}

                        <span class={styles.currentPrice}>
                          <span>
                            ¥{moneyFormat(state.details?.actualPrice || 0)}
                          </span>
                        </span>
                      </div>
                    </div>
                  )}
                </div>
              </div>

              <div class={[styles.musicList, 'musicList']}>
                <Sticky position="top" offsetTop={state.heightV}>
                  <Tabs
                    color="var(--van-primary)"
                    background="transparent"
                    lineWidth={20}
                    shrink
                    ref={tabsRef}
                    v-model:active={state.activeTab}
                    onClick-tab={val => {
                      params.subjectId = null
                      params.keyword = null
                      params.level = ''
                      params.type = ''
                      params.courseTypeCode = ''

                      state.activeTab = val.name
                      activeTypeParams()
                      params.page = 1
                      state.list = []
                      FetchList()
                    }}
                  >
                    {!state.showLoading && <>
                      {state.coursewareCounts && (
                        <Tab title="云课堂" name="COURSEWARE"></Tab>
                      )}
                      {state.subjectCounts && (
                        <Tab title="基础云练" name="SUBJECT"></Tab>
                      )}
                      {state.musicCounts && (
                        <Tab title="独奏云练" name="MUSIC"></Tab>
                      )}
                      {state.ensembleCounts && (
                        <Tab title="合奏云练" name="ENSEMBLE"></Tab>
                      )}</>}
                  </Tabs>
                  <Search
                    modelValue={params.keyword}
                    onInput={(val: any) => {
                      params.keyword = val
                    }}
                    placeholder={
                      state.activeTab === 'COURSEWARE'
                        ? '请输入教材关键词'
                        : '请输入曲谱关键词'
                    }
                    class={styles.search}
                    onSearch={onSearch}
                    type="tenant"
                    v-slots={{
                      left: () =>
                        isSearchStatus.value && state.activeTab !== 'COURSEWARE' && (
                          <DropdownMenu zIndex={2999}>
                              <DropdownItem
                                onOpen={() => {
                                  const targetElement: any =
                                    document.querySelector('.musicList')
                                  const targetPosition =
                                    targetElement.getBoundingClientRect().top +
                                    window.scrollY

                                  window.scrollTo({
                                    top: targetPosition - state.heightV + 1
                                  })
                                }}
                                teleport="body"
                                titleClass={
                                  params.subjectId ||
                                  params.type ||
                                  params.level
                                    ? styles.titleActive
                                    : ''
                                }
                                title="筛选"
                                ref={searchRef}
                              >
                                <div
                                  class={styles.searchResult}
                                  style={{
                                    maxHeight: '45vh',
                                    overflowY: 'auto'
                                  }}
                                >
                                  {searchObj.value[state.activeTab].subjects &&
                                    searchObj.value[state.activeTab].subjects
                                      .length > 0 && (
                                      <>
                                        <div class={styles.searchTitle}>
                                          声部
                                        </div>
                                        <div
                                          class={[
                                            styles['radio-group'],
                                            styles.radio,
                                            styles['organ-radio']
                                          ]}
                                        >
                                          {searchObj.value[
                                            state.activeTab
                                          ].subjects.map((subject: any) => {
                                            const isActive =
                                              subject.id === params.subjectId
                                            const type = isActive
                                              ? 'primary'
                                              : 'default'
                                            return (
                                              <Tag
                                                size="large"
                                                plain={isActive}
                                                type={type}
                                                round
                                                onClick={() => {
                                                  params.subjectId = subject.id
                                                }}
                                              >
                                                {subject.name}
                                              </Tag>
                                            )
                                          })}
                                        </div>
                                      </>
                                    )}
                                  {searchObj.value[state.activeTab].levelList &&
                                    searchObj.value[state.activeTab].levelList
                                      .length > 0 && (
                                      <>
                                        <div class={styles.searchTitle}>
                                          级别
                                        </div>
                                        <div
                                          class={[
                                            styles['radio-group'],
                                            styles.radio,
                                            styles['organ-radio']
                                          ]}
                                        >
                                          {searchObj.value[
                                            state.activeTab
                                          ].levelList.map((subject: any) => {
                                            const isActive =
                                              subject.id === params.level
                                            const type = isActive
                                              ? 'primary'
                                              : 'default'
                                            return (
                                              <Tag
                                                size="large"
                                                plain={isActive}
                                                type={type}
                                                round
                                                onClick={() => {
                                                  params.level = subject.id
                                                }}
                                              >
                                                {subject.value}
                                              </Tag>
                                            )
                                          })}
                                        </div>
                                      </>
                                    )}
                                  {searchObj.value[state.activeTab].typeList &&
                                    searchObj.value[state.activeTab].typeList
                                      .length > 0 && (
                                      <>
                                        <div class={styles.searchTitle}>
                                          类型
                                        </div>
                                        <div
                                          class={[
                                            styles['radio-group'],
                                            styles.radio,
                                            styles['organ-radio']
                                          ]}
                                        >
                                          {searchObj.value[
                                            state.activeTab
                                          ].typeList.map((subject: any) => {
                                            const isActive =
                                              subject.id === params.type
                                            const type = isActive
                                              ? 'primary'
                                              : 'default'
                                            return (
                                              <Tag
                                                size="large"
                                                plain={isActive}
                                                type={type}
                                                round
                                                onClick={() => {
                                                  params.type = subject.id
                                                }}
                                              >
                                                {subject.value}
                                              </Tag>
                                            )
                                          })}
                                        </div>
                                      </>
                                    )}
                                </div>

                                <div class={[styles.btnGroup2,  'btnMore']}>
                                  <Button
                                    class={styles.resetting}
                                    type="primary"
                                    plain
                                    round
                                    onClick={() => {
                                      params.subjectId = null
                                      params.level = ''
                                      params.type = ''
                                    }}
                                  >
                                    重置
                                  </Button>

                                  <Button
                                    class={styles.confirm}
                                    type="primary"
                                    color="linear-gradient( 270deg, #FF204B 0%, #FE5B71 100%)"
                                    round
                                    block
                                    onClick={() => {
                                      onSearch(params.keyword)
                                      searchRef.value?.toggle()
                                    }}
                                  >
                                    确定
                                  </Button>
                                </div>
                              </DropdownItem>
                            
                          </DropdownMenu>
                        )
                    }}
                  />
                </Sticky>

                <div
                  class={[
                    styles.alumnList,
                    state.activeTab === 'COURSEWARE'
                      ? styles.alumnListCourseware
                      : ''
                  ]}
                >
                  <List
                    loading={state.loading}
                    finished={state.finished}
                    finished-text={' '}
                    onLoad={FetchList}
                    immediateCheck={false}
                    error={state.isError}
                  >
                    {state.list && state.list.length ? (
                      state.activeTab === 'COURSEWARE' ? (
                        <CourseItem
                          list={state.list.map(item => {
                            return {
                              name: item.musicSheetName,
                              coverImg: item.titleImg,
                              id: item.id
                            }
                          })}
                          onItemClick={row => {
                            sessionStorage.setItem(
                              'tool-subject-type',
                              JSON.stringify({
                                activeTab: state.activeTab,
                                tenantGroupAlbumId:
                                  baseState.platformType === 'STUDENT'
                                    ? state.details.tenantGroupAlbumId
                                    : state.details.id, // 老师用专辑id当唯一值
                                level: params.level,
                                type: params.type,
                                subjectId: params.type,
                                keyword: params.keyword
                              })
                            )
                            router.push({
                              path: '/courseList',
                              query: {
                                id: row.id,
                                albumId: state.details.id,
                                taId: state.details.tenantGroupAlbumId, // 当通过我的曲目进来的时候 这个值为空
                                buyStatus: state.hasBuyStatus ? '0' : '1' //默认能购买
                              }
                            })
                          }}
                        />
                      ) : (
                        <Song
                          showNumber
                          list={state.list}
                          onDetail={(item: any) => {
                            sessionStorage.setItem(
                              'tool-subject-type',
                              JSON.stringify({
                                activeTab: state.activeTab,
                                tenantGroupAlbumId:
                                  baseState.platformType === 'STUDENT'
                                    ? state.details.tenantGroupAlbumId
                                    : state.details.id, // 老师用专辑id当唯一值
                                level: params.level,
                                type: params.type,
                                subjectId: params.type,
                                keyword: params.keyword
                              })
                            )
                            router.push({
                              path: '/music-detail',
                              query: {
                                id: item.id,
                                tenantAlbumId: item.tenantAlbumId,
                                taId: state.details.tenantGroupAlbumId, // 当通过我的曲目进来的时候 这个值为空
                                buyStatus: state.hasBuyStatus ? '0' : '1' //默认能购买
                              }
                            })
                          }}
                        />
                      )
                    ) : (
                      !state.loading && (
                        <ColResult
                          tips={
                            state.activeTab === 'COURSEWARE'
                              ? '暂无教材'
                              : '暂无曲目'
                          }
                          classImgSize="SMALL"
                          btnStatus={false}
                        />
                      )
                    )}
                  </List>
                </div>
              </div>
              {baseState.platformType === 'STUDENT' && state.buy != '1' && (
                <TheSticky
                  position="bottom"
                  varName="--bottom-train-tool-height"
                >
                  <div class={styles.btnGroup}>
                    <Button
                      round
                      block
                      disabled={!state.hasBuyStatus}
                      color="linear-gradient(270deg, #FF204B 0%, #FE5B71 100%)"
                      onClick={onSubmit}
                    >
                      开通训练教程
                    </Button>
                  </div>
                </TheSticky>
              )}
            </>
          )
        )}

        {/* 选择声部 */}
        <Popup
          show={state.subjectStatus}
          position="bottom"
          round
          safe-area-inset-bottom
          onClose={() => (state.subjectStatus = false)}
          onClosed={() => (state.openStatus = false)}
        >
          <Picker
            defaultIndex={state.teacherSubjectIndex}
            columns={state.subjectList}
            confirmButtonText="确定"
            onCancel={() => {
              state.subjectStatus = false
            }}
            onConfirm={(val: any) => {params.keyword = null
              params.level = ''
              params.type = ''
              params.courseTypeCode = ''
              searchObj.value = {
                COURSEWARE: {},
                SUBJECT: {},
                MUSIC: {},
                ENSEMBLE: {}
              }
              state.teacherSubjectId = val.id
              state.teacherSubjectName = val.name
              params.page = 1
              state.finished = false
              state.list = []

              activeTypeParams()

              FetchList()
              state.subjectStatus = false

              operatoinCatchSubjectInfo('set', {
                defaultSubject: state.teacherSubjectId,
                defaultSubjectName: state.teacherSubjectName,
                userId: state.userId
              })
            }}
          ></Picker>
        </Popup>
      </div>
    )
  }
})
