123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732 |
- import {
- computed,
- defineComponent,
- nextTick,
- onMounted,
- reactive,
- ref
- } 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,
- Dialog,
- Icon,
- Image,
- Popup,
- 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, musicBuy } from '../music'
- import { state } from '@/state'
- 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 '@/views/music/album/icon_share.svg'
- import iconAlbum from '@/views/music/component/images/icon_album.png'
- import iconDownload from './images/icon_download.png'
- import AstronautJSON from './animate/bigLoad.json'
- import ColShare from '@/components/col-share'
- import iconCollect from './images/icon_collect.png'
- import iconCollectActive from './images/icon_collect_active.png'
- import iconListen from './images/icon_listen.png'
- import iconTeacher from '@common/images/icon_teacher.png'
- import {
- addMusicTitle,
- addWatermark,
- convasToImg,
- imgToCanvas
- } from './imageFunction'
- import Plyr from 'plyr'
- import 'plyr/dist/plyr.css'
- export const getAssetsHomeFile = (fileName: string) => {
- const path = `../component/images/${fileName}`
- const modules = import.meta.globEager('../component/images/*')
- return modules[path].default
- }
- export default defineComponent({
- name: 'MusicDetail',
- setup() {
- localStorage.setItem('behaviorId', getRandomKey())
- const router = useRouter()
- const route = useRoute()
- const loading = ref(false)
- 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 musicDetail = ref<any>(null)
- const showImg = ref<string>('')
- const accompanyUrl = ref<string>('')
- const colors: any = {
- FREE: {
- color: '#01B84F',
- text: '免费'
- },
- VIP: {
- color: '#CD863E',
- text: '会员'
- },
- CHARGE: {
- color: '#3591CE',
- text: '点播'
- }
- }
- const FetchList = async (id?: any) => {
- if (loading.value) {
- return
- }
- loading.value = true
- isError.value = false
- try {
- const res = await request.get(`/music/sheet/detail/${route.query.id}`, {
- prefix:
- state.platformType === 'TEACHER' ? '/api-teacher' : '/api-student'
- })
- musicDetail.value = res.data
- showImg.value = res.data.musicImg || ''
- if (!showImg.value) {
- setAccompanyUrl()
- window.addEventListener(
- 'message',
- async e => {
- // 给图片设置背景色
- const tempCanvas = await imgToCanvas(e.data)
- const img = convasToImg(tempCanvas)
- // 开始上传图片
- uploadFunction(img)
- },
- false
- )
- }
- } catch (error) {
- isError.value = true
- }
- loading.value = false
- }
- const base64ToBlob = data => {
- const arr = data.split(','),
- mime = arr[0].match(/:(.*?);/)[1]
- const bstr = atob(arr[1])
- let n = bstr.length
- const u8arr = new Uint8Array(n)
- while (n--) {
- u8arr[n] = bstr.charCodeAt(n)
- }
- return new Blob([u8arr], { type: mime })
- }
- const uploadFunction = async file => {
- try {
- const formData = new FormData()
- const fileName =
- new Date().getTime() +
- musicDetail.value?.musicSheetName.replaceAll(' ', '_') +
- '.png'
- const keyTime = new Date().getTime() + fileName
- const obj = {
- filename: fileName,
- bucketName: 'cloud-coach',
- postData: {
- filename: fileName,
- acl: 'public-read',
- key: keyTime,
- unknowValueField: []
- }
- }
- const res = await request.post(state.platformApi + '/getUploadSign', {
- data: obj
- })
- Toast.loading({
- message: '加载中...',
- forbidClick: true,
- loadingType: 'spinner',
- duration: 0
- })
- const dataObj = {
- policy: res.data.policy,
- signature: res.data.signature,
- key: keyTime,
- KSSAccessKeyId: res.data.kssAccessKeyId,
- acl: 'public-read',
- name: fileName
- }
- for (const key in dataObj) {
- formData.append(key, dataObj[key])
- }
- const files = base64ToBlob(file)
- formData.append('file', files, fileName)
- const ossUploadUrl = 'https://ks3-cn-beijing.ksyuncs.com/cloud-coach'
- await umiRequest(ossUploadUrl, {
- method: 'POST',
- data: formData
- })
- Toast.clear()
- const imgurl = ossUploadUrl + '/' + keyTime
- await request.post(state.platformApi + '/open/music/sheet/img', {
- data: { musicSheetId: musicDetail.value.id, musicImg: imgurl }
- })
- showImg.value = imgurl
- } catch (e) {
- console.log(e)
- }
- }
- const setAccompanyUrl = () => {
- let url = location.host
- if (
- location.host.includes('dev.colexiu') ||
- location.host.includes('192.168') ||
- location.host.includes('localhost')
- ) {
- url = 'https://dev.colexiu.com'
- }
- const music = musicDetail.value
- let subjectId = ''
- if (music.background && music.background.length > 0) {
- subjectId = music.background[0].id
- }
- accompanyUrl.value =
- url +
- `/accompany/colxiu-website.html?id=${music.id}&part-index=${subjectId}`
- }
- const player = ref<any>(null)
- const audio = ref<any>(null)
- const freeRate = ref<any>(0)
- const initAudio = async () => {
- const config = await request.get(
- '/api-student/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 && !buyState.value.play) {
- players.stop()
- // players.pause()
- }
- })
- }
- onMounted(async () => {
- await FetchList()
- const { height } = useRect(headers as any)
- const footer = useRect(footers as any)
- heightInfo.value = height + footer.height
- // 初始化音频
- if (musicDetail.value?.audioFileUrl) {
- initAudio()
- }
- })
- const toggleFavorite = async () => {
- try {
- await request.post('/music/sheet/favorite/' + musicDetail.value?.id, {
- prefix:
- state.platformType === 'TEACHER' ? '/api-teacher' : '/api-student'
- })
- musicDetail.value.favorite = musicDetail.value?.favorite ? 0 : 1
- musicDetail.value.favoriteCount = musicDetail.value?.favorite
- ? musicDetail.value.favoriteCount + 1
- : musicDetail.value.favoriteCount - 1 < 0
- ? 0
- : musicDetail.value.favoriteCount - 1
- setTimeout(() => {
- Toast(musicDetail.value?.favorite ? '收藏成功' : '取消收藏成功')
- }, 100)
- } catch (error) {
- //
- }
- }
- const saveLoading = ref<boolean>(false)
- const image = ref('')
- const onSaveImg = async () => {
- // 判断是否在保存中...
- if (saveLoading.value) {
- return
- }
- saveLoading.value = true
- // 判断是否已经生成图片
- if (image.value) {
- saveImg()
- } else {
- const tempCanvas = await imgToCanvas(showImg.value)
- const titleCanvas = addMusicTitle(tempCanvas, {
- title: musicDetail.value?.musicSheetName,
- size: 18
- })
- const canvas = await addWatermark(titleCanvas, '酷乐秀')
- image.value = convasToImg(canvas)
- await saveImg()
- }
- }
- const saveImg = async () => {
- Toast.loading({
- message: '图片生成中...',
- forbidClick: true
- })
- setTimeout(() => {
- saveLoading.value = false
- }, 100)
- const res = await promisefiyPostMessage({
- api: 'savePicture',
- content: {
- base64: image.value
- }
- })
- if (res?.content?.status === 'success') {
- Toast.success('保存成功')
- } else {
- Toast.fail('保存失败')
- }
- }
- const onBuy = async () => {
- const music = musicDetail.value
- orderStatus.orderObject.orderType = 'MUSIC'
- orderStatus.orderObject.orderName = music.musicSheetName
- orderStatus.orderObject.orderDesc = music.musicSheetName
- 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.musicSheetName,
- actualPrice: 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: '您有一个未支付的订单,是否继续支付?',
- confirmButtonColor: '#269a93',
- 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()
- }
- }
- const routerTo = () => {
- const music = musicDetail.value
- 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 paymentType = computed(() => {
- let paymentType = musicDetail.value?.paymentType
- if (typeof paymentType === 'string') {
- paymentType = paymentType.split(',')
- return paymentType
- }
- return []
- })
- const buyState = computed(() => {
- const music = musicDetail.value
- return {
- 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 shareStatus = ref(false)
- const shareUrl = ref('')
- const shareDiscount = ref(0)
- // console.log(data)
- const onShare = async () => {
- try {
- const res = await request.post('/api-teacher/open/musicShareProfit', {
- data: {
- bizId: musicDetail.value?.id,
- userId: state.user.data?.userId
- }
- })
- let url =
- location.origin +
- `/teacher/#/shareMusic?id=${musicDetail.value?.id}&recomUserId=${state.user.data?.userId}&userType=${state.platformType}`
- // 判断是否有活动
- if (res.data.discount === 1) {
- url += `&activityId=${res.data.activityId}`
- }
- shareDiscount.value = res.data.discount || 0
- console.log(url)
- shareUrl.value = url
- shareStatus.value = true
- return
- } catch {}
- }
- return () => {
- return (
- <div class={styles.detail}>
- <Sticky position="top">
- <div ref={headers}>
- <ColHeader
- background="transparent"
- border={false}
- isFixed={false}
- color="#fff"
- title={musicDetail.value?.musicSheetName}
- backIconColor="white"
- v-slots={{
- right: () => (
- <div
- class={styles.shareBtn}
- style={{
- color: '#fff'
- }}
- onClick={onShare}
- >
- <Image src={iconShare} />
- 分享
- </div>
- )
- }}
- />
- </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={getAssetsHomeFile('icon_exquisite.png')}
- />
- )}
- {musicDetail.value?.albumNums > 0 && (
- <Image
- class={styles.songAlbum}
- src={getAssetsHomeFile('icon_album_active.png')}
- />
- )}
- <span class={styles.coomposer}>
- {musicDetail.value?.composer}
- </span>
- </p>
- </div>
- ),
- value: () => (
- <span class={styles.download} onClick={() => onSaveImg()}>
- <img src={iconDownload} />
- 下载曲谱
- </span>
- )
- }}
- />
- <div class={styles.musicContent}>
- <iframe
- id="containerPrint"
- ref="print"
- style="width: 100%;page-break-after:always; height: 0"
- src={accompanyUrl.value}
- />
- <p class={styles.musicTitle}>
- {musicDetail.value?.musicSheetName}
- </p>
- {showImg.value ? (
- <img src={showImg.value} alt="" class={styles.musicImg} />
- ) : (
- <>
- <Vue3Lottie
- animationData={AstronautJSON}
- class={styles.finch}
- ></Vue3Lottie>
- <p class={styles.finchLoad}>加载中...</p>
- </>
- )}
- <div class={styles.videoOperation}>
- {musicDetail.value?.audioFileUrl && (
- <>
- {!buyState.value.play && (
- <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={musicDetail.value?.audioFileUrl}
- 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={() => toggleFavorite()}
- >
- <span>{musicDetail.value?.favoriteCount}人收藏</span>
- <img
- src={
- musicDetail.value?.favorite
- ? iconCollectActive
- : iconCollect
- }
- />
- </div>
- </div>
- </div>
- </div>
- <div
- class={[styles.lookAlbum, styles.collectCell]}
- onClick={() => {
- router.push({
- path: '/look-album-list',
- query: {
- id: musicDetail.value?.id
- }
- })
- }}
- >
- <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}>
- {/* 判断是否是免费的,或者已经购买过 */}
- {buyState.value.play ? (
- <Button
- round
- block
- type="primary"
- color="linear-gradient(180deg, #59E5D5 0%, #2DC7AA 100%)"
- onClick={() => musicBuy(musicDetail.value)}
- >
- 立即练习
- </Button>
- ) : (
- <div class={styles.colSticky}>
- {/* 只有,有点播类型的才显示价格 */}
- {buyState.value.charge && (
- <div class={styles.priceSection}>
- <span>点播价:</span>
- <span class={styles.price}>
- <i>¥</i>
- {moneyFormat(musicDetail.value?.musicPrice)}
- </span>
- </div>
- )}
- <div class={[styles.buyBtn]}>
- {/* 判断是否是需要收费的 */}
- {buyState.value.charge && (
- <Button
- round
- type="primary"
- color="linear-gradient(180deg, #59E5D5 0%, #2DC7AA 100%)"
- class={styles.primary}
- onClick={onBuy}
- >
- 立即点播
- </Button>
- )}
- {/* 判断是否有会员的 */}
- {buyState.value.vip && (
- <Button
- round
- block={!buyState.value.charge ? true : false}
- type="primary"
- color="linear-gradient(180deg, #F7BD8D 0%, #CD8806 100%)"
- class={styles.memeber}
- onClick={() => {
- router.push({
- path: '/memberCenter',
- query: {
- ...route.query
- }
- })
- }}
- >
- {studentActivityId.value > 0 && (
- <div class={[styles.buttonDiscount]}>专属优惠</div>
- )}
- 开通会员
- </Button>
- )}
- </div>
- </div>
- )}
- </div>
- </ColSticky>
- )}
- <Popup
- v-model:show={shareStatus.value}
- style={{ background: 'transparent' }}
- teleport="body"
- >
- <ColShare
- teacherId={state.user.data?.userId}
- shareUrl={shareUrl.value}
- shareType="music"
- >
- <div class={styles.shareMate}>
- {shareDiscount.value === 1 && (
- <div class={styles.tagDiscount}>专属优惠</div>
- )}
- <img
- class={styles.icon}
- crossorigin="anonymous"
- src={
- musicDetail.value?.titleImg +
- `@base@tag=imgScale&h=80&w=80&m=1?t=${+new Date()}`
- }
- />
- <div class={styles.info}>
- <h4 class="van-multi-ellipsis--l2">
- {musicDetail.value?.musicSheetName}
- </h4>
- <p>作曲人:{musicDetail.value?.composer}</p>
- </div>
- </div>
- </ColShare>
- </Popup>
- </div>
- )
- }
- }
- })
|