import {
  computed,
  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, Popup } from 'vant'
import styles from './index.module.less'
import { useRect } from '@vant/use'
import { useEventListener, useWindowScroll } from '@vueuse/core'
import { getRandomKey, musicBuy } from '../music'
import { openDefaultWebView, state } from '@/state'
import IconPan from './icon-pan.png'
import oStart from './icon-hart.png'
import iStart from './icon-hart-active.png'
import Song from '../component/song'
import ColResult from '@/components/col-result'
import MusicGrid from '../component/music-grid'
import { useEventTracking } from '@/helpers/hooks'
import ColSticky from '@/components/col-sticky'
import { moneyFormat } from '@/helpers/utils'
import { orderStatus } from '@/views/order-detail/orderStatus'
import iconShare from '../../images/icon-share.png'
import ColShare from '@/components/col-share'
import SongShare from '../component/song-share'
import icon_music_list from './icon_music_list.png'
import iconMenu from './icon-menu.png'
import TheSticky from '@/components/the-sticky'
import SelectSubject from '../search/select-subject'

const noop = () => {}

export default defineComponent({
  name: 'AlbumDetail',
  props: {
    onItemClick: {
      type: Function,
      default: noop
    }
  },
  setup({ onItemClick }) {
    localStorage.setItem('behaviorId', getRandomKey())
    const router = useRouter()
    const route = useRoute()
    const subjects = reactive({
      name: route.query.subjectName || '全部声部',
      id: route.query.subjectId || null
    })
    const params = reactive({
      search: '',
      relatedNum: 6, //相关专辑数
      page: 1,
      rows: 200
    })
    const albumDetail = ref<any>(null)
    const subjectPopup = ref(false)
    // const data = ref<any>(null)
    const rows = ref<any[]>([])
    const loading = ref(false)
    const aId = Number(route.query.activityId) || 0
    const studentActivityId = ref(aId)
    // const finished = ref(false)
    const isError = ref(false)
    const favorited = ref(0)
    const albumFavoriteCount = ref(0)
    const background = ref<string>('rgba(55, 205, 177, 0)')
    const color = ref<string>('#fff')

    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,
            subjectIds: subjects.id
          }
        })
        const { musicSheetList, ...rest } = res.data
        rows.value = [...musicSheetList.rows]
        const musicTagNames = rest?.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
    }

    const onBuy = async () => {
      const album = albumDetail.value
      orderStatus.orderObject.orderType = 'ALBUM'
      orderStatus.orderObject.orderName = album.albumName
      orderStatus.orderObject.orderDesc = album.albumName
      orderStatus.orderObject.actualPrice = album.albumPrice
      orderStatus.orderObject.recomUserId = route.query.recomUserId || 0
      orderStatus.orderObject.activityId = route.query.activityId || 0
      orderStatus.orderObject.orderNo = ''
      orderStatus.orderObject.orderList = [
        {
          orderType: 'ALBUM',
          goodsName: album.albumName,
          recomUserId: route.query.recomUserId || 0,
          price: album.albumPrice,
          ...album
        }
      ]

      const res = await request.post('/api-student/userOrder/getPendingOrder', {
        data: {
          goodType: 'ALBUM',
          bizId: album.id
        }
      })

      const result = res.data
      if (result) {
        Dialog.confirm({
          title: '提示',
          message: '您有一个未支付的订单，是否继续支付？',
          theme: 'round-button',
          className: 'confirm-button-group',
          cancelButtonText: '取消订单',
          confirmButtonText: '继续支付'
        })
          .then(async () => {
            orderStatus.orderObject.orderNo = result.orderNo
            orderStatus.orderObject.actualPrice = result.actualPrice
            orderStatus.orderObject.discountPrice = result.discountPrice
            routerTo()
          })
          .catch(() => {
            Dialog.close()
            // 只用取消订单，不用做其它处理
            cancelPayment(result.orderNo)
          })
      } else {
        routerTo()
      }
      // this.$router.push({
      //   path: '/orderDetail',
      //   query: {
      //     orderType: 'VIP'
      //   }
      // })
    }
    const routerTo = () => {
      const album = albumDetail.value
      router.push({
        path: '/orderDetail',
        query: {
          orderType: 'ALBUM',
          album: album.id
        }
      })
    }
    const cancelPayment = async (orderNo: string) => {
      try {
        await request.post('/api-student/userOrder/orderCancel', {
          data: {
            orderNo
          }
        })
        // this.routerTo()
      } catch {
        //
      }
    }

    const onComfirmSubject = item => {
      subjects.name = item.name
      subjects.id = item.id
      subjectPopup.value = false
      FetchList()
    }

    const shareStatus = ref<boolean>(false)
    const shareUrl = ref<string>('')
    const shareDiscount = ref<number>(0)
    const onShare = async () => {
      const userId = state.user.data.userId
      const id = route.params.id
      let activityId = 0
      console.log(state.user, userId)
      if (state.platformType === 'TEACHER') {
        const res = await request.post('/api-teacher/open/vipProfit', {
          data: {
            bizId: id,
            userId
          }
        })
        // 如果有会员则显示
        if (buyVip.value) {
          activityId = res.data.activityId || 0
          shareDiscount.value = res.data.discount || 0
        }
      }
      shareUrl.value = `${location.origin}/teacher/#/shareAblum?id=${id}&recomUserId=${userId}&activityId=${activityId}&userType=${state.platformType}&p=tenant`
      // console.log(shareUrl.value, 'shareUrl')
      shareStatus.value = true
    }

    const buyVip = computed(() => {
      const album = albumDetail.value?.musicPaymentTypes
      return album && album.includes('VIP')
    })

    /** 分享曲谱列表, 最大数量2 */
    const shareMusicList = computed(() => {
      return rows.value.length > 2 ? rows.value.slice(0, 2) : rows.value
    })
    return () => {
      return (
        <div class={styles.detail}>
          <TheSticky position="top">
            <ColHeader
              background={background.value}
              border={false}
              isFixed={false}
              color={color.value}
              backIconColor="white"
            />
          </TheSticky>
          <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.des, 'van-multi-ellipsis--l2']}>
                  {albumDetail.value?.albumDesc}
                </div>
                <div class={styles.tags}>
                  {albumDetail.value?.musicTagNames?.map((tag: any) => (
                    <span class={styles.tag}>{tag}</span>
                  ))}
                </div>
              </div>
            </div>
            <div class={styles.alumCollect}>
              <div class={styles.alumCollectItem} onClick={onShare}>
                <Image src={iconShare} />
                <span>分享</span>
              </div>
              <div
                class={styles.alumCollectItem}
                onClick={() =>
                  router.push({
                    path: '/look-album-list',
                    query: {
                      id: route.params.id
                    }
                  })
                }
              >
                <img src={IconPan} />
                <span>相关专辑</span>
              </div>
              <div
                class={styles.alumCollectItem}
                onClick={() => toggleFavorite(albumDetail.value?.id)}
              >
                <img src={favorited.value ? iStart : oStart} />
                <span>{albumFavoriteCount.value}</span>
              </div>
            </div>

            {albumDetail.value?.paymentType === 'CHARGE' &&
              albumDetail.value?.orderStatus !== 'PAID' && (
                <div class={styles.albumTips}>
                  <span>开通会员或购买专辑，即可自由练习该专辑</span>
                  <span class={styles.albumPrice}>
                    ¥{moneyFormat(albumDetail.value?.albumPrice)}
                  </span>
                </div>
              )}
          </div>
          <div class={styles.alumnContainer}>
            <div class={styles.alumnList}>
              {/* <Title title="曲目列表" isMore={false} /> */}
              <div class={styles.alumnTitleSection}>
                <div class={styles.alumnTitle}>
                  <img src={iconMenu} class={styles.iconMenu} />
                  曲目列表{' '}
                  <span>({albumDetail.value?.musicSheetCount || 0})</span>
                </div>
                {albumDetail.value?.albumType === 'CONCERT' && (
                  <div
                    class={[
                      styles.subjectSearch,
                      subjectPopup.value ? styles.active : ''
                    ]}
                    onClick={() => (subjectPopup.value = true)}
                  >
                    {subjects.name}
                  </div>
                )}
              </div>
              <Song
                showNumber
                list={rows.value}
                onDetail={(item: any) => {
                  if (onItemClick === noop || !onItemClick) {
                    const url =
                      location.origin +
                      location.pathname +
                      '#/music-detail?id=' +
                      item.id +
                      '&albumId=' +
                      route.params.id
                    openDefaultWebView(url, () => {
                      router.push({
                        path: '/music-detail',
                        query: {
                          id: item.id,
                          albumId: route.params.id
                        }
                      })
                    })
                  } else {
                    onItemClick(item)
                  }
                }}
              />

              {rows.value && rows.value.length <= 0 && !loading.value && (
                <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>

          {/* 判断是否是收费 是否是已经购买 */}
          {albumDetail.value?.paymentType === 'CHARGE' &&
            albumDetail.value?.orderStatus !== 'PAID' && (
              <ColSticky position="bottom" class={styles.btnStickyBottom}>
                <div
                  class={[
                    'btnGroup',
                    buyVip.value && !state.user.data.isVip && 'btnMore'
                  ]}
                  style={{ paddingTop: '12px' }}
                >
                  <Button
                    block
                    round
                    type="primary"
                    style={{ fontSize: '16px' }}
                    onClick={onBuy}
                    color="linear-gradient(270deg, #FF204B 0%, #FE5B71 100%)"
                  >
                    购买专辑
                  </Button>
                  {buyVip.value && !state.user.data.isVip && (
                    <Button
                      block
                      round
                      type="primary"
                      style={{ fontSize: '16px' }}
                      color="linear-gradient(270deg, #FF204B 0%, #FE5B71 100%)"
                      onClick={() => {
                        router.push({
                          path: '/memberCenter',
                          query: {
                            ...route.query
                          }
                        })
                      }}
                    >
                      {studentActivityId.value > 0 && (
                        <div class={[styles.buttonDiscount]}>专属优惠</div>
                      )}
                      开通会员
                    </Button>
                  )}
                </div>
              </ColSticky>
            )}

          <Popup
            v-model:show={shareStatus.value}
            style={{ background: 'transparent' }}
            class={styles.albumShare}
          >
            <ColShare
              type="tenant"
              teacherId={state.user.data.userId}
              shareUrl={shareUrl.value}
              shareType="album"
              shareLength={1}
            >
              <div class={styles.shareVip}>
                {shareDiscount.value === 1 && (
                  <div class={styles.tagDiscount}>专属优惠</div>
                )}

                <img
                  class={styles.icon}
                  crossorigin="anonymous"
                  src={albumDetail.value?.albumCoverUrl + `?t=${+new Date()}`}
                />
                <div class={styles.info}>
                  <h4 class="van-multi-ellipsis--l2">
                    {albumDetail.value?.albumName}
                  </h4>
                  <p
                    class={['van-multi-ellipsis--l3']}
                    style={{
                      lineHeight: '16px',
                      margin: '5px 0 10px 0'
                    }}
                  >
                    {albumDetail.value?.albumDesc}
                  </p>
                  <div class={styles.shareAlumCollect}>
                    <img src={icon_music_list} />
                    <span>
                      共
                      <span style="color: var(--van-primary-color);">
                        {albumDetail.value?.musicSheetCount}
                      </span>
                      首曲目
                    </span>
                  </div>
                </div>
              </div>

              <div class={[styles.shareVip, styles.shareMusicList]}>
                <SongShare list={shareMusicList.value} />
              </div>
            </ColShare>
          </Popup>

          <Popup
            position="bottom"
            round
            v-model:show={subjectPopup.value}
            closeable
          >
            <div class={styles.popupTitle}>选择声部</div>
            <SelectSubject
              type="ALBUM"
              isShowAllSubject
              // isReset
              searchParams={subjects}
              onComfirm={onComfirmSubject}
            />
          </Popup>
        </div>
      )
    }
  }
})
