import { defineComponent, nextTick, onMounted, reactive, ref } from 'vue'
import { useRoute } from 'vue-router'
import request from '@/helpers/request'
import ColHeader from '@/components/col-header'
import { Button, Icon, Image, List, 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 { getRandomKey, musicBuy } from '../music'

const noop = () => {}

export default defineComponent({
  name: 'AlbumDetail',
  props: {
    onItemClick: {
      type: Function,
      default: noop
    }
  },
  setup({ onItemClick }) {
    localStorage.setItem('behaviorId', getRandomKey())
    const params = reactive({
      search: '',
      page: 1
    })
    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)
    let heights = ref(0)

    const route = useRoute()
    const FetchList = async () => {
      if (loading.value) {
        return
      }
      loading.value = true
      isError.value = false
      try {
        const res = await request.post('/api-student/music/album/detail', {
          data: { id: route.params.id, ...params }
        })
        const { musicSheetList, ...rest } = res.data
        rows.value = [...rows.value, ...musicSheetList.rows]
        albumDetail.value = rest
        data.value = musicSheetList
        params.page = musicSheetList.pageNo + 1
        finished.value = musicSheetList.pageNo >= musicSheetList.totalPage
        favorited.value = rest.favorite
        albumFavoriteCount.value = rest.albumFavoriteCount
      } catch (error) {
        isError.value = true
      }
      loading.value = false
    }

    const favoriteLoading = ref(false)

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

    onMounted(() => {
      nextTick(() => {
        setTimeout(() => {
          const { height } = useRect(headers as any)
          console.log(height, 'height')
          heights.value = height
        }, 100)
      })
    })

    return () => {
      // console.log(albumFavoriteCount.value)
      return (
        <div class={styles.detail}>
          <Sticky
            class={[styles.base, 'sticky']}
            style={{
              height: heights.value + 'px !important',
              width: '100%'
            }}
          >
            <div ref={headers}>
              <ColHeader
                class={styles.header}
                background="transparent"
                color="#fff"
                title="专辑详情"
                backIconColor="white"
                border={false}
                isFixed={false}
              />
              <div class={styles.detailContent}>
                <div class={classNames(styles.main, 'van-hairline--bottom')}>
                  <Image
                    class={styles.img}
                    src={albumDetail.value?.albumCoverUrl}
                  />
                  <div class={styles.content}>
                    <h4 class="van-ellipsis">{albumDetail.value?.albumName}</h4>
                    <p class="van-multi-ellipsis--l2">
                      {albumDetail.value?.albumDesc}
                    </p>
                  </div>
                </div>
                <div class={styles.footerBar}>
                  <Footer
                    musicSheetCount={albumDetail.value?.musicSheetCount}
                    albumFavoriteCount={albumFavoriteCount.value}
                  />
                  <Button
                    class={styles.favoriteContaineer}
                    loading={favoriteLoading.value}
                    onClick={() => toggleFavorite(albumDetail.value?.id)}
                  >
                    <Icon
                      key={favorited.value}
                      class={styles.favorite}
                      name={favorited.value ? FavoritedIcon : FavoriteIcon}
                    />{' '}
                    <span>{favorited.value ? '已' : ''}收藏</span>
                  </Button>
                </div>
              </div>
            </div>
          </Sticky>
          <List
            loading={loading.value}
            finished={finished.value}
            finished-text="没有更多了"
            onLoad={FetchList}
          >
            {rows.value.length
              ? rows.value.map(item => (
                  <Item
                    data={item}
                    onClick={() => {
                      if (onItemClick === noop || !onItemClick) {
                        musicBuy(item)
                      } else {
                        onItemClick(item)
                      }
                    }}
                  />
                ))
              : null}
          </List>
        </div>
      )
    }
  }
})
