import { defineComponent, onMounted, Ref, ref, watch } from 'vue'
import request from '/src/helpers/request'
import originRequest from 'umi-request'
import MusicSheet from '/src/music-sheet'
import { formatXML, onlyVisible, getCustomInfo } from '/src/pages/detail/helpers'
import { useOriginSearch } from '../colexiu/uses'
import styles from '../colexiu/index.module.less'
import detailStyles from './index.module.less'
import { OpenSheetMusicDisplay } from '/osmd-extended/src'
import { MusicSheelDetail, ShaeetStatusType } from '../colexiu/index.d'
import wxbg from './wx_bg.png'
import qs from 'query-string'
import { Button, Dialog, Popup, Skeleton, Toast, Image } from 'vant'
import Empty from '/src/components/empty'
import { browser, getRequestHostname } from '/src/helpers/utils'
import { postMessage } from '/src/helpers/native-message'
import { startRun } from './wr'
import RightIcon from './right.svg'

type IPolicy = {
  kssAccessKeyId: string
  policy: string
  signature: string
}

const browserInfo = browser()

const search = useOriginSearch()

const discounts = ref<0 | 1>(0)

const awaken = () => {
  if (browserInfo.isApp) {
    if (browserInfo.isTeacher) {
      Dialog.alert({
        message: '请使用酷乐秀学生端扫码打开',
      }).then(() => {
        postMessage({ api: 'back' })
      })
      return
    }
    const behaviorId = sessionStorage.getItem('behaviorId') || '' + new Date().valueOf()
    const url = qs.stringifyUrl({
      url: location.origin + '/orchestra-music-score',
      query: {
        id: search.id as string,
        behaviorId,
        client: browserInfo.isTeacher ? 'teacher' : 'student',
        recomUserId: search.userType && search.userType == 'STUDENT' ? '' : (search.recomUserId as string),
        activityId: (search.activityId || '0') as string,
        discounts: discounts.value,
      },
    })
    postMessage({
      api: 'openAccompanyWebView',
      content: {
        url,
        // url: 'http://192.168.3.13:3000/colexiu.html?id=' + item.id,
        orientation: 0,
        isHideTitle: true,
        statusBarTextColor: false,
        isOpenLight: true,
      },
    })
    return
  }
  const { origin } = location
  let str = origin + '/student/#/share-music-sheet'
  str += `?recomUserId=${search.userType && search.userType == 'STUDENT' ? '' : search.recomUserId}&id=${search.id}&activityId=${search.activityId || '0'}`

  const query = {
    url: str,
    action: search.action || 'h5', // app, h5
    pageTag: search.pageTag || 1, // 页面标识
  }
  // alert(str)
  const iosStr = encodeURIComponent(JSON.stringify(query))
  if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
    // ColexiuStudent 唤起学生端
    window.location.href = `ColexiuStudent://linkUrl=${iosStr}`
  } else if (/(Android)/i.test(navigator.userAgent)) {
    query.url = encodeURIComponent(query.url)
    window.location.href = `colexiustudent://html:8888/SplashActivity?url=${encodeURIComponent(JSON.stringify(query))}`
  } else {
    Toast('请用手机或移动设备打开')
  }
}

const useXml = async (url: string, detail: MusicSheelDetail) => {
  const xml = await originRequest(url)
  let score = ref<string>('')
  const parseXmlInfo = getCustomInfo(xml)
  score.value = formatXML(parseXmlInfo.parsedXML, {
    title: detail.musicSheetName,
  })
  const partIndex = Number(search['part-index']) || 0
  score.value = onlyVisible(score.value, partIndex)
  // detailState.partIndex = partIndex
  return score
}

const useDetail = (id: number | string): [Ref<ShaeetStatusType>, Ref<MusicSheelDetail>, Ref<any>, Ref<boolean>] => {
  const status = ref<ShaeetStatusType>('loading')
  const data = ref<MusicSheelDetail>({})
  const user = ref<any>({})
  const activityCheck = ref(false)
  onMounted(async () => {
    if (search.activityId) {
      request
        .post('/open/activity/state/' + search.activityId, {
          prefix: '/api-teacher',
        })
        .then((res) => {
          discounts.value = res.data.check
          activityCheck.value = !!res.data.check
          if (!activityCheck.value) {
            Dialog.alert({
              message: '优惠活动已结束，您将按原价购买',
            })
          }
        })
        .catch(() => {})
    }
    status.value = 'loading'
    try {
      const res = await request.post(`/open/musicShareProfit`, {
        prefix: getRequestHostname(),
        requestType: 'json',
        data: {
          bizId: search.id,
          userId: search.recomUserId,
        },
      })
      const { musicSheet, ...rest } = res.data
      data.value = { ...musicSheet }
      user.value = rest
      // detailState.partIndex = recordRes.data.partIndex || 0
      status.value = 'success'
    } catch (error) {
      status.value = 'error'
      console.log(error)
    }
  })
  return [status, data, user, activityCheck]
}

