import {
  defineComponent,
  toRefs,
  reactive,
  onMounted,
  ref,
  watch,
  nextTick,
  onDeactivated
} from 'vue'
import classes from './index.module.less'
import {
  ElButton,
  ElOption,
  ElSelect,
  ElScrollbar,
  ElMessageBox
} from 'element-plus'
import printIcon from './images/printIcon.png'
import noMore from './images/noMore.png'
import banner from './images/banner.png'
import colVideo from '@/components/col-video/index'
import iconClose from '@/views/login/images/icon_close.png'
import start from '@/components/albumItem/images/start.png'
import lineStart from '@/components/albumItem/images/lineStart.png'
import oStart from '@/common/images/oStart.png'
import oLineStart from '@/common/images/oLineStart.png'
import teacher from '@/views/videoDetailList/images/teacher.png'
import teacherHeader from '@/common/images/icon_teacher.png'
import musiceIcon from '@/views/videoDetailList/images/musiceIcon.png'
import music from '@/components/musicLIstItem/images/music.png'
import tagItem from '@/components/tagItem'
import code from '@/common/images/student_download.png'
import musicItem from './modals/musicItem'

import ablumIcon from '@/components/col-header/images/ablumIcon.png'
import noAblumIcon from '@/components/col-header/images/noAblumIcon.png'
import onlineIcon from '@/components/col-header/images/onlineIcon.png'
import noOnlineIcon from '@/components/col-header/images/noOnlineIcon.png'
import styleIcon from '@/components/col-header/images/styleIcon.png'
import nostyleIcon from '@/components/col-header/images/noStyleIcon.png'
import videoIcon from '@/components/col-header/images/videoIcon.png'
import noVideoIcon from '@/components/col-header/images/noVideoIcon.png'
import vipIcon from '@/components/col-header/images/vipIcon.png'
import noVipIcon from '@/components/col-header/images/noVipIcon.png'
import umiRequest from 'umi-request'
import request from '@/helpers/request'
import { useRoute, useRouter } from 'vue-router'
import gou from './images/gou.png'
import member from './images/member.png'
import palyer from './images/palyer.png'
import { extend } from 'umi-request'
// import vipIcon from '../images/vipIcon.png'
import {
  getUserType,
  vaildTeachingUrl,
  getAuth,
  setAuth
} from '@/helpers/utils'
import { state as states } from '@/state'
import {
  imgToCanvas,
  addWatermark,
  convasToImg,
  addMusicTitle
} from '@/helpers/imageFunction'
import arrow from '@/views/home/images/moreArrow.png'
import { Vue3Lottie } from 'vue3-lottie'
import 'vue3-lottie/dist/style.css'
import AstronautJSON from '@/common/animate/bigLoad.json'
import printJS from 'print-js'
const chargeTypes = {
  CHARGE: '点播',
  FREE: '免费',
  VIP: '会员'
}
const chargeImg = {
  CHARGE: palyer,
  FREE: gou,
  VIP: member
}
const chargeClass = {
  CHARGE: 'charge',
  FREE: 'gou',
  VIP: 'member'
}
export default defineComponent({
  name: 'muiscDetial',
  props: {
    title: {
      type: String,
      default: ''
    }
  },
  components: {
    colVideo,
    tagItem,
    musicItem,
    Vue3Lottie
  },
  setup(props, conent) {
    const route = useRoute()
    const router = useRouter()
    const state = reactive({
      title: props.title,
      id: route.query.id,
      subjectId: '',
      subjectList: [],
      tagList: [],
      teacherDetail: {} as any,
      musicDetail: {} as any,
      musicList: [],
      mp3Type: '',
      activeRow: {} as any,
      showCode: false,
      userType: '',
      accompanyUrl: '',
      imgData: '',
      imgUrl: '',
      showImg: '',
      iconList: [] as any,
      // ossUploadUrl: 'https://ks3-cn-beijing.ksyuncs.com/cloud-coach',
      ossUploadUrl: `https://cloud-coach.ks3-cn-beijing.ksyuncs.com/`,
      dataObj: {
        policy: '',
        signature: '',
        key: '',
        KSSAccessKeyId: '',
        acl: 'public-read',
        name: ''
      },
      fileList: [] as any
    })
    nextTick(() => {
      // 禁用右键
      // @ts-ignore：无法被执行的代码的错误
      document.oncontextmenu = new Function('event.returnValue=false')
      // @ts-ignore：无法被执行的代码的错误
      // 禁用选择
      document.onselectstart = new Function('event.returnValue=false')
      // @ts-ignore：无法被执行的代码的错误
      //禁止f12
      document.οnkeydοwn = new Function('event.returnValue=false')
    })

    // 上面的禁止f12那段代码没有生效，但是加了下面这段就能生效。
    document.onkeydown = function (e) {
      if (e && e.keyCode === 123) {
        e.returnValue = false
        // e.keyCode = 0   //去掉也可以的，倘若要写，则需要setter 以及 getter配合使用，不配合，会报错
        return false
      }
    }
    const print = ref()
    const getMusicList = async () => {
      try {
        const res = await request.get(
          `/api-website/open/music/sheet/detail/${state.id}`,
          {
            params: {
              clientType: getUserType()
            }
          }
        )
        res.data.paymentType = res.data.paymentType.split(',')
        state.musicDetail = res.data
        state.musicList = res.data.teacher.musicSheetList
        state.subjectList = res.data.background
        state.tagList = res.data.musicTagNames
          ? res.data.musicTagNames.split(',')
          : []
        state.mp3Type = res.data.audioType
        if (state.subjectList && state.subjectList.length > 0) {
          state.activeRow = res.data.background[0]
          state.subjectId = res.data.background[0].id
        }

        state.teacherDetail = res.data.teacher
        if (res.data.musicImg) {
          // 有图片
          state.showImg = res.data.musicImg
        } else {
          window.addEventListener(
            'message',
            async e => {
              console.log(e)
              state.imgData = e.data

              // alert(e.data);
              const tempCanvas = await imgToCanvas(state.imgData)
              const showImg = convasToImg(tempCanvas)

              //  开始上传图片
              uploadFunction(showImg)
            },
            false
          )
        }
        setAccompanyUrl()
        setUser()
      } catch (e) {
        console.log(e)
      }
    }
    const followVideo = async () => {
      try {
        const res = await request.get('/api-website/student/starOrUnStar', {
          params: {
            userId: state.teacherDetail.userId,
            starStatus: state.teacherDetail.star ? 0 : 1
          }
        })
        getMusicList()
        // state.otherVideoList = res.data
      } catch (e) {
        console.log(e)
      }
    }
    const getDetail = (val: string | number) => {
      state.id = val as string
      router.push({
        query: { ...route.query, id: state.id }
      })
      state.showImg = ''
      getMusicList()
    }
    watch(
      () => state.accompanyUrl,
      accompanyUrl => {
        state.accompanyUrl = accompanyUrl
      }
    )
    const setAccompanyUrl = () => {
      const url = 'https://dev.colexiu.com'
      state.accompanyUrl =
        url +
        `/accompany/colxiu-website.html?id=${state.id}&part-index=${state.subjectId}`
      // state.accompanyUrl = `http://192.168.3.8:3000/colxiu-website.html?id=${state.id}&part-index=${state.subjectId}`
    }
    const setSvg = (val: any) => {
      console.log(val)
    }
    // const goIndex = () => {
    //   router.push({
    //     name: 'searchdetail',
    //     params: { type: 'music' }
    //   })
    // }
    onMounted(() => {
      // window.setSvg = (val)=>{
      //   setSvg(val)
      // }
      getMusicList()

      state.userType = getUserType()
      state.showCode =
        state.userType == 'STUDENT' || !state.userType ? true : false

      // if (window.history && window.history.pushState) {
      //   history.pushState(null, '', document.URL)
      //   window.addEventListener('popstate', goIndex, false)
      // }

      // 拼链接
    })
    onDeactivated(() => {
      // window.removeEventListener('popstate', goIndex, false)
    })
    const base64ToBlob = data => {
      var arr = data.split(','),
        mime = arr[0].match(/:(.*?);/)[1]

      let bstr = atob(arr[1])
      let n = bstr.length
      let 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()
        let fileName =
          new Date().getTime() + Math.ceil(Math.random() * 1000) + '.png'
        let key = new Date().getTime() + fileName
        let obj = {
          filename: fileName,
          bucketName: 'cloud-coach',
          postData: {
            filename: fileName,
            acl: 'public-read',
            key: key,
            unknowValueField: []
          }
        }

        const res = await request.post('/api-website/open/getUploadSign', {
          data: obj
        })

        state.dataObj = {
          policy: res.data.policy,
          signature: res.data.signature,
          key: key,
          KSSAccessKeyId: res.data.kssAccessKeyId,
          acl: 'public-read',
          name: fileName
        }
        for (let key in state.dataObj) {
          formData.append(key, state.dataObj[key])
        }
        // const imgRes = await fetch(file)
        const files = base64ToBlob(file)
        // const files = await imgRes.blob()

        formData.append('file', files, fileName)
        await umiRequest(state.ossUploadUrl, {
          method: 'POST',
          data: formData
        })

        let imgurl = state.ossUploadUrl + key
        const ress = await request.post('/api-website/open/music/sheet/img', {
          data: { musicSheetId: state.musicDetail.id, musicImg: imgurl }
        })
        console.log('赋值')
        state.showImg = imgurl
      } catch (e) {
        console.log(e)
      }
    }

    const setUser = () => {
      state.iconList = [] as any
      if (state.teacherDetail.tag.indexOf('STYLE') != -1) {
        state.iconList.push(styleIcon)
      } else {
        state.iconList.push(nostyleIcon)
      }
      if (state.teacherDetail.tag.indexOf('VIDEO') != -1) {
        state.iconList.push(videoIcon)
      } else {
        state.iconList.push(noVideoIcon)
      }
      if (state.teacherDetail.tag.indexOf('LIVE') != -1) {
        state.iconList.push(onlineIcon)
      } else {
        state.iconList.push(noOnlineIcon)
      }
      if (state.teacherDetail.tag.indexOf('MUSIC') != -1) {
        state.iconList.push(ablumIcon)
      } else {
        state.iconList.push(noAblumIcon)
      }
    }
    const printHander = async () => {
      //  img 转 canvas
      const tempCanvas = await imgToCanvas(state.showImg)
      const showImg = convasToImg(tempCanvas)
      state.showImg = showImg
      const titleCanvas = addMusicTitle(tempCanvas, {
        title: state.musicDetail.musicSheetName,
        size: 18
      })
      const canvas = await addWatermark(titleCanvas, '酷乐秀')

      const imgUrl = convasToImg(canvas)
      const link = document.createElement('a')
      link.setAttribute('download', state.musicDetail.musicSheetName + '.png')
      // 添加时间戳，防止浏览器缓存图片
      // console.log(imgUrl,'imgUrl')
      state.imgUrl = imgUrl
      link.href = imgUrl
      link.click()
    }
    const gotoMusic = () => {
      router.push({
        name: 'musicLibrary',
        query: {
          search: state.teacherDetail.userName as string,
          type: 'music'
        }
      })
    }

    const favoriteMusic = async () => {
      const tockn = getAuth()
      if (!tockn) {
        states.loginPopupStatus = true
        return
      }
      ElMessageBox.confirm(
        `是否${state.musicDetail.favorite ? '取消收藏' : '收藏'}该曲目？`,
        '提示',
        {
          type: 'warning'
        }
      ).then(async () => {
        try {
          const res = await request.post(
            `/api-website/music/sheet/favorite/${state.id}`,
            {
              params: {
                clientType: getUserType()
              }
            }
          )
          getMusicList()
          // state.otherVideoList = res.data
        } catch (e) {
          console.log(e)
        }
      })
    }
    return () => (
      <>
        <div class={classes.wallWrap}>
          <div class={classes.wall}></div>
          <div class={classes.musicWraps}>
            <div class={[classes.width1200]}>
              <div class={[classes.musicWrap]}>
                <div class={classes.left}>
                  <div class={classes.title}>
                    {/* <div class={classes.titleLeft}>
                    <p>声部：</p>
                    <ElSelect
                      class="w-full subjectChiose"
                      v-model={state.subjectId}
                      placeholder="请选择声部"
                      onChange={() => {
                        setAccompanyUrl()
                      }}
                    >
                      {state.subjectList.map((item: any) => (
                        <ElOption
                          key={item.id}
                          value={item.id}
                          label={item.track}
                        />
                      ))}
                    </ElSelect>
                  </div> */}
                    <div
                      class={classes.titleRight}
                      onClick={() => printHander()}
                    >
                      <img src={printIcon} alt="" />
                      <p>下载乐谱</p>
                    </div>
                  </div>

                  <div class={classes.musicContent}>
                    {/*        id="iframe"       ref="iframe"*/}

                    <img
                      class={classes.musicStag}
                      src={chargeImg[state.musicDetail.chargeType]}
                      alt=""
                    />
                    <iframe
                      id="containerPrint"
                      ref="print"
                      style="width: 538px;page-break-after:always; "
                      src={state.accompanyUrl}
                      class={classes.iframe}
                    />
                    <p class={classes.musicTitle}>
                      {state.musicDetail.musicSheetName}
                    </p>
                    {state.showImg ? (
                      <img src={state.showImg} alt="" />
                    ) : (
                      <div>
                        <Vue3Lottie
                          animationData={AstronautJSON}
                          class={classes.finch}
                        ></Vue3Lottie>
                        <p class={classes.finchLoad}>加载中...</p>
                      </div>
                    )}
                  </div>

                  {state.mp3Type == 'MP3' ? (
                    <colVideo
                      src={state.activeRow.audioFileUrl}
                      styleValue={{
                        height: '68px',
                        bacground: '#333'
                      }}
                      type={'audto'}
                      settings={[
                        'captions',
                        'quality',
                        'speed',
                        'loop',
                        'title'
                      ]}
                      class={classes.audios}
                      poster={state.activeRow.title}
                    ></colVideo>
                  ) : (
                    <>
                      <div class={classes.noMoreWrap}>
                        <img src={noMore} alt="" />
                        <p>温馨提示：该曲目暂不支持播放喔～</p>
                      </div>
                    </>
                  )}

                  {state.showCode ? (
                    <div class={classes.showCode}>
                      <div class={classes.showCodeWrap}>
                        <img
                          class={classes.close}
                          src={iconClose}
                          alt=""
                          onClick={() => {
                            state.showCode = false
                          }}
                        />
                        <img class={classes.code} src={code} alt="" />
                        {/* <h2 class={classes.title}>酷乐秀</h2>
                  <p class={classes.conent}>扫码下载酷乐秀APP</p>
                  <p class={classes.subConent}>
                    使用小酷Ai即可智能练习本首曲目哦！
                  </p> */}
                        <img src={banner} class={classes.banner} alt="" />
                      </div>
                    </div>
                  ) : null}
                </div>
                <div class={classes.right}>
                  <div class={classes.musicInfo}>
                    <h2>
                      {Array.isArray(state.musicDetail.paymentType) &&
                        state.musicDetail.paymentType.map((tag: string) => (
                          <span
                            class={[
                              classes.musicTag,
                              classes[chargeClass[tag]]
                            ]}
                          >
                            {chargeTypes[tag]}
                          </span>
                        ))}

                      {state.musicDetail.musicSheetName}
                    </h2>
                    <div class={classes.collectWrap}>
                      <div class={classes.masker} onClick={favoriteMusic}>
                        <img
                          src={state.musicDetail.favorite ? lineStart : start}
                          alt=""
                        />
                      </div>
                      <img
                        src={state.musicDetail.titleImg || music}
                        class={classes.musiceIcon}
                        alt=""
                      />
                      <div>
                        <div class={classes.collect} onClick={favoriteMusic}>
                          <img
                            src={
                              state.musicDetail.favorite ? oLineStart : oStart
                            }
                            class={classes.start}
                            alt=""
                          />
                          <p>{state.musicDetail.favoriteNum}人收藏</p>
                        </div>

                        <div class={classes.tagList}>
                          {state.tagList.map((item: any) => {
                            return <div class={classes.tag}>{item}</div>
                          })}
                        </div>
                        <p class={classes.subTitle}>
                          作曲人：<span>{state.musicDetail.composer}</span>
                        </p>
                        <p class={classes.subTitle}>
                          声部：<span>{state.musicDetail.subjectNames}</span>
                        </p>
                      </div>
                    </div>
                  </div>
                  <div class={classes.btooom}>
                    {state.teacherDetail.userId ? (
                      <div class={classes.teacherInfo}>
                        <h2>上传者</h2>
                        <div class={classes.teacherHeadWrap}>
                          <div class={classes.teacherHeadLeft}>
                            <img
                              src={
                                state.teacherDetail.userAvatar
                                  ? state.teacherDetail.userAvatar
                                  : teacherHeader
                              }
                              alt=""
                              class={classes.teacherHeader}
                            />
                            <div class={classes.teacherHeadInfo}>
                              <div class={classes.teacherHeadName}>
                                <p>{state.teacherDetail.userName}</p>
                                {/* {!state.teacherDetail.entryFlag ? (
                            ''
                          ) : (
                            <img
                              src={teacher}
                              class={classes.teacherIcon}
                              alt=""
                            />
                          )}
                          {!state.teacherDetail.musicianFlag ? (
                            ''
                          ) : (
                            <img
                              src={musiceIcon}
                              class={classes.teacherIcon}
                              alt=""
                            />
                          )} */}
                                {state.userType == 'STUDENT' ? (
                                  <div
                                    class={[
                                      classes.teacherHeadRight,
                                      state.teacherDetail.star
                                        ? classes.isStart
                                        : ''
                                    ]}
                                    onClick={() => followVideo()}
                                  >
                                    {state.teacherDetail.star
                                      ? '已关注'
                                      : '+ 关注'}
                                  </div>
                                ) : (
                                  <div class={classes.iconWrapList}>
                                    <img
                                      src={
                                        state.teacherDetail.isVip
                                          ? vipIcon
                                          : noVipIcon
                                      }
                                      class={classes.vipIcon}
                                      alt=""
                                    />
                                    {state.iconList.map(item => (
                                      <img
                                        class={classes.teacherDetailIcon}
                                        src={item}
                                        alt=""
                                      />
                                    ))}
                                  </div>
                                )}
                              </div>
                            </div>
                          </div>
                          <div>
                            <p class={classes.fensNum}>
                              {state.teacherDetail.fansNum}
                            </p>
                            <p class={classes.fens}>粉丝数</p>
                          </div>
                        </div>
                      </div>
                    ) : null}

                    {state.musicList.length > 0 && (
                      <div class={classes.otherMusic}>
                        <div class={classes.videoNav}>
                          <h5>TA的曲谱</h5>
                          <div
                            class={classes.wrapRight}
                            onClick={() => gotoMusic()}
                          >
                            <span>更多</span>
                            <img class={classes.arrow} src={arrow} alt="" />
                          </div>
                        </div>

                        <div class={classes.otherMusicList}>
                          {state.musicList.map(item => {
                            return (
                              <musicItem
                                item={item}
                                onMusicDetail={val => getDetail(val)}
                              ></musicItem>
                            )
                          })}
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </>
    )
  }
})
