import { defineComponent, toRefs, PropType, ref, Transition, onMounted } from 'vue'
import { Button, Grid, GridItem, Popup, Dialog, Toast } from 'vant'
import qs from 'query-string'
import BackIcon from '../../colexiu/header/icons/back.svg'
import { heardLevel } from '/src/constant/formats'
import Note from '/src/pages/report/note'
import PlayerPopup from '/src/pages/report/player'
import styles from './index.module.less'
import state from '/src/pages/state'
import AgainIcon from '../again.svg'
import ExplainIcon from '../explain.svg'
import ReplayIcon from '../replay.svg'
import CloseIcon from './close.png'
import detailStyles from './index.module.less'
import { postMessage } from '/src/helpers/native-message'
import { useOriginSearch } from '../../colexiu/uses'
import wxbg from '../../colexiu-share/wx_bg.png'
import { browser } from '/src/helpers/utils'

const browserInfo = browser()

const search = useOriginSearch()

export const active = ref<'pitch' | 'rhythm' | 'completion'>('pitch')

const visible = ref(false)
const wxshow = ref(false)

export default defineComponent({
  name: 'ColexiuReportHeader',
  props: {
    detail: {
      type: Object as PropType<any | null>,
    },
    record: {
      type: Object,
    },
    className: {
      type: String,
    },
  },
  emits: ['activeChange'],
  setup(props, { emit, expose }) {
    const back = () => {
      postMessage({
        api: 'back',
      })
    }

    const autoShow = () => {
      if (localStorage.getItem('explain-view') != '1') {
        visible.value = true
        setTimeout(() => {
          visible.value = false
          localStorage.setItem('explain-view', '1')
        }, 5000)
      }
    }

    const again = () => {
      if (search.source === 'evaluation') {
        back()
      } else {
        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',
          },
        })
        postMessage({
          api: 'openAccompanyWebView',
          content: {
            url,
            orientation: 0,
            isHideTitle: true,
            statusBarTextColor: false,
            isOpenLight: true,
          },
        })
      }
    }

    expose({
      autoShow,
    })

    return () => {
      const { detail, record } = toRefs(props)

      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 + '/student/#/music-detail',
        //     query: {
        //       id: record.value?.musicalNotesPlayStats?.examSongId,
        //     },
        //   })
        //   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/#/music-detail'
        str += `?id=${record.value?.musicalNotesPlayStats?.examSongId}`

        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 openApp = () => {
        if (browserInfo.weixin) {
          wxshow.value = true
        } else {
          awaken()
          if (!browserInfo.isApp) {
            setTimeout(() => {
              location.href = location.origin + '/student/#/download'
            }, 3000)
          }
        }
      }

      return (
        <header class={[styles.header, styles.className]}>
          <div class={styles.info}>
            {record.value && record.value?.heardLevel ? (
              <Grid class={styles.center} columnNum={5}>
                <GridItem
                  class="van-hairline--right"
                  vSlots={{
                    text: () => <span>难度</span>,
                    icon: () => <span>{(heardLevel as any)[record.value?.heardLevel]}</span>,
                  }}
                />
                <GridItem
                  class="van-hairline--right"
                  vSlots={{
                    text: () => <span>评测分数</span>,
                    icon: () => <span>{record.value?.score}分</span>,
                  }}
                />
                <GridItem
                  class="van-hairline--right"
                  onClick={() => {
                    active.value = 'pitch'
                    emit('activeChange', 'pitch')
                  }}
                  vSlots={{
                    text: () => <span class={['switch', { active: active.value === 'pitch' }]}>音准</span>,
                    icon: () => <span style={{ color: '#2DC7AA' }}>{record.value?.intonation}分</span>,
                  }}
                />
                <GridItem
                  class="van-hairline--right"
                  onClick={() => {
                    active.value = 'rhythm'
                    emit('activeChange', 'rhythm')
                  }}
                  vSlots={{
                    text: () => <span class={['switch', { active: active.value === 'rhythm' }]}>节奏</span>,
                    icon: () => <span style={{ color: '#FF4E19' }}>{record.value?.cadence}分</span>,
                  }}
                />
                <GridItem
                  onClick={() => {
                    active.value = 'completion'
                    emit('activeChange', 'completion')
                  }}
                  vSlots={{
                    text: () => <span class={['switch', { active: active.value === 'completion' }]}>时值</span>,
                    icon: () => <span style={{ color: '#FFC459' }}>{record.value?.integrity}分</span>,
                  }}
                />
              </Grid>
            ) : null}
            <Grid columnNum={3} class={styles.btns}>
              <GridItem
                onClick={() => (visible.value = true)}
                vSlots={{
                  text: () => <span>释义</span>,
                  icon: () => <img src={ExplainIcon} />,
                }}
              />
            </Grid>
          </div>
          {record.value?.score ? (
            <div class={detailStyles.try}>
              <Button
                class={detailStyles.trybtn}
                // url={'/student/#/music-detail?id=' + record.value?.musicalNotesPlayStats?.examSongId}
                onClick={openApp}
              >
                我来试一试
              </Button>
            </div>
          ) : null}
          {record.value ? (
            <div class={styles.demos}>
              {/* <div>
                <Note fill="#01C1B5" />
                <span>演奏正确</span>
              </div> */}
              {active.value === 'pitch' && (
                <>
                  <div>
                    <Note fill="#FFAB25" shadow x={-3} y={0} />
                    <span>音高了</span>
                  </div>
                  <div>
                    <Note fill="#FFAB25" shadow x={-1} y={-2} />
                    <span>音低了</span>
                  </div>
                </>
              )}
              {!state.isPercussion ? (
                <>
                  {active.value === 'rhythm' && (
                    <>
                      <div>
                        <Note fill="#FF4444" shadow x={0} />
                        <span>节奏快了</span>
                      </div>
                      <div>
                        <Note fill="#FF4444" shadow x={-3} y={-2} />
                        <span>节奏慢了</span>
                      </div>
                    </>
                  )}
                  {active.value === 'completion' && (
                    <div>
                      <Note fill="#CC75FF" />
                      <span>时值不足</span>
                    </div>
                  )}
                </>
              ) : null}
              {/* <div>
                <Note fill="#AEAEAE" />
                <span>未演奏</span>
              </div> */}
            </div>
          ) : null}
          <Popup show={wxshow.value} position="top" style={{ background: 'none' }}>
            <img src={wxbg} style={{ width: '80%', display: 'block', margin: 'auto' }} />
          </Popup>
          <Popup
            teleport="body"
            show={visible.value}
            class={styles.pop}
            style={{ width: '60vw' }}
            onClickOverlay={() => (visible.value = false)}
          >
            <div class={styles.close} onClick={() => (visible.value = false)}>
              <img src={CloseIcon} />
            </div>
            <h2>图标释义</h2>
            <Grid columnNum={2} class={styles.btns} border={false}>
              <GridItem
                vSlots={{
                  text: () => <span>绿色音符：演奏正确</span>,
                  icon: () => <Note fill="#01C1B5" />,
                }}
              />
              <GridItem
                vSlots={{
                  text: () => <span>红色音符：错音</span>,
                  icon: () => <Note fill="#FF4444" />,
                }}
              />
              <GridItem
                vSlots={{
                  text: () => <span>音符重影(红色在前)：节奏过快</span>,
                  icon: () => <Note fill="#FF4444" shadow x={0} />,
                }}
              />
              <GridItem
                vSlots={{
                  text: () => <span>音符重影(红色在后)：节奏慢了</span>,
                  icon: () => <Note fill="#FF4444" shadow x={-3} y={-2} />,
                }}
              />
              <GridItem
                vSlots={{
                  text: () => <span>音符重影(黄色在上)：音高了</span>,
                  icon: () => <Note fill="#FFAB25" shadow x={-3} y={0} />,
                }}
              />
              <GridItem
                vSlots={{
                  text: () => <span>音符重影(黄色在下)：音低了</span>,
                  icon: () => <Note fill="#FFAB25" shadow x={-1} y={-2} />,
                }}
              />
              <GridItem
                vSlots={{
                  text: () => <span>紫色音符：完整度不足</span>,
                  icon: () => <Note fill="#CC75FF" />,
                }}
              />
              <GridItem
                vSlots={{
                  text: () => <span>灰色音符：未演奏</span>,
                  icon: () => <Note fill="#AEAEAE" />,
                }}
              />
            </Grid>
          </Popup>
        </header>
      )
    }
  },
})
