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, Dialog, Icon, Image, List, NavBar, Popup, Sticky } from 'vant'
import styles from './index.module.less'
import { useRect } from '@vant/use'
import { useEventListener, useWindowScroll } from '@vueuse/core'
import { getRandomKey } from '@/views/music/music'
import IconPan from './pan.png'
import oStart from './oStart.png'
import iStart from './iStart.png'
import Title from '@/views/music/component/title'
import Song from '@/views/music/component/song'
import ColResult from '@/components/col-result'
import MusicGrid from '@/views/music/component/music-grid'
import ColSticky from '@/components/col-sticky'
import { browser, moneyFormat } from '@/helpers/utils'
import { initJumpNativePage, shareCall } from '../share'
import wxImage from '../images/wx_bg.png'
import qs from 'query-string'

export default defineComponent({
  name: 'AlbumDetail',
  setup() {
    localStorage.setItem('behaviorId', getRandomKey())
    const router = useRouter()
    const route = useRoute()
    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 tmpUrl = `${location.origin}/${
      route.query.p == 'tenant' ? 'tenant.html' : 'student/'
    }#/music-album-detail/${route.query.id}?${qs.stringify(route.query)}`

    console.log(tmpUrl, 'tmpUrl')
    const jumpUrl = ref<string>(tmpUrl)

    const FetchList = async (id?: any) => {
      if (loading.value) {
        return
      }
      loading.value = true
      isError.value = false
      try {
        const res = await request.post('/api-teacher/open/albumShareProfit', {
          data: { bizId: id || route.query.id, userId: route.query.recomUserId }
        })
        const { musicSheetList, ...rest } = res.data.musicAlbum
        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
    }

    onMounted(() => {
      console.log(jumpUrl.value)
      initJumpNativePage(jumpUrl.value)
      FetchList()
      useEventListener(document, 'scroll', evt => {
        const { y } = useWindowScroll()
        if (y.value > 20) {
          background.value = `rgba(255, 255, 255)`
          color.value = 'black'
        } else {
          background.value = 'transparent'
          color.value = '#fff'
        }
      })
    })

    const wxStatus = ref<boolean>(false)
    const onShare = () => {
      console.log(browser().weixin)
      if (browser().weixin) {
        wxStatus.value = true
        return
      }
      // 尝试拉起app
      shareCall(jumpUrl.value)
      // 不管有没有拉起app则都跳转到下载app
      setTimeout(() => {
        window.location.href = location.origin + '/student/#/download'
      }, 3000)
    }

    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}>
                {albumDetail.value?.paymentType === 'CHARGE' && (
                  <span class={styles.albumType}>付费</span>
                )}
                <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}首曲目</span>
              <div class={styles.right}>
                <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} showPlay={false} />

              {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}
                  />
                </>
              )} */}
          </div>

          <ColSticky position="bottom" background="white">
            <div class={['btnGroup']} style={{ paddingTop: '12px' }}>
              <Button
                block
                round
                type="primary"
                onClick={onShare}
                color="linear-gradient(220deg, #DFA164 0%, #FAC87E 100%)"
              >
                下载小酷Ai开始练习吧！
              </Button>
            </div>
          </ColSticky>

          {wxStatus.value && (
            <div
              class={styles.wxpopup}
              onClick={() => {
                wxStatus.value = false
              }}
            >
              <img src={wxImage} alt="" />
            </div>
          )}
        </div>
      )
    }
  }
})
