import { defineComponent, nextTick, onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import request from '@/helpers/request'
import ColHeader from '@/components/col-header'
import { postMessage } from '@/helpers/native-message'
import { Button, Icon, Image, List, NavBar, Sticky } from 'vant'
// import classNames from 'classnames'
// import Footer from '../album/footer'
// import FavoriteIcon from '../album/favorite.svg'
// import FavoritedIcon from '../album/favorited.svg'
import styles from './index.module.less'
// import Item from '../list/item'
import { useRect } from '@vant/use'
import { useEventListener, useWindowScroll } from '@vueuse/core'
import { getRandomKey, musicBuy } from '../music'
import { state } from '@/state'
import IconPan from './pan.png'
import oStart from './oStart.png'
import iStart from './iStart.png'
import Title from '../component/title'
import Song from '../component/song'
import ColResult from '@/components/col-result'
import MusicGrid from '../component/music-grid'
import { useEventTracking } from '@/helpers/hooks'

const noop = () => {}

export default defineComponent({
  name: 'AlbumDetail',
  props: {
    onItemClick: {
      type: Function,
      default: noop
    }
  },
  setup({ onItemClick }) {
    localStorage.setItem('behaviorId', getRandomKey())
    const router = useRouter()
    const params = reactive({
      search: '',
      relatedNum: 6, //相关专辑数
      page: 1,
      rows: 200
    })
    const albumDetail = ref<any>(null)
    // const data = ref<any>(null)
    const rows = ref<any[]>([])
    const loading = ref(false)
    // const finished = ref(false)
    const isError = ref(false)
    const favorited = ref(0)
    const albumFavoriteCount = ref(0)
    const headers = ref(null)
    const background = ref<string>('rgba(55, 205, 177, 0)')
    const color = ref<string>('#fff')
    const heightInfo = ref<any>('auto')

    const route = useRoute()
    const FetchList = async (id?: any) => {
      if (loading.value) {
        return
      }
      loading.value = true
      isError.value = false
      try {
        const res = await request.post('/music/album/detail', {
          prefix:
            state.platformType === 'TEACHER' ? '/api-teacher' : '/api-student',
          data: { id: id || route.params.id, ...params }
        })
        const { musicSheetList, ...rest } = res.data
        rows.value = [...musicSheetList.rows]
        const musicTagNames = rest?.musicTagNames?.split(',') || []
        albumDetail.value = {
          ...rest,
          musicTagNames
        }
        favorited.value = rest.favorite
        albumFavoriteCount.value = rest.albumFavoriteCount
      } catch (error) {
        isError.value = true
      }
      loading.value = false
    }

    const favoriteLoading = ref(false)

    onMounted(() => {
      FetchList()
      useEventListener(document, 'scroll', evt => {
        const { y } = useWindowScroll()
        if (y.value > 20) {
          background.value = `rgba(255, 255, 255)`
          color.value = 'black'
          postMessage({
            api: 'backIconChange',
            content: { iconStyle: 'black' }
          })
        } else {
          background.value = 'transparent'
          color.value = '#fff'
          postMessage({
            api: 'backIconChange',
            content: { iconStyle: 'white' }
          })
        }
      })

      useEventTracking('专辑')
    })

    const toggleFavorite = async (id: number) => {
      favoriteLoading.value = true
      try {
        await request.post('/music/album/favorite/' + id, {
          prefix:
            state.platformType === 'TEACHER' ? '/api-teacher' : '/api-student'
        })
        favorited.value = favorited.value === 1 ? 0 : 1
        albumFavoriteCount.value += favorited.value ? 1 : -1
      } catch (error) {}
      favoriteLoading.value = false
    }

    return () => {
      return (
        <div class={styles.detail}>
          <div ref={headers}>
            <ColHeader
              background={background.value}
              border={false}
              color={color.value}
              backIconColor="white"
              onHeaderBack={() => {
                nextTick(() => {
                  const { height } = useRect(headers as any)
                  heightInfo.value = height
                })
              }}
            />
          </div>
          <img class={styles.bgImg} src={albumDetail.value?.albumCoverUrl} />
          <div class={styles.musicContent}></div>
          <div class={styles.bg}>
            <div class={styles.alumWrap}>
              <div class={styles.img}>
                <Image
                  class={styles.image}
                  width="100%"
                  height="100%"
                  fit="cover"
                  src={albumDetail.value?.albumCoverUrl}
                />
              </div>
              <div class={styles.alumDes}>
                <div class={[styles.alumTitle, 'van-ellipsis']}>
                  {albumDetail.value?.albumName}
                </div>
                <div class={styles.tags}>
                  {albumDetail.value?.musicTagNames?.map((tag: any) => (
                    <span class={styles.tag}>{tag}</span>
                  ))}
                </div>
                <div
                  class={[styles.des, 'van-multi-ellipsis--l3']}
                  style={{
                    height: '48px',
                    lineHeight: '16px'
                  }}
                >
                  {albumDetail.value?.albumDesc}
                </div>
              </div>
            </div>
            <div class={styles.alumCollect}>
              <img src={IconPan} />
              <span>共{albumDetail.value?.musicSheetCount}首曲目{state.platformType}</span>
              <div
                  class={styles.right}
                  onClick={() => toggleFavorite(albumDetail.value?.id)}
                >
                  <img src={favorited.value ? iStart : oStart} />
                  <span>{albumFavoriteCount.value}人收藏</span>
                </div>
            </div>
          </div>
          <div class={styles.alumnContainer}>
            <div class={styles.alumnList}>
              <Title title="曲目列表" isMore={false} />
              <Song
                list={rows.value}
                onDetail={(item: any) => {
                  if (onItemClick === noop || !onItemClick) {
                    musicBuy(item, () => {}, {
                      albumId: route.params.id,
                      albumName: albumDetail.value?.albumName
                    })
                  } else {
                    onItemClick(item)
                  }
                }}
              />

              {rows.value && rows.value.length <= 0 && (
                <ColResult btnStatus={false} tips="暂无曲目" />
              )}
            </div>

            {albumDetail.value?.relatedMusicAlbum &&
              albumDetail.value?.relatedMusicAlbum.length > 0 && (
                <>
                  <Title
                    title="相关专辑"
                    onMore={() => {
                      router.push({
                        path: '/music-album'
                      })
                    }}
                  />

                  <MusicGrid
                    list={albumDetail.value?.relatedMusicAlbum}
                    onGoto={(n: any) => {
                      router
                        .push({
                          name: 'music-album-detail',
                          params: {
                            id: n.id
                          }
                        })
                        .then(() => {
                          FetchList(n.id)
                          window.scrollTo(0, 0)
                        })
                    }}
                  />
                </>
              )}
          </div>
        </div>
      )
    }
  }
})
