import { defineComponent, nextTick, onMounted, reactive, ref } from 'vue'
import { List, DropdownMenu, DropdownItem, Tag, Sticky, Button } from 'vant'
import Search from '@/components/col-search'
import request from '@/helpers/request'
import { useRoute, useRouter } from 'vue-router'
import ColResult from '@/components/col-result'
import styles from './index.module.less'
import { getRandomKey } from '../music'
import { openDefaultWebView, state as baseState } from '@/state'
import { SubjectEnum, useSubjectId } from '@/helpers/hooks'
import Song from '../component/song'
import ColHeader from '@/components/col-header'
import bgImg from '../../images/bg-image.png'
import TheSticky from '@/components/the-sticky'

const noop = () => {
  //
}

export default defineComponent({
  name: 'MusicList',
  props: {
    teacherId: {
      type: String || Number,
      default: ''
    },
    myself: {
      type: Boolean,
      default: false
    }
  },
  setup({ onItemClick }, { expose }) {
    localStorage.setItem('behaviorId', getRandomKey())
    const route = useRoute()
    const router = useRouter()
    //

    const subjectType = route.query.subjectType || ''
    let title = ''
    if (subjectType === 'SUBJECT') {
      title = '声部练习'
    } else if (subjectType === 'MUSIC') {
      title = '独奏曲目'
    } else if (subjectType === 'ENSEMBLE') {
      title = '合奏练习'
    }
    const params = reactive({
      search: (route.query.search as string) || '',
      subjectType: subjectType,
      page: 1,
      subjectId: null,
      level: '',
      type: '',
      title: title
    })
    const data = ref<any>(null)
    const loading = ref(false)
    const finished = ref(false)
    const isError = ref(false)
    const searchObj = ref<any>({})
    const searchRef = ref()

    const apiSuffix = ref(
      baseState.platformType === 'STUDENT' ? '/api-student' : '/api-teacher'
    )

    const onSearch = (value: string) => {
      params.page = 1
      params.search = value
      data.value = null
      FetchList()
    }

    const FetchList = async () => {
      loading.value = true
      isError.value = false
      const tempParams = {
        ...params
      }

      try {
        const res = await request.post(
          `${apiSuffix.value}/tenantAlbumMusic/page`,
          {
            data: tempParams
          }
        )
        if (data.value) {
          const result = (data.value?.rows || []).concat(res.data.rows || [])
          data.value.rows = result
        }
        data.value = data.value || res.data
        params.page = res.data.pageNo + 1
        finished.value = res.data.pageNo >= res.data.totalPage
      } catch (error) {
        isError.value = true
      }
      loading.value = false
    }

    const getSelectCondition = async () => {
      const { data } = await request.post(
        `${apiSuffix.value}/tenantAlbumMusic/selectCondition`,
        {
          data: {
            subjectType: params.subjectType
          }
        }
      )
      searchObj.value = data || {}
    }

    onMounted(async () => {
      // SUBJECT: '声部练习',
      // MUSIC: '独奏曲目',
      // ENSEMBLE: '合奏练习'
      loading.value = true
      await getSelectCondition()
      await FetchList()
    })

    return () => {
      return (
        <>
          <div class={styles.sticky}>
            <TheSticky>
              <ColHeader
                background="transparent"
                isFixed={false}
                border={false}
                title={title}
                color="#131415"
              />
              <Search
                onSearch={onSearch}
                type="tenant"
                background="transparent"
                inputBackground="transparent"
                // leftIcon={iconSearch}
                v-slots={{
                  left: () => (
                    <DropdownMenu>
                      <DropdownItem
                        titleClass={
                          params.subjectId || params.type || params.level
                            ? styles.titleActive
                            : ''
                        }
                        title="筛选"
                        ref={searchRef}
                      >
                        <div
                          class={styles.searchResult}
                          style={{ maxHeight: '45vh', overflowY: 'auto' }}
                        >
                          {searchObj.value.subjects &&
                            searchObj.value.subjects.length > 0 && (
                              <>
                                <div class={styles.searchTitle}>声部</div>
                                <div
                                  class={[
                                    styles['radio-group'],
                                    styles.radio,
                                    styles['organ-radio']
                                  ]}
                                >
                                  {searchObj.value.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.levels &&
                            searchObj.value.levels.length > 0 && (
                              <>
                                <div class={styles.searchTitle}>级别</div>
                                <div
                                  class={[
                                    styles['radio-group'],
                                    styles.radio,
                                    styles['organ-radio']
                                  ]}
                                >
                                  {searchObj.value.levels.map(
                                    (subject: any) => {
                                      const isActive = subject === params.level
                                      const type = isActive
                                        ? 'primary'
                                        : 'default'
                                      return (
                                        <Tag
                                          size="large"
                                          plain={isActive}
                                          type={type}
                                          round
                                          onClick={() => {
                                            params.level = subject
                                          }}
                                        >
                                          {subject}
                                        </Tag>
                                      )
                                    }
                                  )}
                                </div>
                              </>
                            )}
                          {searchObj.value.types &&
                            searchObj.value.types.length > 0 && (
                              <>
                                <div class={styles.searchTitle}>类型</div>
                                <div
                                  class={[
                                    styles['radio-group'],
                                    styles.radio,
                                    styles['organ-radio']
                                  ]}
                                >
                                  {searchObj.value.types.map((subject: any) => {
                                    const isActive = subject === params.type
                                    const type = isActive
                                      ? 'primary'
                                      : 'default'
                                    return (
                                      <Tag
                                        size="large"
                                        plain={isActive}
                                        type={type}
                                        round
                                        onClick={() => {
                                          params.type = subject
                                        }}
                                      >
                                        {subject}
                                      </Tag>
                                    )
                                  })}
                                </div>
                              </>
                            )}
                        </div>

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

                          <Button
                            type="primary"
                            round
                            block
                            onClick={() => {
                              onSearch('')
                              searchRef.value?.toggle()
                            }}
                          >
                            确 认
                          </Button>
                        </div>
                      </DropdownItem>
                    </DropdownMenu>
                  )
                }}
              />
            </TheSticky>
            <img class={styles.bgImg} src={bgImg} />
          </div>

          <div class={styles.alumnList}>
            <List
              // loading={loading.value}
              finished={finished.value}
              finished-text={data.value && data.value.rows.length ? '' : ''}
              onLoad={FetchList}
              error={isError.value}
              immediateCheck={false}
            >
              {data.value && data.value.rows.length ? (
                <Song
                  showTitleImg
                  list={data.value.rows}
                  onDetail={(item: any) => {
                    if (onItemClick === noop) {
                      const url =
                        location.origin +
                        location.pathname +
                        '#/music-detail?id=' +
                        item.id
                      openDefaultWebView(url, () => {
                        router.push({
                          path: '/music-detail',
                          query: {
                            id: item.id
                          }
                        })
                      })
                    } else {
                      onItemClick?.(item)
                    }
                  }}
                />
              ) : (
                !loading.value && (
                  <ColResult
                    tips="暂无曲目"
                    classImgSize="SMALL"
                    btnStatus={false}
                  />
                )
              )}
            </List>
          </div>

          {/* 声部弹框 */}
          {/* <Popup
            show={subject.show}
            position="bottom"
            round
            closeable
            safe-area-inset-bottom
            onClose={() => (subject.show = false)}
            onClosed={() => (subject.show = false)}
          >
            <SelectSubject
              type="MUSIC"
              searchParams={
                baseState.platformType === 'TEACHER'
                  ? teacherDetaultSubject.value
                  : subject
              }
              onComfirm={onComfirmSubject}
            />
          </Popup> */}
        </>
      )
    }
  }
})
