import TheSticky from '@/components/the-sticky'
import styles from './new-index.module.less'
import { useThrottleFn } from '@vueuse/core'
import { postMessage, promisefiyPostMessage } from '@/helpers/native-message'
// import iconShare from '../../images/icon-share.png'
import oStart from '../album-detail/icon-hart.png'
import iStart from '../album-detail/icon-hart-active.png'
import iconDownload from './images/icon-download.png'
import iconMemberSmall from './images/icon-member-small.png'
import {
  computed,
  defineComponent,
  nextTick,
  onMounted,
  onUnmounted,
  reactive,
  ref
} from 'vue'
import { useRoute, useRouter } from 'vue-router'
import request from '@/helpers/request'
import ColHeader from '@/components/col-header'

import {
  Button,
  Cell,
  CellGroup,
  Dialog,
  Icon,
  Image,
  Popup,
  RadioGroup,
  Radio,
  Toast,
  Picker
} from 'vant'
import { useRect } from '@vant/use'
// import { Vue3Lottie } from 'vue3-lottie'
import { getRandomKey, musicBuy } from '../music'
import { state } from '@/state'
import { browser, getHttpOrigin, moneyFormat } from '@/helpers/utils'
import { orderStatus } from '@/views/order-detail/orderStatus'
// import AstronautJSON from './animate/refresh_anim.json'
// import ColShare from '@/components/col-share'
import iconListen from './images/icon_listen.png'
// import iconTeacher from '@common/images/icon_teacher.png'
// import emtpy from './images/emtpy.png'
import { state as baseState } from '@/state'

import activeButtonIcon from './images/icon_checkbox.png'
import inactiveButtonIcon from './images/icon_checkbox_default.png'
import staffDetafult from './images/staff-default.png'
import firstDefault from './images/first-default.png'
import fixedDefault from './images/fixed-default.png'

import Plyr from 'plyr'
import 'plyr/dist/plyr.css'
import Download from './download'
import { getInstrumentName } from '@/constant/instruments'
import { svgtopng } from './formatSvgToImg'

