index.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  1. import {
  2. computed,
  3. defineComponent,
  4. nextTick,
  5. onMounted,
  6. reactive,
  7. ref
  8. } from 'vue'
  9. import umiRequest from 'umi-request'
  10. import { useRoute, useRouter } from 'vue-router'
  11. import request from '@/helpers/request'
  12. import ColHeader from '@/components/col-header'
  13. import { postMessage, promisefiyPostMessage } from '@/helpers/native-message'
  14. import {
  15. Button,
  16. Cell,
  17. Dialog,
  18. Icon,
  19. Image,
  20. Popup,
  21. Sticky,
  22. Tag,
  23. Toast
  24. } from 'vant'
  25. import styles from './index.module.less'
  26. // import Item from '../list/item'
  27. import { useRect } from '@vant/use'
  28. import { Vue3Lottie } from 'vue3-lottie'
  29. import { getRandomKey, musicBuy } from '../music'
  30. import { state } from '@/state'
  31. import { useEventTracking } from '@/helpers/hooks'
  32. import ColSticky from '@/components/col-sticky'
  33. import { moneyFormat } from '@/helpers/utils'
  34. import { orderStatus } from '@/views/order-detail/orderStatus'
  35. import iconShare from '@/views/music/album/icon_share.svg'
  36. import iconAlbum from '@/views/music/component/images/icon_album.png'
  37. import iconDownload from './images/icon_download.png'
  38. import AstronautJSON from './animate/bigLoad.json'
  39. import ColShare from '@/components/col-share'
  40. import iconCollect from './images/icon_collect.png'
  41. import iconCollectActive from './images/icon_collect_active.png'
  42. import iconListen from './images/icon_listen.png'
  43. import iconTeacher from '@common/images/icon_teacher.png'
  44. import {
  45. addMusicTitle,
  46. addWatermark,
  47. convasToImg,
  48. imgToCanvas
  49. } from './imageFunction'
  50. import Plyr from 'plyr'
  51. import 'plyr/dist/plyr.css'
  52. export const getAssetsHomeFile = (fileName: string) => {
  53. const path = `../component/images/${fileName}`
  54. const modules = import.meta.globEager('../component/images/*')
  55. return modules[path].default
  56. }
  57. export default defineComponent({
  58. name: 'MusicDetail',
  59. setup() {
  60. localStorage.setItem('behaviorId', getRandomKey())
  61. const router = useRouter()
  62. const route = useRoute()
  63. const loading = ref(false)
  64. const aId = Number(route.query.activityId) || 0
  65. const studentActivityId = ref(aId)
  66. const isError = ref(false)
  67. const headers = ref(null)
  68. const footers = ref(null)
  69. const heightInfo = ref<any>('0')
  70. const musicDetail = ref<any>(null)
  71. const showImg = ref<string>('')
  72. const accompanyUrl = ref<string>('')
  73. const colors: any = {
  74. FREE: {
  75. color: '#01B84F',
  76. text: '免费'
  77. },
  78. VIP: {
  79. color: '#CD863E',
  80. text: '会员'
  81. },
  82. CHARGE: {
  83. color: '#3591CE',
  84. text: '点播'
  85. }
  86. }
  87. const FetchList = async (id?: any) => {
  88. if (loading.value) {
  89. return
  90. }
  91. loading.value = true
  92. isError.value = false
  93. try {
  94. const res = await request.get(`/music/sheet/detail/${route.query.id}`, {
  95. prefix:
  96. state.platformType === 'TEACHER' ? '/api-teacher' : '/api-student'
  97. })
  98. musicDetail.value = res.data
  99. showImg.value = res.data.musicImg || ''
  100. if (!showImg.value) {
  101. setAccompanyUrl()
  102. window.addEventListener(
  103. 'message',
  104. async e => {
  105. // 给图片设置背景色
  106. const tempCanvas = await imgToCanvas(e.data)
  107. const img = convasToImg(tempCanvas)
  108. // 开始上传图片
  109. uploadFunction(img)
  110. },
  111. false
  112. )
  113. }
  114. } catch (error) {
  115. isError.value = true
  116. }
  117. loading.value = false
  118. }
  119. const base64ToBlob = data => {
  120. const arr = data.split(','),
  121. mime = arr[0].match(/:(.*?);/)[1]
  122. const bstr = atob(arr[1])
  123. let n = bstr.length
  124. const u8arr = new Uint8Array(n)
  125. while (n--) {
  126. u8arr[n] = bstr.charCodeAt(n)
  127. }
  128. return new Blob([u8arr], { type: mime })
  129. }
  130. const uploadFunction = async file => {
  131. try {
  132. const formData = new FormData()
  133. const fileName =
  134. new Date().getTime() +
  135. musicDetail.value?.musicSheetName.replaceAll(' ', '_') +
  136. '.png'
  137. const keyTime = new Date().getTime() + fileName
  138. const obj = {
  139. filename: fileName,
  140. bucketName: 'cloud-coach',
  141. postData: {
  142. filename: fileName,
  143. acl: 'public-read',
  144. key: keyTime,
  145. unknowValueField: []
  146. }
  147. }
  148. const res = await request.post(state.platformApi + '/getUploadSign', {
  149. data: obj
  150. })
  151. Toast.loading({
  152. message: '加载中...',
  153. forbidClick: true,
  154. loadingType: 'spinner',
  155. duration: 0
  156. })
  157. const dataObj = {
  158. policy: res.data.policy,
  159. signature: res.data.signature,
  160. key: keyTime,
  161. KSSAccessKeyId: res.data.kssAccessKeyId,
  162. acl: 'public-read',
  163. name: fileName
  164. }
  165. for (const key in dataObj) {
  166. formData.append(key, dataObj[key])
  167. }
  168. const files = base64ToBlob(file)
  169. formData.append('file', files, fileName)
  170. const ossUploadUrl = 'https://ks3-cn-beijing.ksyuncs.com/cloud-coach'
  171. await umiRequest(ossUploadUrl, {
  172. method: 'POST',
  173. data: formData
  174. })
  175. Toast.clear()
  176. const imgurl = ossUploadUrl + '/' + keyTime
  177. await request.post(state.platformApi + '/open/music/sheet/img', {
  178. data: { musicSheetId: musicDetail.value.id, musicImg: imgurl }
  179. })
  180. showImg.value = imgurl
  181. } catch (e) {
  182. console.log(e)
  183. }
  184. }
  185. const setAccompanyUrl = () => {
  186. let url = location.host
  187. if (
  188. location.host.includes('dev.colexiu') ||
  189. location.host.includes('192.168') ||
  190. location.host.includes('localhost')
  191. ) {
  192. url = 'https://dev.colexiu.com'
  193. }
  194. const music = musicDetail.value
  195. let subjectId = ''
  196. if (music.background && music.background.length > 0) {
  197. subjectId = music.background[0].id
  198. }
  199. accompanyUrl.value =
  200. url +
  201. `/accompany/colxiu-website.html?id=${music.id}&part-index=${subjectId}`
  202. }
  203. const player = ref<any>(null)
  204. const audio = ref<any>(null)
  205. const freeRate = ref<any>(0)
  206. const initAudio = async () => {
  207. const config = await request.get(
  208. '/api-student/sysConfig/queryByParamNameList',
  209. {
  210. params: {
  211. paramNames: 'music_sheet_free_rate'
  212. }
  213. }
  214. )
  215. freeRate.value = config.data[0]?.paramValue || 0
  216. const controls = [
  217. // 'play-large',
  218. 'play',
  219. 'progress',
  220. // 'captions',
  221. // 'fullscreen',
  222. 'duration'
  223. ]
  224. player.value = new Plyr(audio.value, {
  225. controls: controls
  226. })
  227. player.value.on('timeupdate', () => {
  228. // 允许播放时间
  229. const players = player.value
  230. const playTime = (players.duration * freeRate.value) / 100 || 0
  231. // 时间,不能播放
  232. if (players.currentTime >= playTime && !buyState.value.play) {
  233. players.stop()
  234. // players.pause()
  235. }
  236. })
  237. }
  238. onMounted(async () => {
  239. await FetchList()
  240. const { height } = useRect(headers as any)
  241. const footer = useRect(footers as any)
  242. heightInfo.value = height + footer.height
  243. // 初始化音频
  244. if (musicDetail.value?.audioFileUrl) {
  245. initAudio()
  246. }
  247. })
  248. const toggleFavorite = async () => {
  249. try {
  250. await request.post('/music/sheet/favorite/' + musicDetail.value?.id, {
  251. prefix:
  252. state.platformType === 'TEACHER' ? '/api-teacher' : '/api-student'
  253. })
  254. musicDetail.value.favorite = musicDetail.value?.favorite ? 0 : 1
  255. musicDetail.value.favoriteCount = musicDetail.value?.favorite
  256. ? musicDetail.value.favoriteCount + 1
  257. : musicDetail.value.favoriteCount - 1 < 0
  258. ? 0
  259. : musicDetail.value.favoriteCount - 1
  260. setTimeout(() => {
  261. Toast(musicDetail.value?.favorite ? '收藏成功' : '取消收藏成功')
  262. }, 100)
  263. } catch (error) {
  264. //
  265. }
  266. }
  267. const saveLoading = ref<boolean>(false)
  268. const image = ref('')
  269. const onSaveImg = async () => {
  270. // 判断是否在保存中...
  271. if (saveLoading.value) {
  272. return
  273. }
  274. saveLoading.value = true
  275. // 判断是否已经生成图片
  276. if (image.value) {
  277. saveImg()
  278. } else {
  279. const tempCanvas = await imgToCanvas(showImg.value)
  280. const titleCanvas = addMusicTitle(tempCanvas, {
  281. title: musicDetail.value?.musicSheetName,
  282. size: 18
  283. })
  284. const canvas = await addWatermark(titleCanvas, '酷乐秀')
  285. image.value = convasToImg(canvas)
  286. await saveImg()
  287. }
  288. }
  289. const saveImg = async () => {
  290. Toast.loading({
  291. message: '图片生成中...',
  292. forbidClick: true
  293. })
  294. setTimeout(() => {
  295. saveLoading.value = false
  296. }, 100)
  297. const res = await promisefiyPostMessage({
  298. api: 'savePicture',
  299. content: {
  300. base64: image.value
  301. }
  302. })
  303. if (res?.content?.status === 'success') {
  304. Toast.success('保存成功')
  305. } else {
  306. Toast.fail('保存失败')
  307. }
  308. }
  309. const onBuy = async () => {
  310. const music = musicDetail.value
  311. orderStatus.orderObject.orderType = 'MUSIC'
  312. orderStatus.orderObject.orderName = music.musicSheetName
  313. orderStatus.orderObject.orderDesc = music.musicSheetName
  314. orderStatus.orderObject.actualPrice = music.musicPrice
  315. orderStatus.orderObject.recomUserId = route.query.recomUserId || 0
  316. orderStatus.orderObject.activityId = route.query.activityId || 0
  317. orderStatus.orderObject.orderNo = ''
  318. orderStatus.orderObject.orderList = [
  319. {
  320. orderType: 'MUSIC',
  321. goodsName: music.musicSheetName,
  322. actualPrice: music.musicPrice,
  323. ...music
  324. }
  325. ]
  326. const res = await request.post('/api-student/userOrder/getPendingOrder', {
  327. data: {
  328. goodType: 'MUSIC',
  329. bizId: music.id
  330. }
  331. })
  332. const result = res.data
  333. if (result) {
  334. Dialog.confirm({
  335. title: '提示',
  336. message: '您有一个未支付的订单,是否继续支付?',
  337. confirmButtonColor: '#269a93',
  338. cancelButtonText: '取消订单',
  339. confirmButtonText: '继续支付'
  340. })
  341. .then(async () => {
  342. orderStatus.orderObject.orderNo = result.orderNo
  343. orderStatus.orderObject.actualPrice = result.actualPrice
  344. orderStatus.orderObject.discountPrice = result.discountPrice
  345. routerTo()
  346. })
  347. .catch(() => {
  348. Dialog.close()
  349. // 只用取消订单,不用做其它处理
  350. cancelPayment(result.orderNo)
  351. })
  352. } else {
  353. routerTo()
  354. }
  355. }
  356. const routerTo = () => {
  357. const music = musicDetail.value
  358. router.push({
  359. path: '/orderDetail',
  360. query: {
  361. orderType: 'MUSIC',
  362. musicId: music.id
  363. }
  364. })
  365. }
  366. const cancelPayment = async (orderNo: string) => {
  367. try {
  368. await request.post('/api-student/userOrder/orderCancel', {
  369. data: {
  370. orderNo
  371. }
  372. })
  373. } catch {}
  374. }
  375. const paymentType = computed(() => {
  376. let paymentType = musicDetail.value?.paymentType
  377. if (typeof paymentType === 'string') {
  378. paymentType = paymentType.split(',')
  379. return paymentType
  380. }
  381. return []
  382. })
  383. const buyState = computed(() => {
  384. const music = musicDetail.value
  385. return {
  386. play: music.play ? true : false, // 是否可以播放
  387. free: music?.paymentType.includes('FREE'),
  388. charge: music?.paymentType.includes('CHARGE'),
  389. vip: music?.paymentType.includes('VIP'),
  390. buy: music?.orderStatus === 'PAID' // 是否已买
  391. }
  392. })
  393. const shareStatus = ref(false)
  394. const shareUrl = ref('')
  395. const shareDiscount = ref(0)
  396. // console.log(data)
  397. const onShare = async () => {
  398. try {
  399. const res = await request.post('/api-teacher/open/musicShareProfit', {
  400. data: {
  401. bizId: musicDetail.value?.id,
  402. userId: state.user.data?.userId
  403. }
  404. })
  405. let url =
  406. location.origin +
  407. `/teacher/#/shareMusic?id=${musicDetail.value?.id}&recomUserId=${state.user.data?.userId}&userType=${state.platformType}`
  408. // 判断是否有活动
  409. if (res.data.discount === 1) {
  410. url += `&activityId=${res.data.activityId}`
  411. }
  412. shareDiscount.value = res.data.discount || 0
  413. console.log(url)
  414. shareUrl.value = url
  415. shareStatus.value = true
  416. return
  417. } catch {}
  418. }
  419. return () => {
  420. return (
  421. <div class={styles.detail}>
  422. <Sticky position="top">
  423. <div ref={headers}>
  424. <ColHeader
  425. background="transparent"
  426. border={false}
  427. isFixed={false}
  428. color="#fff"
  429. title={musicDetail.value?.musicSheetName}
  430. backIconColor="white"
  431. v-slots={{
  432. right: () => (
  433. <div
  434. class={styles.shareBtn}
  435. style={{
  436. color: '#fff'
  437. }}
  438. onClick={onShare}
  439. >
  440. <Image src={iconShare} />
  441. 分享
  442. </div>
  443. )
  444. }}
  445. />
  446. </div>
  447. </Sticky>
  448. <img class={styles.bgImg} src={musicDetail.value?.titleImg} />
  449. <div class={styles.bgContent}></div>
  450. <div
  451. class={styles.musicContainer}
  452. style={{
  453. marginTop: '16px',
  454. height: `calc(100vh - ${heightInfo.value + 16 + 'px'})`
  455. }}
  456. >
  457. <Cell
  458. border={false}
  459. center
  460. class={styles.musicInfo}
  461. v-slots={{
  462. icon: () => (
  463. <Image
  464. class={styles.pImg}
  465. src={musicDetail.value?.titleImg}
  466. />
  467. ),
  468. title: () => (
  469. <div class={styles.info}>
  470. <h4 class="van-ellipsis">
  471. {musicDetail.value?.musicSheetName}
  472. </h4>
  473. <p
  474. style={{
  475. display: 'flex'
  476. }}
  477. >
  478. {paymentType.value.map(tag => (
  479. <Tag
  480. style={{ color: colors[tag].color }}
  481. class={styles.tag}
  482. type="success"
  483. plain
  484. >
  485. {colors[tag].text}
  486. </Tag>
  487. ))}
  488. {musicDetail.value?.exquisiteFlag === 1 && (
  489. <Image
  490. class={styles.exquisiteFlag}
  491. src={getAssetsHomeFile('icon_exquisite.png')}
  492. />
  493. )}
  494. {musicDetail.value?.albumNums > 0 && (
  495. <Image
  496. class={styles.songAlbum}
  497. src={getAssetsHomeFile('icon_album_active.png')}
  498. />
  499. )}
  500. <span class={styles.coomposer}>
  501. {musicDetail.value?.composer}
  502. </span>
  503. </p>
  504. </div>
  505. ),
  506. value: () => (
  507. <span class={styles.download} onClick={() => onSaveImg()}>
  508. <img src={iconDownload} />
  509. 下载曲谱
  510. </span>
  511. )
  512. }}
  513. />
  514. <div class={styles.musicContent}>
  515. <iframe
  516. id="containerPrint"
  517. ref="print"
  518. style="width: 100%;page-break-after:always; height: 0"
  519. src={accompanyUrl.value}
  520. />
  521. <p class={styles.musicTitle}>
  522. {musicDetail.value?.musicSheetName}
  523. </p>
  524. {showImg.value ? (
  525. <img src={showImg.value} alt="" class={styles.musicImg} />
  526. ) : (
  527. <>
  528. <Vue3Lottie
  529. animationData={AstronautJSON}
  530. class={styles.finch}
  531. ></Vue3Lottie>
  532. <p class={styles.finchLoad}>加载中...</p>
  533. </>
  534. )}
  535. <div class={styles.videoOperation}>
  536. {musicDetail.value?.audioFileUrl && (
  537. <>
  538. {!buyState.value.play && (
  539. <div class={[styles.audition]}>
  540. <img src={iconListen} />
  541. <span>每首曲目可试听{freeRate.value}%</span>
  542. </div>
  543. )}
  544. <div class={[styles.audio, styles.collectCell]}>
  545. <audio id="player" controls ref={audio}>
  546. <source
  547. src={musicDetail.value?.audioFileUrl}
  548. type="audio/mp3"
  549. />
  550. </audio>
  551. </div>
  552. </>
  553. )}
  554. <div class={[styles.collect, styles.collectCell]}>
  555. <div class={[styles.userInfo]}>
  556. <img src={musicDetail.value?.userAvatar || iconTeacher} />
  557. <span>{musicDetail.value?.userName}</span>
  558. </div>
  559. <div
  560. class={[styles.collectSection]}
  561. onClick={() => toggleFavorite()}
  562. >
  563. <span>{musicDetail.value?.favoriteCount}人收藏</span>
  564. <img
  565. src={
  566. musicDetail.value?.favorite
  567. ? iconCollectActive
  568. : iconCollect
  569. }
  570. />
  571. </div>
  572. </div>
  573. </div>
  574. </div>
  575. <div
  576. class={[styles.lookAlbum, styles.collectCell]}
  577. onClick={() => {
  578. router.push({
  579. path: '/look-album-list',
  580. query: {
  581. id: musicDetail.value?.id
  582. }
  583. })
  584. }}
  585. >
  586. <div>
  587. <img src={iconAlbum} />
  588. <span>进入曲目所在专辑列表</span>
  589. </div>
  590. <Icon name="arrow" size={16} color="#666" />
  591. </div>
  592. </div>
  593. {musicDetail.value?.id && (
  594. <ColSticky position="bottom" background="white">
  595. <div ref={footers}>
  596. {/* 判断是否是免费的,或者已经购买过 */}
  597. {buyState.value.play ? (
  598. <Button
  599. round
  600. block
  601. type="primary"
  602. color="linear-gradient(180deg, #59E5D5 0%, #2DC7AA 100%)"
  603. onClick={() => musicBuy(musicDetail.value)}
  604. >
  605. 立即练习
  606. </Button>
  607. ) : (
  608. <div class={styles.colSticky}>
  609. {/* 只有,有点播类型的才显示价格 */}
  610. {buyState.value.charge && (
  611. <div class={styles.priceSection}>
  612. <span>点播价:</span>
  613. <span class={styles.price}>
  614. <i>¥</i>
  615. {moneyFormat(musicDetail.value?.musicPrice)}
  616. </span>
  617. </div>
  618. )}
  619. <div class={[styles.buyBtn]}>
  620. {/* 判断是否是需要收费的 */}
  621. {buyState.value.charge && (
  622. <Button
  623. round
  624. type="primary"
  625. color="linear-gradient(180deg, #59E5D5 0%, #2DC7AA 100%)"
  626. class={styles.primary}
  627. onClick={onBuy}
  628. >
  629. 立即点播
  630. </Button>
  631. )}
  632. {/* 判断是否有会员的 */}
  633. {buyState.value.vip && (
  634. <Button
  635. round
  636. block={!buyState.value.charge ? true : false}
  637. type="primary"
  638. color="linear-gradient(180deg, #F7BD8D 0%, #CD8806 100%)"
  639. class={styles.memeber}
  640. onClick={() => {
  641. router.push({
  642. path: '/memberCenter',
  643. query: {
  644. ...route.query
  645. }
  646. })
  647. }}
  648. >
  649. {studentActivityId.value > 0 && (
  650. <div class={[styles.buttonDiscount]}>专属优惠</div>
  651. )}
  652. 开通会员
  653. </Button>
  654. )}
  655. </div>
  656. </div>
  657. )}
  658. </div>
  659. </ColSticky>
  660. )}
  661. <Popup
  662. v-model:show={shareStatus.value}
  663. style={{ background: 'transparent' }}
  664. teleport="body"
  665. >
  666. <ColShare
  667. teacherId={state.user.data?.userId}
  668. shareUrl={shareUrl.value}
  669. shareType="music"
  670. >
  671. <div class={styles.shareMate}>
  672. {shareDiscount.value === 1 && (
  673. <div class={styles.tagDiscount}>专属优惠</div>
  674. )}
  675. <img
  676. class={styles.icon}
  677. crossorigin="anonymous"
  678. src={
  679. musicDetail.value?.titleImg +
  680. `@base@tag=imgScale&h=80&w=80&m=1?t=${+new Date()}`
  681. }
  682. />
  683. <div class={styles.info}>
  684. <h4 class="van-multi-ellipsis--l2">
  685. {musicDetail.value?.musicSheetName}
  686. </h4>
  687. <p>作曲人:{musicDetail.value?.composer}</p>
  688. </div>
  689. </div>
  690. </ColShare>
  691. </Popup>
  692. </div>
  693. )
  694. }
  695. }
  696. })