import {
  defineComponent,
  toRefs,
  reactive,
  onMounted,
  ref,
  watch,
  nextTick
} from 'vue'
import classes from './index.module.less'
import { ElButton, ElOption, ElSelect, ElScrollbar } 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 teacher from '@/views/videoDetailList/images/teacher.png'
import teacherHeader from '@/common/images/icon_teacher.png'
import musiceIcon from '@/views/videoDetailList/images/musiceIcon.png'
import tagItem from '@/components/tagItem'
import code from './images/code.png'
import musicItem from './modals/musicItem'
import request from '@/helpers/request'
import { useRoute, useRouter } from 'vue-router'
import { getUserType, vaildTeachingUrl } from '@/helpers/utils'
import { imgToCanvas, addWatermark, convasToImg } from '@/helpers/imageFunction'
import arrow from '@/components/musicLIstItem/images/arrow.png'
import { Vue3Lottie } from 'vue3-lottie'
import 'vue3-lottie/dist/style.css'
import AstronautJSON from '@/common/animate/bigLoad.json'
import printJS from 'print-js'

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: ''
    })
   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}`,
          {}
        )

        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
        setAccompanyUrl()
        console.log('调用')
      } 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 = () => {
      let url = vaildTeachingUrl()
      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)
    }
    onMounted(() => {
      // window.setSvg = (val)=>{
      //   setSvg(val)
      // }
      window.addEventListener(
        'message',
        async e => {
          console.log(e)
          state.imgData = e.data
          // printHander()
          // alert(e.data);
          const tempCanvas = await imgToCanvas(state.imgData)
          const showImg = convasToImg(tempCanvas)
          state.showImg = showImg
        },
        false
      )
      state.userType = getUserType()
      state.showCode =
        state.userType == 'STUDENT' || !state.userType ? true : false
      // 拼链接
      getMusicList()
    })
    const printHander = async () => {
      const tempCanvas = await imgToCanvas(state.imgData)
      const showImg = convasToImg(tempCanvas)
      state.showImg = showImg
      console.log(state.showImg)
      const canvas = addWatermark(tempCanvas, '酷乐秀')
      const imgUrl = convasToImg(canvas)
      const link = document.createElement('a')
      link.setAttribute('download', state.musicDetail.musicSheetName + '.png')

      // 添加时间戳，防止浏览器缓存图片
      state.imgUrl = imgUrl
      // console.log('printHander',imgUrl)
      // return
      link.href = imgUrl
      link.click()
    }
    const gotoMusic = () => {
      router.push({
        path: '/searchdetail',
        query: { search: state.teacherDetail.userName as string, type: 'music' }
      })
    }
    return () => (
      <>
        <div class={classes.wall}></div>
        <div class={[classes.width1200, 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"*/}
              <iframe
                id="containerPrint"
                ref="print"
                style="width: 100%;page-break-after:always; "
                src={state.accompanyUrl}
                class={classes.iframe}
              />

              {state.showImg ? (
                <img src={state.showImg} alt="" />
              ) : (
                <div>
                  <Vue3Lottie
                    animationData={AstronautJSON}
                    class={classes.finch}
                  ></Vue3Lottie>
                  <p class={classes.finchLoad}>加载中...</p>
                </div>
              )}
              {}
            </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} alt="" />
                </div>
              </div>
            ) : null}

            {state.mp3Type == 'MP3' ? (
              <colVideo
                src={state.activeRow.audioFileUrl}
                styleValue={{
                  height: '68px',
                  bacground: '#333'
                }}
                type={'audto'}
                settings={['captions', 'quality', 'speed', 'loop']}
                class={classes.audios}
              ></colVideo>
            ) : <>
            <div  class={classes.noMoreWrap}>
                <img src={noMore} alt="" />
                <p>温馨提示：该曲目暂不支持播放喔～</p>
            </div>
            </>}
          </div>
          <div class={classes.right}>
            <div class={classes.musicInfo}>
              <h2>{state.musicDetail.musicSheetName}</h2>
              <div class={classes.collect}>
                <img src={start} class={classes.start} alt="" />
                <p>{state.musicDetail.favoriteNum}人收藏</p>
              </div>
              <div class={classes.tagList}>
                {state.tagList.map((item: any) => {
                  return <tagItem title={item}>{item}</tagItem>
                })}
              </div>
              <p class={classes.subTitle}>
                作曲人：<span>{state.musicDetail.composer}</span>
              </p>
              <p class={classes.subTitle}>
                声部：<span>{state.musicDetail.subjectNames}</span>
              </p>
            </div>
            <div class={classes.btooom}>
              {state.teacherDetail.userId ? (
                <div class={classes.teacherInfo}>
                  <div class={classes.teacherHeadWrap}>
                    <div class={classes.teacherHeadLeft}>
                      <img
                        src={
                          state.teacherDetail.avatar
                            ? state.teacherDetail.avatar
                            : teacherHeader
                        }
                        alt=""
                        class={classes.teacherHeader}
                      />
                      <div class={classes.teacherHeadInfo}>
                        <div class={classes.teacherHeadName}>
                          <span>{state.teacherDetail.userName}</span>
                          {/* {!state.teacherDetail.entryFlag ? (
                            ''
                          ) : (
                            <img
                              src={teacher}
                              class={classes.teacherIcon}
                              alt=""
                            />
                          )}
                          {!state.teacherDetail.musicianFlag ? (
                            ''
                          ) : (
                            <img
                              src={musiceIcon}
                              class={classes.teacherIcon}
                              alt=""
                            />
                          )} */}
                        </div>
                        <p class={classes.fens}>
                          粉丝 <span>{state.teacherDetail.fansNum}</span>
                        </p>
                      </div>
                    </div>
                    {state.userType == 'STUDENT' ? (
                      <div
                        class={[
                          classes.teacherHeadRight,
                          state.teacherDetail.star ? classes.isStart : ''
                        ]}
                        onClick={() => followVideo()}
                      >
                        {state.teacherDetail.star ? '已关注' : '关注'}
                      </div>
                    ) : null}
                  </div>
                </div>
              ) : null}

              <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>
          {/* <img src={state.imgUrl} alt="" /> */}
        </div>
      </>
    )
  }
})
