import {
  computed,
  defineComponent,
  nextTick,
  onMounted,
  reactive,
  ref,
  watch
} from 'vue'
import umiRequest from 'umi-request'
import { useRoute, useRouter } from 'vue-router'
import request from '@/helpers/request'
import ColHeader from '@/components/col-header'
import { postMessage, promisefiyPostMessage } from '@/helpers/native-message'
import {
  Button,
  Cell,
  CellGroup,
  Dialog,
  Icon,
  Image,
  Popup,
  Radio,
  RadioGroup,
  Sticky,
  Tag,
  Toast
} from 'vant'
import styles from './index.module.less'
// import Item from '../list/item'
import { useRect } from '@vant/use'
import { Vue3Lottie } from 'vue3-lottie'
import { getRandomKey } from '@/views/music/music'
import { getOssUploadUrl, state } from '@/state'
import { useEventTracking } from '@/helpers/hooks'
import ColSticky from '@/components/col-sticky'
import { browser, moneyFormat } from '@/helpers/utils'
import { orderStatus } from '@/views/order-detail/orderStatus'
import iconAlbum from '@/views/music/component/images/icon_album.png'
import iconDownload from '@/views/music/music-detail/images/icon_download.png'
import iconChangeStaff from '@/views/music/music-detail/images/icon-change-staff.png'
import AstronautJSON from '@/views/music/music-detail/animate/bigLoad.json'
import ColShare from '@/components/col-share'
import iconCollect from '@/views/music/music-detail/images/icon_collect.png'
import iconCollectActive from '@/views/music/music-detail/images/icon_collect_active.png'
import iconListen from '@/views/music/music-detail/images/icon_listen.png'
import iconTeacher from '@common/images/icon_teacher.png'

import activeButtonIcon from '@common/images/icon_checkbox.png'
import inactiveButtonIcon from '@common/images/icon_checkbox_default.png'
import staffDetafult from '@/views/music/music-detail/images/staff-default.png'
import firstDefault from '@/views/music/music-detail/images/first-default.png'
import fixedDefault from '@/views/music/music-detail/images/fixed-default.png'
import emtpy from '@/views/music/music-detail/images/emtpy.png'
import {
  addMusicTitle,
  addWatermark,
  convasToImg,
  imgToCanvas
} from '@/views/music/music-detail/imageFunction'
import Plyr from 'plyr'
import 'plyr/dist/plyr.css'

import icon_exquisite from '@/views/music/component/images/icon_exquisite.png'
import icon_album_active from '@/views/music/component/images/icon_album_active.png'
import wx_bg from '../images/wx_bg.png'
import { initJumpNativePage, shareCall } from '../share'
import qs from 'query-string'
import Download from '@/views/music/music-detail/download'