export default defineComponent({
  name: 'Colexiu',
  setup() {
    const wxshow = ref(false)
    const renderLoading = ref(true)
    const renderError = ref(false)
    const score = ref<string>('')
    const musicImg = ref('')
    const [detailStatus, detail, record, activityCheck] = useDetail(search.id as string)
    watch(detailStatus, async () => {
      if (detailStatus.value === 'success' && detail.value.xmlFileUrl) {
        if (detail.value.musicImg) {
          renderLoading.value = false
          musicImg.value = await startRun(detail.value.musicImg + '?_t=' + new Date().valueOf())
          return
        }
        const xml = await useXml(detail.value.xmlFileUrl, detail.value)
        // console.log(runtime.songs, detailState.partListNames)
        score.value = xml.value
      }
    })

    const setWatermark = (osmd: OpenSheetMusicDisplay) => {
      const w = 240,
        h = 200
      const backend = osmd.Drawer.Backends[0]
      const maxEdge = Math.max(backend.width, backend.height)
      const xWatermark = Math.floor(maxEdge / w) * 5
      const yWatermark = Math.floor(maxEdge / h) * 5
      // @ts-ignore
      const ctx: CanvasRenderingContext2D = backend.CanvasRenderingCtx
      ctx.font = '50px 宋体'
      ctx.fillStyle = 'rgba(0,0,0,.1)'
      ctx.rotate((-30 * Math.PI) / 180)

      for (let i = 0; i < xWatermark; i++) {
        for (let j = 0; j < yWatermark; j++) {
          ctx.fillText('酷乐秀', i * w - maxEdge, j * h - maxEdge / 2)
        }
      }
    }

    const policy = (params: object) => {
      return request(`/open/getUploadSign`, {
        method: 'post',
        data: params,
        requestType: 'json',
      } as any)
    }

    const uploadMusicSheet = async (fileName: string) => {
      const key = fileName
      return policy({
        filename: fileName,
        bucketName: 'daya',
        postData: {
          filename: fileName,
          acl: 'public-read',
          key,
          unknowValueField: [],
        },
      }) as Promise<{
        data: IPolicy
      }>
    }

    const musicSheetUpload = async (img: string, fileName: string, policy: IPolicy) => {
      const file = await originRequest(img, {
        responseType: 'blob',
      })
      const formData = new FormData()
      formData.append('policy', policy.policy)
      formData.append('signature', policy.signature)
      formData.append('acl', 'public-read')
      formData.append('KSSAccessKeyId', policy.kssAccessKeyId)
      formData.append('name', fileName)
      formData.append('key', fileName)
      formData.append('file', file)
      const res = await originRequest('https://ks3-cn-beijing.ksyuncs.com/daya', {
        method: 'POST',
        body: formData,
      })
      console.log(res)
      // if (res.status === 200) {
      await originRequest('/api-student/open/music/sheet/img', {
        method: 'post',
        data: {
          musicImg: 'https://ks3-cn-beijing.ksyuncs.com/daya/' + fileName,
          musicSheetId: detail.value.id,
        },
      })
      // state.forms.musicImg =
      // 'https://ks3-cn-beijing.ksyuncs.com/daya/' + fileName
      // }
      // console.log(state.forms.musicImg)
    }

    const onRerender = async (osmd: OpenSheetMusicDisplay) => {
      try {
        const fileName = 'music-sheet/' + detail.value.musicSheetName + '.png'
        // @ts-ignore
        const img = osmd.Drawer.Backends[0].canvas.toDataURL('image/png')
        const res = await uploadMusicSheet(fileName)
        await musicSheetUpload(img, fileName, res.data)
      } catch (error) {
        console.log(error)
      }
      setWatermark(osmd)
      awaken()
      // runtime.osmd = osmd
      renderLoading.value = false
    }

    const onRenderError = () => {
      renderError.value = true
      renderLoading.value = false
    }

    const openApp = () => {
      if (browserInfo.weixin) {
        wxshow.value = true
      } else {
        awaken()
        if (!browserInfo.isApp) {
          setTimeout(() => {
            location.href = location.origin + '/student/#/download'
          }, 3000)
        }
      }
    }

    return () => {
      const loading = renderLoading.value || detailStatus.value === 'loading'
      const error = renderError.value || detailStatus.value === 'error'
      // console.log('ColexiuRender', detail.value.musicSubject, score.value)
      const showShare = record.value && activityCheck.value
      return (
        <div class={[styles.container]} style={{ background: '#fff', paddingTop: showShare ? '80px' : 0 }}>
          {showShare && (
            <div class={detailStyles.share}>
              <Image radius="100%" class={detailStyles.avatar} src={record.value.avatar} />
              <div class={detailStyles.mate}>
                <div class={detailStyles.info}>
                  <span>{record.value.name}老师</span>
                  <span>专属分享～</span>
                </div>
                <Button class={detailStyles.topbtn} onClick={openApp}>
                  开通会员专属优惠
                  <img src={RightIcon} />
                </Button>
              </div>
            </div>
          )}
          <div
            id="colexiu-detail-music-sheet"
            class={[styles.musicSheet, detailStyles.musicSheet]}
            style={{ paddingBottom: '100px!important' }}
          >
            {loading && !error && <Skeleton class={styles.skeleton} rowWidth="80%" title row={3} />}
            {error && <Empty />}
            {musicImg.value && (
              <>
                <h3
                  style={{
                    fontSize: '24px',
                    fontWeight: 'normal',
                    textAlign: 'center',
                    padding: '0 10px',
                    marginTop: '36px',
                    marginBottom: '0px',
                  }}
                  class="van-ellipsis"
                >
                  {detail.value.musicSheetName}
                </h3>
                <Image
                  class={detailStyles.fullimg}
                  src={musicImg.value}
                  alt=""
                  style={{ width: '100%', display: 'block!important' }}
                />
              </>
            )}
            {!musicImg.value && score.value && (
              <>
                <h3
                  style={{
                    fontSize: '24px',
                    fontWeight: 'normal',
                    textAlign: 'center',
                    padding: '0 10px',
                    marginTop: '36px',
                    marginBottom: '0px',
                  }}
                  class="van-ellipsis"
                >
                  {detail.value.musicSheetName}
                </h3>
                <MusicSheet
                  score={score.value}
                  showSection={false}
                  opotions={{
                    drawTitle: false,
                    drawComposer: true,
                    drawLyricist: false,
                    drawMetronomeMarks: true,
                    drawMeasureNumbers: true,
                    autoResize: false,
                    backend: 'canvas',
                    // drawingParameters: 'compacttight',
                  }}
                  EngravingRules={{
                    // DrawPartNames: false,
                    VoiceSpacingMultiplierVexflow: 0.65,
                    VoiceSpacingAddendVexflow: 2.0,
                    // tight rendering mode, lower margins and safety distances between systems, staffs etc. may cause overlap.
                    // these options can afterwards be finetuned by setting osmd.rules.BetweenStaffDistance for example
                    MinSkyBottomDistBetweenStaves: 2.0, // default 1.0. this can cause collisions with slurs and dynamics sometimes
                    MinSkyBottomDistBetweenSystems: 3.0, // default 5.0
                    // note that this.rules:== osmd.rules, since it's passed as a reference
                    BetweenStaffDistance: 2.5,
                    StaffDistance: 3.5,
                    MinimumDistanceBetweenSystems: 1,
                    // PageTopMargin: 0.0, // see PageTopMarginNarrow used in compact mode
                    PageBottomMargin: 0.0,
                    PageLeftMargin: 2.0,
                    PageRightMargin: 2.0,
                  }}
                  onRerender={onRerender}
                  onRenderError={onRenderError}
                />
              </>
            )}
          </div>
          <div class={detailStyles.btnWraper}>
            <Button onClick={openApp} class={detailStyles.btn} color="linear-gradient(to bottom, #55F1CC, #2DC7AA)">
              {browserInfo.isApp ? '打卡小酷Ai开始练习吧！' : '下载酷乐秀立即练习'}
            </Button>
          </div>
          <Popup show={wxshow.value} position="top" style={{ background: 'none' }}>
            <img src={wxbg} style={{ width: '80%', display: 'block', margin: 'auto' }} />
          </Popup>
        </div>
      )
    }
  },
})