export default defineComponent({
  name: 'new-index',
  setup() {
    localStorage.setItem('behaviorId', getRandomKey())
    const router = useRouter()
    const route = useRoute()
    const loading = ref(false)
    const background = ref<string>('rgba(55, 205, 177, 0)')
    const color = ref<string>('#fff')
    const aId = Number(route.query.activityId) || 0
    const studentActivityId = ref(aId)
    const isError = ref(false)
    const headers = ref(null)
    const footers = ref(null)
    const heightInfo = ref<any>('0')
    const audioFileUrl = ref('')

    const partColumns = ref<any>([])
    const downloadStatus = ref<boolean>(false)
    const staff = reactive({
      status: false,
      radio: 'staff' // staff first fixed
    })

    const apiSuffix = ref(
      baseState.platformType === 'STUDENT' ? '/api-student' : '/api-teacher'
    )
    // 更改预览状态
    const onChangeStaff = (type: string) => {
      staff.radio = type
      staff.status = false
      staffData.imgs = []
      if (type == 'FIRST') {
        loading.value = false
        const tempPdf = staffData.details?.firstPdfUrl
        initIframe(tempPdf, 'FIRST')
      } else if (type == 'JIAN') {
        loading.value = false
        const tempPdf = staffData.details?.jianPdfUrl
        initIframe(tempPdf, 'JIAN')
      } else {
        loading.value = false
        const tempPdf = staffData.details?.musicPdfUrl
        initIframe(tempPdf, 'STAVE')
      }
    }

    const FetchList = async (id?: any) => {
      if (loading.value) {
        return
      }
      loading.value = true
      isError.value = false
      try {
        const {data} = await request.post('/musicSheet/detailSmall', {
          prefix:
            state.platformType === 'TEACHER' ? '/api-teacher' : '/api-student',
          data: {
            musicSheetId: route.query.id,
            tenantAlbumId: route.query.tenantAlbumId,
            providerType: route.query.providerType,
            instrumentId: staffData.instrumentId,
            subjectId: staffData.subjectId
          }
        })
        staffData.details = data
        await toDetail(data)
      } catch (error) {
        isError.value = true
      }
      if (staffData.details?.musicSheetType !== 'CONCERT') {
        loading.value = false
      }
    }
    const player = ref<any>(null)
    const audio = ref<any>(null)
    const freeRate = ref<any>(0)
    const initAudio = async () => {
      const controls = [
        'play-large',
        'play',
        'progress',
        'captions',
        // 'fullscreen',
        'duration'
      ]
      player.value = new Plyr(audio.value, {
        controls: controls
      })

      const config = await request.get(
        '/sysConfig/queryByParamNameList',
        {
          prefix: state.platformType === 'TEACHER' ? '/api-teacher' : '/api-student',
          params: {
            paramNames: 'music_sheet_free_rate'
          }
        }
      )
      freeRate.value = config.data[0]?.paramValue || 0


      nextTick(async () => {
        console.log("nextTick nextTick")
        renderStaff();
      });

      player.value.on('timeupdate', () => {
        // 允许播放时间
        const players = player.value
        const playTime = (players.duration * freeRate.value) / 100 || 0
        // 时间，不能播放
        if (players.currentTime >= playTime && !buyState.value.play) {
          players.stop()
          // players.pause()
        }
      })
    }

    const showLoading = async (e: any) => {
      // console.log(e, 'showLoading')
      if (e.data?.api === 'musicStaffRender') {
        const osmdImg = e.data.osmdImg
        const imgs: any = []
        for (let i = 0; i < osmdImg.length; i++) {
          const img = await svgtopng(
            osmdImg[i].img,
            osmdImg[i].width,
            osmdImg[i].height
          )
          imgs.push(img)
        }
        staffData.imgs = imgs

        loading.value = e.data.loading
      }
    }
    onMounted(async () => {
      const instrumentIds = state.user.data?.instrumentId
      if (instrumentIds) {
        const instrumentId = instrumentIds.split(',')[0]
        staffData.instrumentId = instrumentId
      }
      const subjectIds = state.user.data?.subjectId
      if(subjectIds) {
        const subjectId = subjectIds.split(',')[0]
        staffData.subjectId = subjectId
      }

      postMessage({
        api: 'setStatusBarTextColor',
        content: { statusBarTextColor: true }
      })
      await FetchList()
      const { height } = useRect(headers as any)
      const footer = useRect(footers as any)
      heightInfo.value = height + footer.height

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

      window.addEventListener('message', showLoading)
    })
    onUnmounted(() => {
      postMessage({
        api: 'setStatusBarTextColor',
        content: { statusBarTextColor: false }
      })
      window.removeEventListener('message', showLoading)
    })
    const toggleFavorite = async () => {
      try {
        await request.post('/music/sheet/favorite/' + staffData.details?.id, {
          prefix:
            state.platformType === 'TEACHER' ? '/api-teacher' : '/api-student'
        })
        staffData.details.favorite = staffData.details?.favorite ? 0 : 1
        staffData.details.favoriteCount = staffData.details?.favorite
          ? staffData.details.favoriteCount + 1
          : staffData.details.favoriteCount - 1 < 0
          ? 0
          : staffData.details.favoriteCount - 1
        setTimeout(() => {
          Toast(staffData.details?.favorite ? '收藏成功' : '取消收藏成功')
        }, 100)
      } catch (error) {
        //
      }
    }

    const onBuy = async () => {
      const music = staffData.details
      orderStatus.orderObject.orderType = 'MUSIC'
      orderStatus.orderObject.orderName = music.name
      orderStatus.orderObject.orderDesc = music.name
      orderStatus.orderObject.actualPrice = music.musicPrice
      orderStatus.orderObject.recomUserId = route.query.recomUserId || 0
      orderStatus.orderObject.activityId = route.query.activityId || 0
      orderStatus.orderObject.orderNo = ''
      orderStatus.orderObject.orderList = [
        {
          orderType: 'MUSIC',
          goodsName: music.name,
          actualPrice: music.musicPrice,
          price: music.musicPrice,
          ...music
        }
      ]

      const res = await request.post('/api-student/userOrder/getPendingOrder', {
        data: {
          goodType: 'MUSIC',
          bizId: music.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
            orderStatus.orderObject.paymentConfig = {
              ...result.paymentConfig,
              paymentVendor: result.paymentVendor,
              paymentVersion: result.paymentVersion
            }
            routerTo()
          })
          .catch(() => {
            Dialog.close()
            // 只用取消订单，不用做其它处理
            cancelPayment(result.orderNo)
          })
      } else {
        routerTo()
      }
    }
    const routerTo = () => {
      const music = staffData.details
      router.push({
        path: '/orderDetail',
        query: {
          orderType: 'MUSIC',
          musicId: music.id
        }
      })
    }
    const cancelPayment = async (orderNo: string) => {
      try {
        await request.post('/api-student/userOrder/orderCancel', {
          data: {
            orderNo
          }
        })
      } catch {
        //
      }
    }

    const buyState = computed(() => {
      const music = staffData.details
      return {
        hasTenantAlbum: route.query?.tenantAlbumId ? true : false, // 是否从专辑来的
        play: music.play ? true : false, // 是否可以播放
        free: music?.paymentType.includes('FREE'),
        charge: music?.paymentType.includes('CHARGE'),
        vip: music?.paymentType.includes('VIP'),
        buy: music?.orderStatus === 'PAID' // 是否已买
      }
    })

    const staffData = reactive({
      musicId: route.query.id as any,
      instrumentId: '', // 声部编号
      subjectId: '', //
      isConcert: false, // 是否合奏
      details: {} as any,
      list: [], // 列表数据
      open: false,
      closed: true,
      audioReady: false,
      iframeSrc: '',
      // musicXml: '',
      instrumentName: '',
      iframeRef: null as any,
      imgs: [] as any,
      musicPdfUrl: '', // 当前声轨PDF
      partList: [] as any[],
      partNames: [] as string[],
      selectedPartName: '' as any,
      selectedPartIndex: 0,
      isComberRender: false, // 是否合并谱显示
      metronomeUrl: '', // 合奏使用链接
      metronomeMp3Url: '' // 独奏使用链接
    })

    // 当前先中的数据
    const currentColumn = computed(() => {
      return partColumns.value.find(
        (item: any) => item.value === staffData.selectedPartIndex
      )
    })

    // 是否转谱不能转，默认谱面不是五线谱时
    const defaultConvertible = computed(() => {
      const details = staffData.details
      let isConvertibleScore = details.isConvertibleScore
      let isHiddenStaff = false // 是否隐藏五线谱转谱

      if(!isConvertibleScore && ["FIRST", "JIAN"].includes(details.scoreType)) {
        isConvertibleScore = true
        isHiddenStaff = true
      }
      return {
        isConvertibleScore,
        isHiddenStaff
      }
    })
    /** 渲染五线谱 */
    // 长笛、单簧管、萨克斯、小号、长号、圆号、大号、上低音号
    // const sortList = {
    //   长笛: 1,
    //   单簧管: 2,
    //   中音单簧管: 3,
    //   低音单簧管: 4,
    //   高音萨克斯风: 5,
    //   中音萨克斯风: 6,
    //   次中音萨克斯风: 7,
    //   低音萨克斯风: 8,
    //   小号: 9,
    //   长号: 10,
    //   圆号: 11,
    //   大号: 12,
    //   上低音号: 13
    // }
    // const instrumentSort = (list: Array<any>) => {
    //   list.sort((a, b) => {
    //     return (
    //       (sortList[getInstrumentName(a.track)] || 20) -
    //       (sortList[getInstrumentName(b.track)] || 20)
    //     )
    //   })
    //   return list
    // }

    /** 获取分轨信息 */
    const getInstrumentItem = (instruments: any, name = '') => {
      name = name.toLocaleLowerCase().replace(/ /g, '') //.replace(/\d*/gi, '')
      if (!name) return ''
      for (let key in instruments) {
        const item = instruments[key]
        const _key = item.track?.toLocaleLowerCase().replace(/ /g, '') //.replace(/\d*/gi, '')
        if (_key === name) {
          return item
        }
      }
      return ''
    }

    // 根据当前选中的声部和曲目筛选出对应的声轨
    function filterSoundCodes(musicalInstruments: any) {
      // 老师端，加上乐器id
      const instrumentIds = staffData.instrumentId // appState.instrumentId || appState.user?.instrumentId || route.query.instrumentId
      if (instrumentIds) {
        const { track  } =
          musicalInstruments.find((item: any) => {
            return instrumentIds == item.musicalInstrumentId
          }) || {}
        return track 
      }
      return null
    }

    // 根据当前选中的声部和曲目筛选出对应的声轨
    // function filterSoundInfo(musicalInstruments: any) {
    //   if (musicalInstruments.length <= 0) return null
    //   // 老师端，加上乐器id
    //   const instrumentIds = staffData.instrumentId //appState.instrumentId || appState.user?.instrumentId || route.query.instrumentId
    //   if (instrumentIds) {
    //     const item =
    //       musicalInstruments.find((item: any) => {
    //         return (
    //           instrumentIds == item.musicalInstrumentId &&
    //           item.audioPlayType == 'PLAY'
    //         )
    //       }) || null
    //     return item
    //   }
    //   return null
    // }

    // 获取PDF
    const getCurrentPdf = (item: any, scoreType: string) => {
      let pdfUrl = ''
      if (scoreType === 'FIRST') {
        pdfUrl = item?.firstPdfUrl
      } else if (scoreType === 'JIAN') {
        pdfUrl = item?.jianPdfUrl
      } else if (scoreType === 'STAVE') {
        pdfUrl = item?.musicPdfUrl
      }
      return pdfUrl || ''
    }

    const toDetail = async (row: any) => {
      // const partNames = await getPartNames(row.xmlFileUrl);
      // staffData.partNames = partNames;
      staff.radio = row.scoreType // 默认是什么谱页
      const tempSongList = row.musicSheetSoundList || []
      let partList = tempSongList
      staffData.list = tempSongList
      partList = partList.filter(
        (item: any) => !item.track?.toLocaleUpperCase()?.includes('COMMON')
      )
      partColumns.value = partList.map((item: any, index: number) => {
        // const xmlIndex = staffData.partNames.filter((text: string) => text.toLocaleUpperCase() !== "COMMON").findIndex(
        //   (name: any) => name.trim() === item.track
        // );
        // 因为合奏的，显示总谱会加一个声轨
        const defaultIndex =
          row.musicSheetType !== 'SINGLE' && row.isScoreRender
            ? index + 1
            : index
        const cnName = getInstrumentName(item.track)
        return {
          text: item.track + (cnName ?  `(${cnName})` : ''),
        name: item.track + (cnName ?  `(${cnName})` : ''), // true
          track: item.track,
          musicPdfUrl: item.musicPdfUrl,
          firstPdfUrl: item.firstPdfUrl,
          jianPdfUrl: item.jianPdfUrl,
          // xmlIndex,
          value: defaultIndex
        }
      })

      staffData.details = row || {}
      // staffData.musicXml = staffData.details?.xmlFileUrl
      staffData.isComberRender = staffData.details?.isScoreRender

      let defaultShowStaff
      if (staffData.details?.musicSheetSoundList) {
        const soundCodes = filterSoundCodes(
          staffData.details?.musicSheetSoundList
        )
        if (soundCodes) {
          const soundCodesArr = soundCodes.split(',').map((code: string) => {
            return code
              .toLowerCase()
              .replace(/^\d+|\d+$/g, '')
              .trim()
          })
          defaultShowStaff = partColumns.value.find((item: any) =>
            soundCodesArr.includes(
              item.track &&
                item.track
                  .toLowerCase()
                  .replace(/^\d+|\d+$/g, '')
                  .trim()
            )
          )
          // console.log(defaultShowStaff, 'defaultShowStaff')
          if (defaultShowStaff) {
            staffData.selectedPartIndex = defaultShowStaff.value
          }
        }
      }

      if (row.musicSheetType === 'SINGLE') {
        staffData.musicPdfUrl = getCurrentPdf(
          row,
          row.scoreType
        )

        // 生成的图片
        // staffData.imgs = row.musicImg ? row.musicImg.split(',') : [];
      } else {
        // 初始化数据
        // 是否显示总谱
        if (staffData.isComberRender) {
          partColumns.value.unshift({
            text: '总谱',
            value: 0,
            xmlIndex: 999,
            musicPdfUrl: row.musicPdfUrl,
            firstPdfUrl: row.firstPdfUrl,
            jianPdfUrl: row.jianPdfUrl,
            track: '',
            name: '总谱'
          })
          // 如果是总谱则默认选中，否则选择
          staffData.selectedPartIndex = row.defaultScoreRender
            ? 0
            : defaultShowStaff
            ? defaultShowStaff.value
            : 1
          let pdfUrl = ''
          if (row.defaultScoreRender) {
            pdfUrl = getCurrentPdf(row, row.scoreType)
          } else {
            pdfUrl = getCurrentPdf(
              defaultShowStaff,
              row.scoreType
            )
          }
          staffData.musicPdfUrl = pdfUrl
        } else {
          const item = partColumns.value.find(
            (item: any) => item.value === staffData.selectedPartIndex
          )
          if (item) {
            staffData.musicPdfUrl = getCurrentPdf(item, row.scoreType) //item.musicPdfUrl;
          } else {
            staffData.musicPdfUrl = ''
          }
        }
      }

      // 通过isScoreRender判断是否合并渲染
      // 多声轨,  不是单声部多声轨, 不是老师布置作业选择曲谱
      audioFileUrl.value = row.mp3Url
      if (
        audioFileUrl.value
      ) {
        // audioFileUrl.value = staffData.isConcert
        //   ? staffData.metronomeUrl
        //   : staffData.metronomeMp3Url
        nextTick(async () => {
          initAudio()
        })
      } else {
        renderStaff()
      }
    }

    const getPreViewCloud = (musicId: string, partIndex: number, track: string) => {
      const Authorization = sessionStorage.getItem('Authorization') || ''
      const musicScorePath = '/klx-music-score/'
      const musicScoreUrl = getHttpOrigin() + musicScorePath
      // const musicScoreUrl = "https://dev.colexiu.com" + musicScorePath;
      // const musicScoreUrl = 'http://192.168.3.68:3000/instrument.html';
      let href = `${musicScoreUrl}?t=${Date.now()}#/?id=${musicId}&Authorization=${Authorization}&isPreView=true&zoom=0.5&downPng=A4`
      // // 老师端加上systemType=teacher
      href +=
        '&systemType=' +
        (state.platformType === 'STUDENT' ? `student` : 'teacher')
        // 总谱还是什么
        if(partIndex === 999) {
          href += `&part-index=${partIndex}`
        } else {
          href += `&part-name=${encodeURIComponent(track || "")}`
        }
      // if (location.pathname.includes("accompany-teacher")) {
      //   href += `&systemType=teacher`;
      // }
      //   musicRenderType
      //   /** 五线谱 */
      // staff = "staff",
      // /** 简谱（首调） */
      // firstTone = "firstTone",
      // /** 固定音高 */
      // fixedTone = "fixedTone",
      if (staff.radio === 'STAVE') {
        href += '&musicRenderType=staff'
      } else if (staff.radio === 'JIAN') {
        href += '&musicRenderType=fixedTone'
      } else if (staff.radio === 'FIRST') {
        href += '&musicRenderType=firstTone'
      }

      return href
    }

    const renderStaff = async () => {
      try {
        nextTick(() => {
          if (staffData.musicPdfUrl) {
            const url = `${getHttpOrigin()}${
              location.pathname
            }pdf/web/viewer-pdf.html?file=${encodeURIComponent(
              staffData.musicPdfUrl
            )}&t=${Date.now()}`

            const iframeRef = document.querySelector('#staffIframeRef') as any
            iframeRef.contentWindow.location.replace(url)
            // staffData.iframeSrc = url
          } else {
            const url = getPreViewCloud(
              staffData.musicId,
              currentColumn.value?.xmlIndex || 0,
              currentColumn.value?.track || ''
            )
            console.log(url, 'staffIframeRef')
            const iframeRef = document.querySelector('#staffIframeRef') as any
            iframeRef.contentWindow.location.replace(url)
            // staffData.iframeSrc = url
          }
        })
      } catch (error) {
        //
      }
    }

    const resetRender = () => {
      const iframeRef: any = document.getElementById('staffIframeRef')
      iframeRef.contentWindow.location.replace(getPreViewCloud(staffData.musicId, currentColumn.value?.xmlIndex || 0, currentColumn.value.track))
    }

    const onDownloadApp = () => {
      Dialog.alert({
        title: '提示',
        message: '请在酷乐秀APP中使用',
        confirmButtonColor: '#2dc7aa'
      }).then(() => {
        window.location.href = getHttpOrigin() + '/student/#/download'
      })
    }

    //  购买
    const onSubmit = async () => {
      const url =
        apiSuffix.value +
        '/tenantGroupAlbum/buyAlbumInfo?tenantGroupAlbumId=' +
        (route.query.taId || '')
      const { data } = await request.get(url)
      const details = data[0]
      orderStatus.orderObject.orderType = 'TENANT_ALBUM'
      orderStatus.orderObject.orderName = details.name
      orderStatus.orderObject.orderDesc = details.name
      orderStatus.orderObject.actualPrice = details.actualPrice
      // orderStatus.orderObject.recomUserId = route.query.recomUserId || 0
      // orderStatus.orderObject.activityId = route.query.activityId || 0
      orderStatus.orderObject.orderNo = ''
      orderStatus.orderObject.orderList = [
        {
          orderType: 'TENANT_ALBUM',
          goodsName: details.name,
          actualPrice: details.actualPrice,
          price: details.actualPrice,
          ...details
        }
      ]

      const res = await request.post('/api-student/userOrder/getPendingOrder', {
        data: {
          goodType: 'TENANT_ALBUM',
          bizId: details.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
            orderStatus.orderObject.paymentConfig = {
              ...result.paymentConfig,
              paymentVendor: result.paymentVendor,
              paymentVersion: result.paymentVersion
            }

            routerToALBUM(details.id)
          })
          .catch(() => {
            Dialog.close()
            // 只用取消订单，不用做其它处理
            cancelPaymentALBUM(result.orderNo)
          })
      } else {
        routerToALBUM(details.id)
      }
    }
    const cancelPaymentALBUM = async (orderNo: string) => {
      try {
        await request.post('/api-student/userOrder/orderCancel/v2', {
          data: {
            orderNo
          }
        })
      } catch {
        //
      }
    }
    const routerToALBUM = (id: string) => {
      router.push({
        path: '/orderDetail',
        query: {
          orderType: 'ALBUM',
          album: id
        }
      })
    }

    const initIframe = (tempPdf: string, staff: string) => {
      if (tempPdf) {
        staffData.musicPdfUrl = tempPdf
      } else {
        staffData.musicPdfUrl = ''
      }
      renderStaff()
    }
    return () => (
      <div class={styles.detail}>
        <TheSticky position="top">
          <ColHeader
            background={background.value}
            hideHeader={false}
            border={false}
            isFixed={false}
            color={color.value}
            backIconColor="white"
          />
        </TheSticky>
        <img class={styles.bgImg} src={staffData.details?.musicCover} />
        <div class={styles.musicContentBg}></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={staffData.details?.musicCover}
              />
            </div>
            <div class={styles.alumDes}>
              <div class={[styles.alumTitle, 'van-ellipsis']}>
                {staffData.details?.name}
              </div>
              <div class={[styles.des, 'van-multi-ellipsis--l2']}>
                {!staffData.details?.composer
                  ? `上传者：${staffData.details?.addName || ''}`
                  : `作曲：${staffData.details?.composer || ''}`}
              </div>
            </div>
          </div>
          <div class={[styles.alumCollect]}>
            <div
              class={[
                styles.alumCollectItem,
                staffData.imgs.length <= 0 && !staffData.musicPdfUrl
                  ? styles.alumCollectItemActive
                  : ''
              ]}
              onClick={() => {
                if (browser().isApp) {
                  if(staffData.imgs.length <= 0 && !staffData.musicPdfUrl) return
                  if (staffData.musicPdfUrl) {
                    const songName =
                      staffData.details?.name +
                      (staffData.isConcert &&
                      currentColumn.value?.name
                        ? `(${
                            currentColumn.value
                              ?.name || ""
                          })`
                        : "");
                    promisefiyPostMessage({
                      api: "downloadFile",
                      content: {
                        downloadUrl: staffData.musicPdfUrl,
                        fileName: songName,
                      },
                    });
                  } else {
                    downloadStatus.value = true;
                  }
                } else {
                  onDownloadApp()
                }
              }}
            >
              <img src={iconDownload} />
              <span>下载曲谱</span>
            </div>

            <div
              class={styles.alumCollectItem}
              onClick={() => toggleFavorite()}
            >
              <img src={staffData.details?.favorite ? iStart : oStart} />
              <span>{staffData.details?.favoriteCount}人收藏</span>
            </div>
          </div>
          {/* {buyState.value.hasTenantAlbum ? 'true' : 'false'} */}
          {staffData.details?.id &&
            !buyState.value.play &&
            !buyState.value.hasTenantAlbum && (
              <div class={styles.albumTips}>
                {buyState.value.charge && buyState.value.vip ? (
                  <>
                    <span>开通会员或点播单曲，即可自由练习该曲谱</span>
                    <span class={styles.albumPrice}>
                      ¥{moneyFormat(staffData.details?.musicPrice)}
                    </span>
                  </>
                ) : buyState.value.vip ? (
                  <span>
                    <img src={iconMemberSmall} class={styles.iconMemberSmall} />
                    此曲谱为会员专享，开通会员即可自由练习该曲谱
                  </span>
                ) : buyState.value.charge ? (
                  <>
                    <span>此曲谱为点播曲谱，点播即可自由练习该曲谱</span>
                    <span class={styles.albumPrice}>
                      ¥{moneyFormat(staffData.details?.musicPrice)}
                    </span>
                  </>
                ) : (
                  ''
                )}
              </div>
            )}
        </div>

        <div class={styles.musicContent}>
          {defaultConvertible.value.isConvertibleScore && staffData.details?.musicSheetType === 'SINGLE' ? (
            <span
              class={styles.iconTransfer}
              style={{
                display:
                  staffData.details?.musicSheetType === 'SINGLE' ? '' : 'none'
              }}
              onClick={() => {
                staff.status = true
              }}
            >
              转谱
            </span>
          ) : null}
          <span
            class={styles.iconTransfer}
            style={{
              display:
                staffData.details?.musicSheetType === 'CONCERT' ? '' : 'none'
            }}
            onClick={() => {
              staffData.open = true
            }}
          >
            切换声轨
          </span>

          {staffData.details.id ? (
            <>
              {staffData.musicPdfUrl ? (
                <>
                  {/* {loading.value && (
                  <>
                    <Vue3Lottie
                      animationData={AstronautJSON}
                      class={styles.finch}
                    ></Vue3Lottie>
                    <p class={styles.finchLoad}>加载中...</p>
                  </>
                )} */}
                  <iframe
                    style={{
                      opacity: loading.value ? 0 : 1
                    }}
                    id="staffIframeRef"
                    src={staffData.iframeSrc}
                    onLoad={() => {
                      // 判断是用哪个渲染的
                      loading.value = false
                    }}
                  ></iframe>
                </>
              ) : (
                <>
                  <p class={styles.musicTitle}>
                    {staffData.details?.name && (
                      <>
                        {staffData.details?.name}
                        {staffData.isConcert && currentColumn.value?.name
                          ? `(${currentColumn.value?.name || ''})`
                          : ''}
                      </>
                    )}
                  </p>
                  {/* {loading.value && (
                  <>
                    <Vue3Lottie
                      animationData={AstronautJSON}
                      class={styles.finch}
                    ></Vue3Lottie>
                    <p class={styles.finchLoad}>加载中...</p>
                  </>
                )} */}
                  <iframe
                    id="staffIframeRef"
                    style={{
                      opacity: loading.value ? 0 : 1
                    }}
                    src={staffData.iframeSrc}
                    onLoad={() => {
                      loading.value = false
                      // musicIframeLoad();
                    }}
                  ></iframe>
                </>
              )}
            </>
          ) : null}
        </div>

        {staffData.details?.id && (
          <TheSticky position="bottom" varName="--bottom-height">
            <div style={{ backgroundColor: '#fff' }}>
              <div class={styles.videoOperation}>
                {audioFileUrl.value && (
                  <>
                    {!buyState.value.play &&
                      freeRate.value != 100 &&
                      freeRate.value != 0 && (
                        <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>

              <div ref={footers} class={styles.footers}>
                {/* 判断是否是免费的，或者已经购买过 */}
                {buyState.value.play ? (
                  <Button
                    round
                    block
                    type="primary"
                    color="linear-gradient( 270deg, #FF204B 0%, #FE5B71 100%)"
                    onClick={() => {
                      if (!browser().isApp) {
                        onDownloadApp()
                        return
                      }
                      const throttleFn = useThrottleFn(() => {
                        player.value && player.value.stop()
                        // const item: any = partColumns.value.find(
                        //   (c: any) => c.value === staffData.partIndex
                        // )

                        // const index = staffData.tempPartList.findIndex(
                        //   (i: any) => i.track === item?.track
                        // )
                        // 新版云教练的谱面类型使用musicRenderType字段
                        // const musicRenderType = staff.radio === 'staff' ? 'staff' : staff.radio === 'first' ? 'firstTone' :  staff.radio === 'fixed' ? 'fixedTone' : '';

                        player.value && player.value.stop()
                        // 新版云教练的谱面类型使用musicRenderType字段
                        let musicRenderType = ''
                        if (staff.radio === 'STAVE') {
                          musicRenderType = 'staff'
                        } else if (staff.radio === 'JIAN') {
                          musicRenderType = 'fixedTone'
                        } else if (staff.radio === 'FIRST') {
                          musicRenderType = 'firstTone'
                        }
                        let extraParam: any = {
                          // 'part-index': currentColumn.value.xmlIndex || 0,
                          'part-name': encodeURIComponent(currentColumn.value.track?.trim() || ''),
                          musicRenderType,

                          albumId: route.query.tenantAlbumId || '', // 专辑编号
                          // 1：忽略系统节拍器
                          ignoreSysMetronome:
                            route.query.subjectType === 'MUSIC' ? 1 : 0
                        }
                        if (route.query.tenantAlbumId) {
                          extraParam.albumId = route.query.tenantAlbumId
                        }

                        musicBuy(
                          {
                            id: staffData.details.id
                          },
                          () => {},
                          extraParam
                        )
                      }, 300)

                      throttleFn()
                    }}
                  >
                    立即练习
                  </Button>
                ) : buyState.value.hasTenantAlbum && !buyState.value.play ? (
                  <Button
                    disabled={route.query.buyStatus === '1'}
                    round
                    block
                    type="primary"
                    color="linear-gradient( 270deg, #FF204B 0%, #FE5B71 100%)"
                    onClick={() => {
                      if (!browser().isApp) {
                        onDownloadApp()
                        return
                      }
                      if (route.query.type === 'search') {
                        router.push('train-tool')
                      } else {
                        onSubmit()
                      }
                    }}
                  >
                    开通训练教程
                  </Button>
                ) : (
                  <div class={[styles.buyBtn]}>
                    {/* 判断是否是需要收费的 */}
                    {buyState.value.charge && (
                      <Button
                        round
                        type="primary"
                        color="linear-gradient(270deg, #FF204B 0%, #FE5B71 100%)"
                        class={styles.primary}
                        onClick={() => {
                          if (!browser().isApp) {
                            onDownloadApp()
                            return
                          }
                          onBuy()
                        }}
                      >
                        立即点播
                      </Button>
                    )}

                    {/* 判断是否有会员的 */}
                    {buyState.value.vip && (
                      <Button
                        round
                        block={!buyState.value.charge ? true : false}
                        type="primary"
                        color="linear-gradient(270deg, #FF204B 0%, #FE5B71 100%)"
                        class={styles.memeber}
                        onClick={() => {
                          if (!browser().isApp) {
                            onDownloadApp()
                            return
                          }
                          router.push({
                            path: '/memberCenter',
                            query: {
                              ...route.query
                            }
                          })
                        }}
                      >
                        {studentActivityId.value > 0 && (
                          <div class={[styles.buttonDiscount]}>专属优惠</div>
                        )}
                        开通会员
                      </Button>
                    )}
                  </div>
                )}
              </div>
            </div>
          </TheSticky>
        )}

        <Popup v-model:show={downloadStatus.value} position="bottom" round>
          {downloadStatus.value && (
            <Download
              imgList={JSON.parse(JSON.stringify(staffData.imgs))}
              musicSheetName={
                staffData.details.name +
                  (staffData.isConcert &&
                  currentColumn.value?.name
                    ? `(${
                        currentColumn.value?.name || ""
                      })`
                    : "")
              }
            />
          )}
        </Popup>

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

        <Popup
          teleport="body"
          position="bottom"
          round
          v-model:show={staffData.open}
        >
          <Picker
            columns={partColumns.value}
            defaultIndex={staffData.selectedPartIndex}
            onConfirm={value => {
              staffData.open = false;
              staffData.selectedPartIndex = value.value;
              staffData.imgs = [];
              nextTick(() => {
                const item = partColumns.value.find((child: any) => child.value === value.value)
                const tempPdf = getCurrentPdf(item, staff.radio)
                staffData.musicPdfUrl = tempPdf;
                if (tempPdf) {
                  renderStaff();
                } else {
                  loading.value = true;
                  if (staffData.musicPdfUrl) {
                    resetRender();
                  } else {
                    renderStaff();
                  }
                }
              });
            }}
            onCancel={() => (staffData.open = false)}
          />
        </Popup>
      </div>
    )
  }
})
