import { defineComponent, reactive, ref } from 'vue'
import { Sticky, List, Popup } from 'vant'
import Search from '@/components/col-search'
import request from '@/helpers/request'
import Item from './item'
import SelectTag from '../search/select-tag'
import { useRoute, useRouter } from 'vue-router'
import ColResult from '@/components/col-result'
import styles from './index.module.less'
import { getRandomKey, musicBuy } from '../music'
import { state } from '@/state'

const noop = () => {}

export default defineComponent({
  name: 'MusicList',
  props: {
    hideSearch: {
      type: Boolean,
      default: false
    },
    defauleParams: {
      type: Object,
      default: () => ({})
    },
    onItemClick: {
      type: Function,
      default: noop
    },
    teacherId: {
      type: String || Number,
      default: ''
    }
  },
  setup({ hideSearch, defauleParams, onItemClick, teacherId }, { expose }) {
    localStorage.setItem('behaviorId', getRandomKey())
    const route = useRoute()
    // const router = useRouter()
    const tempParams: any = {}
    if (state.version) {
      tempParams.version = state.version || '' // 处理ios审核版本
      tempParams.platform = 'ios-student'
    }
    const params = reactive({
      search: (route.query.search as string) || '',
      musicTagIds: route.query.tagids || '',
      page: 1,
      ...tempParams,
      ...defauleParams
    })
    const data = ref<any>(null)
    const loading = ref(false)
    const finished = ref(false)
    const isError = ref(false)
    const tagVisibility = ref(false)

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

    const FetchList = async () => {
      if (loading.value) {
        return
      }
      loading.value = true
      isError.value = false
      try {
        const res = await request.post('/api-student/music/sheet/list', {
          data: {
            ...params,
            idAndName: params.search,
            createBy: teacherId
          }
        })
        if (data.value) {
          let 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 onComfirm = tags => {
      const d = Object.values(tags).flat().filter(Boolean).join(',')
      params.musicTagIds = d
      params.page = 1
      data.value = null
      FetchList()
      tagVisibility.value = false
    }

    expose({
      onSearch,
      onComfirm
    })

    return () => (
      <>
        <List
          loading={loading.value}
          finished={finished.value}
          finished-text={
            data.value && data.value.rows.length ? '没有更多了' : ''
          }
          onLoad={FetchList}
          error={isError.value}
        >
          {!hideSearch && (
            <Sticky class={styles.sticky}>
              <Search
                showAction
                onSearch={onSearch}
                onFilter={() => (tagVisibility.value = true)}
                filterDot={!!params.musicTagIds}
              />
            </Sticky>
          )}

          {data.value && data.value.rows.length
            ? data.value.rows.map(item => (
                <Item
                  data={item}
                  onClick={() => {
                    if (onItemClick === noop) {
                      musicBuy(item)
                    } else {
                      onItemClick?.(item)
                    }
                  }}
                />
              ))
            : !loading.value && (
                <ColResult
                  tips="暂无曲目"
                  classImgSize="SMALL"
                  btnStatus={false}
                />
              )}
        </List>
        <Popup
          show={tagVisibility.value}
          round
          closeable
          position="bottom"
          style={{ height: '60%' }}
          teleport="body"
          onUpdate:show={val => (tagVisibility.value = val)}
        >
          <SelectTag
            onConfirm={onComfirm}
            onCancel={() => {}}
            defaultValue={route.query.tagids as string}
          />
        </Popup>
      </>
    )
  }
})