export default defineComponent({
  name: 'MusicDetail',
  setup() {
    localStorage.setItem('behaviorId', getRandomKey())
    const route = useRoute()
    const loading = ref(false)
    const isError = ref(false)
    const headers = ref(null)
    const footers = ref(null)
    const heightInfo = ref<any>('0')
    const musicDetail = ref<any>(null)
    // const showImg = ref<string>('')
    // const accompanyUrl = ref<string>('')
    const audioFileUrl = ref('')
    const wxStatus = ref<boolean>(false)
    let showImg = [] as any
    const firstList = ref<Array<any>>([])
    const fixedList = ref<Array<any>>([])
    const staffList = ref<Array<any>>([])
    const accompanyUrl = ref<string>('')
    const downloadStatus = ref<boolean>(false)
    const staff = reactive({
      status: false,
      radio: 'staff' // staff first fixed
    })

    const tmpUrl = `${location.origin}/${
      route.query.p == 'tenant' ? 'tenant' : 'student'
    }/#/music-detail?${qs.stringify(route.query)}`
    const jumpUrl = ref<string>(tmpUrl)

    const colors: any = {
      FREE: {
        color: '#01B84F',
        text: '免费'
      },
      VIP: {
        color: '#CD863E',
        text: '会员'
      },
      CHARGE: {
        color: '#3591CE',
        text: '点播'
      }
    }

    // 更改预览状态
    const onChangeStaff = (type: string) => {
      staff.radio = type
      staff.status = false
    }
    watch(
      () => staff.radio,
      (val: string) => {
        if (val == 'first') {
          showImg = firstList.value
        } else if (val == 'fixed') {
          showImg = fixedList.value
        } else {
          showImg = staffList.value
        }
      }
    )

    const FetchList = async (id?: any) => {
      if (loading.value) {
        return
      }
      loading.value = true
      isError.value = false
      try {
        const search = route.query
        const res = await request.post(`/open/musicShareProfit`, {
          prefix: '/api-teacher',
          requestType: 'json',
          data: {
            bizId: search.id,
            userId: search.recomUserId
          }
        })

        // 取原音，如果有多个则默认第一个
        const background = res.data.musicSheet.background

        audioFileUrl.value =
          background && background.length > 0 ? background[0].audioFileUrl : ''
        console.log(audioFileUrl.value)
        musicDetail.value = res.data.musicSheet
        // showImg.value = musicDetail.value?.musicImg || ''
        showImg = musicDetail.value?.musicImg
          ? musicDetail.value?.musicImg.split(',')
          : []
        firstList.value = musicDetail.value?.firstTone
          ? musicDetail.value?.firstTone.split(',')
          : []
        fixedList.value = musicDetail.value?.fixedTone
          ? musicDetail.value?.fixedTone.split(',')
          : []
        staffList.value = musicDetail.value?.musicImg
          ? musicDetail.value?.musicImg.split(',')
          : []
      } catch (error) {
        isError.value = true
      }
      loading.value = false
    }

    const player = ref<any>(null)
    const audio = ref<any>(null)
    const freeRate = ref<any>(0)
    const initAudio = async () => {
      const config = await request.get(
        state.platformApi + '/sysConfig/queryByParamNameList',
        {
          params: {
            paramNames: 'music_sheet_free_rate'
          }
        }
      )
      freeRate.value = config.data[0]?.paramValue || 0

      const controls = [
        // 'play-large',
        'play',
        'progress',
        // 'captions',
        // 'fullscreen',
        'duration'
      ]
      player.value = new Plyr(audio.value, {
        controls: controls
      })

      player.value.on('timeupdate', () => {
        // 允许播放时间
        const players = player.value
        const playTime = (players.duration * freeRate.value) / 100 || 0
        // 时间，是否购买，是否免费
        if (
          players.currentTime >= playTime &&
          musicDetail.value?.orderStatus !== 'PAID' &&
          !paymentType.value.includes('FREE')
        ) {
          // players.stop()
          players.pause()
        }
      })
    }
    onMounted(async () => {
      initJumpNativePage(jumpUrl.value)
      await FetchList()
      const { height } = useRect(headers as any)
      const footer = useRect(footers as any)
      heightInfo.value = height + footer.height

      // 初始化音频
      if (audioFileUrl.value) {
        initAudio()
      }
    })

    const paymentType = computed(() => {
      let paymentType = musicDetail.value?.paymentType
      if (typeof paymentType === 'string') {
        paymentType = paymentType.split(',')
        return paymentType
      }
      return []
    })

    const onShare = () => {
      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}>
          <Sticky position="top">
            <div ref={headers}>
              <ColHeader
                background="transparent"
                border={false}
                isFixed={false}
                color="#fff"
                backIconColor="white"
              />
            </div>
          </Sticky>

          <img class={styles.bgImg} src={musicDetail.value?.titleImg} />
          <div class={styles.bgContent}></div>
          <div
            class={styles.musicContainer}
            style={{
              marginTop: '16px',
              height: `calc(100vh - ${heightInfo.value + 16 + 'px'})`
            }}
          >
            <Cell
              border={false}
              center
              class={styles.musicInfo}
              v-slots={{
                icon: () => (
                  <Image
                    class={styles.pImg}
                    src={musicDetail.value?.titleImg}
                  />
                ),
                title: () => (
                  <div class={styles.info}>
                    <h4 class="van-ellipsis">
                      {musicDetail.value?.musicSheetName}
                    </h4>
                    <p
                      style={{
                        display: 'flex'
                      }}
                    >
                      {paymentType.value.map(tag => (
                        <Tag
                          style={{ color: colors[tag].color }}
                          class={styles.tag}
                          type="success"
                          plain
                        >
                          {colors[tag].text}
                        </Tag>
                      ))}
                      {musicDetail.value?.exquisiteFlag === 1 && (
                        <Image
                          class={styles.exquisiteFlag}
                          src={icon_exquisite}
                        />
                      )}

                      {musicDetail.value?.albumNums > 0 && (
                        <Image
                          class={styles.songAlbum}
                          src={icon_album_active}
                        />
                      )}
                      <span style={{ paddingTop: '2px', paddingLeft: '6px' }}>
                        {musicDetail.value?.composer}
                      </span>
                    </p>
                  </div>
                ),
                value: () => (
                  // <span class={styles.download} onClick={() => onShare()}>
                  //   <img src={iconDownload} />
                  //   下载曲谱
                  // </span>
                  <>
                    {musicDetail.value?.notation ? (
                      <span class={styles.download} onClick={() => onShare()}>
                        <img src={iconChangeStaff} />
                        <span>转谱</span>
                      </span>
                    ) : null}
                    <span class={styles.download} onClick={() => onShare()}>
                      <img src={iconDownload} />
                      <span>下载曲谱</span>
                    </span>
                  </>
                )
              }}
            />
            <div class={styles.musicContent}>
              <p class={styles.musicTitle}>
                {musicDetail.value?.musicSheetName}
              </p>
              {showImg.length > 0 ? (
                <img src={showImg[0]} alt="" class={styles.musicImg} />
              ) : loading.value ? (
                <>
                  <Vue3Lottie
                    animationData={AstronautJSON}
                    class={styles.finch}
                  ></Vue3Lottie>
                  <p class={styles.finchLoad}>加载中...</p>
                </>
              ) : (
                <div class={styles.empty}>
                  <Image src={emtpy} class={styles.emptyImg} />
                  <p class={styles.emptyTip}>暂无乐谱预览图</p>
                </div>
              )}

              <div class={styles.videoOperation}>
                {audioFileUrl.value && (
                  <>
                    {(paymentType.value.includes('CHARGE') ||
                      paymentType.value.includes('VIP')) &&
                      musicDetail.value?.orderStatus !== 'PAID' && (
                        <div class={[styles.audition]}>
                          <img src={iconListen} />
                          <span>每首曲目可试听{freeRate.value}%</span>
                        </div>
                      )}

                    <div class={[styles.audio, styles.collectCell]}>
                      <audio id="player" controls ref={audio}>
                        <source src={audioFileUrl.value} type="audio/mp3" />
                      </audio>
                    </div>
                  </>
                )}

                <div class={[styles.collect, styles.collectCell]}>
                  <div class={[styles.userInfo]}>
                    <img src={musicDetail.value?.userAvatar || iconTeacher} />
                    <span>{musicDetail.value?.userName}</span>
                  </div>

                  <div
                    class={[styles.collectSection]}
                    onClick={() => onShare()}
                  >
                    <span>{musicDetail.value?.favoriteCount}人收藏</span>
                    <img
                      src={
                        musicDetail.value?.favorite
                          ? iconCollectActive
                          : iconCollect
                      }
                    />
                  </div>
                </div>
              </div>
            </div>

            <div
              class={[styles.lookAlbum, styles.collectCell]}
              onClick={() => {
                onShare()
              }}
            >
              <div>
                <img src={iconAlbum} />
                <span>进入曲目所在专辑列表</span>
              </div>
              <Icon name="arrow" size={16} color="#666" />
            </div>
          </div>

          {musicDetail.value?.id && (
            <ColSticky position="bottom" background="white">
              <div ref={footers}>
                <Button
                  round
                  block
                  type="primary"
                  color="linear-gradient(180deg, #59E5D5 0%, #2DC7AA 100%)"
                  onClick={() => onShare()}
                >
                  下载酷乐秀进入详情
                </Button>
              </div>
            </ColSticky>
          )}

          <Popup v-model:show={downloadStatus.value} position="bottom" round>
            <Download
              imgList={JSON.parse(JSON.stringify(showImg))}
              musicSheetName={musicDetail.value.musicSheetName}
            />
          </Popup>

          <Popup
            v-model:show={staff.status}
            teleport="body"
            closeable
            style={{ width: '80%' }}
            round
          >
            <div class={styles.staffContainer}>
              <div class={styles.staffTitle}>选择转换曲谱</div>
              <RadioGroup v-model={staff.radio}>
                <CellGroup border={false}>
                  <Cell
                    center
                    border={false}
                    class={staff.radio === 'staff' ? styles.active : ''}
                    onClick={() => onChangeStaff('staff')}
                  >
                    {{
                      icon: () => (
                        <Image src={staffDetafult} class={styles.staffImg} />
                      ),
                      title: () => <span class={styles.name}>五线谱</span>,
                      value: () => (
                        <Radio name="staff">
                          {{
                            icon: (props: any) => (
                              <Icon
                                class={styles.boxStyle}
                                size={16}
                                name={
                                  props.checked
                                    ? activeButtonIcon
                                    : inactiveButtonIcon
                                }
                              />
                            )
                          }}
                        </Radio>
                      )
                    }}
                  </Cell>
                  <Cell
                    center
                    border={false}
                    class={staff.radio === 'first' ? styles.active : ''}
                    onClick={() => onChangeStaff('first')}
                  >
                    {{
                      icon: () => (
                        <Image src={firstDefault} class={styles.staffImg} />
                      ),
                      title: () => <span class={styles.name}>简谱-首调</span>,
                      value: () => (
                        <Radio name="first">
                          {{
                            icon: (props: any) => (
                              <Icon
                                class={styles.boxStyle}
                                size={16}
                                name={
                                  props.checked
                                    ? activeButtonIcon
                                    : inactiveButtonIcon
                                }
                              />
                            )
                          }}
                        </Radio>
                      )
                    }}
                  </Cell>
                  <Cell
                    center
                    border={false}
                    class={staff.radio === 'fixed' ? styles.active : ''}
                    onClick={() => onChangeStaff('fixed')}
                  >
                    {{
                      icon: () => (
                        <Image src={fixedDefault} class={styles.staffImg} />
                      ),
                      title: () => <span class={styles.name}>简谱-固定调</span>,
                      value: () => (
                        <Radio name="fixed">
                          {{
                            icon: (props: any) => (
                              <Icon
                                class={styles.boxStyle}
                                size={16}
                                name={
                                  props.checked
                                    ? activeButtonIcon
                                    : inactiveButtonIcon
                                }
                              />
                            )
                          }}
                        </Radio>
                      )
                    }}
                  </Cell>
                </CellGroup>
              </RadioGroup>
            </div>
          </Popup>

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