import { Button, Dialog, Grid, GridItem, Popup, Toast } from 'vant'
import { defineComponent, ref, toRefs } from 'vue'
import qs from 'query-string'
import appState from '/src/state'
import detailState from '/src/pages/detail/state'
import styles from './index.module.less'
import backIcon from '../sound-effect/icons/back.svg'
import iconBadge from './icons/icon-badge.svg'
import iconLianxi from './icons/icon-lianxi.png'
import iconReport from './icons/icon-report.png'
import TryIcon from './icons/icon-try.png'
import IntegrityIcon from './icons/integrity.svg'
import IntonationIcon from './icons/intonation.svg'
import CadenceIcon from './icons/cadence.svg'
import runtime from '/src/pages/detail/runtime'
import { postMessage } from '/src/helpers/native-message'
import { evaluatingShow, ResultContent } from './index'
import { getLeveByScoreId } from '/src/pages/detail/evaluating/helper'

import Image1 from './icons/5.png'
import Image2 from './icons/4.png'
import Image3 from './icons/3.png'
import Image4 from './icons/2.png'
import Image5 from './icons/1.png'
import iconShare from './icons/icon-share.svg'
import iconUpload from './icons/icon-upload.svg'
import { useOriginSearch } from '../../uses'
import { onChangeModelType } from '../../buttons'

const scoreInfos: any = {
  1: {
    img: Image1,
    tips: '你的演奏不太好，音准和完整性还需加强，再练一练吧～',
    mome: '敢于尝试',
  },
  2: {
    img: Image2,
    tips: '你的演奏还不熟练，音准和完整性还需加强，加紧训练才能有好成绩哦～',
    mome: '还要加油哦',
  },
  3: {
    img: Image3,
    tips: '你的演奏还不流畅，音准和节奏还需加强，科学的练习才能更完美哦～',
    mome: '突破自我',
  },
  4: {
    img: Image4,
    tips: '你的演奏还不错，继续加油吧，加强音准，离完美就差一步啦～',
    mome: '崭露头角',
  },
  5: {
    img: Image5,
    tips: '你的演奏非常不错，音准的把握和节奏稍有瑕疵，完整性把握的很好~',
    mome: '你很棒',
  },
}

//效音组件
export default defineComponent({
  name: 'ColexiuEvaluatingContent',
  props: {
    data: {
      type: Object as () => ResultContent | null,
      default: () => null,
    },
  },
  emits: ['restart', 'upload'],
  setup(props, { emit }) {
    const search = useOriginSearch()
    /** 是否是单元测试 */
    const isUnitTest = search.unitId ? true : false
    const shareShow = ref(false)
    const shareLoadedPngData = ref('')
    const { data } = toRefs(props)
    const pathname = location.pathname
    const getShareUrl = () => {
      const shareData: any = {
        id: data.value?.recordId,
        musicId: search.id,
        name: appState.user?.username || '',
        subjectName: (appState.user?.subjectName || '').split(',')[0] || '',
        avatar: encodeURIComponent(appState.user?.avatar || ''),
        score: data.value?.score || 0,
        examSongName: detailState.activeDetail?.examSongName || '',
      }
      if (!detailState.isPercussion) {
        shareData.intonation = data.value?.intonation
        shareData.cadence = data.value?.cadence
        shareData.integrity = data.value?.integrity
      }
      return `${location.origin}${pathname}/share-colexiu-evaluating/index.html?${qs.stringify(shareData)}`
    }

    const shareLoaded = (evt: Event) => {
      const el = evt.target as HTMLIFrameElement
      if (el) {
        // @ts-ignore
        el.contentWindow.setPng = (data: string) => {
          shareLoadedPngData.value = data
        }
      }
    }

    const shareNext = () => {
      if (!shareLoadedPngData.value) return
      postMessage(
        {
          api: 'shareAchievements',
          content: {
            title: '分享我的乐器练习进度，一起见证我的成长！',
            desc: '晒一下我的评测分数，快来“小酷AI”上和我PK一下吧！',
            image: shareLoadedPngData.value,
            video: '',
            type: 'image',
            button: ['copy'],
            url: getShareUrl(),
          },
        },
        (res) => {
          if (res?.content?.status) {
            shareShow.value = false
          }
          if (res?.content?.message) {
            Toast(res?.content?.message)
          }
        }
      )
    }

    const viewReport = () => {
      postMessage({
        api: 'openWebView',
        content: {
          url:
            location.origin +
              pathname +
              '/colexiu-report.html?source=evaluation&musicId=' +
              search.id +
              '&id=' +
              data.value?.recordIdStr || '',
          orientation: 0,
          isHideTitle: true, // 此处兼容安卓，意思为隐藏全部头部
          statusBarTextColor: false,
          isOpenLight: true,
        },
      })
    }
    return () => {
      const info = getLeveByScoreId(data.value?.score)
      return (
        <div>
          <div class={styles.box}>
            <div class={styles.wrap}>
              <div class={styles.wrapContainer}>
                <div class={styles.top}>
                  <div class={styles.title}>
                    <div style={{ position: 'relative', zIndex: 1, 'white-space': 'nowrap' }}>
                      <span class={styles.num}>{data.value?.score}</span>
                      <span class={styles.txt}>分 {scoreInfos[info].mome}</span>
                    </div>
                    <div class={styles.line}></div>
                  </div>
                  <img class={styles.iconTop} src={scoreInfos[info].img} />
                </div>
                <div class={styles.evaluatWrap}>
                  <Grid>
                    {detailState.isPercussion ? null : (
                      <GridItem
                        vSlots={{
                          icon: () => (
                            <div>
                              <img class={styles.evaluatIcon} src={IntonationIcon} />
                              <span class={styles.evaluatTitle}>音准</span>
                            </div>
                          ),
                          text: () => (
                            <span class={styles.fraction}>
                              {data.value?.intonation}
                              <span>分</span>
                            </span>
                          ),
                        }}
                      ></GridItem>
                    )}
                    <div class={styles.line}></div>
                    <GridItem
                      vSlots={{
                        icon: () => (
                          <div>
                            <img class={styles.evaluatIcon} src={CadenceIcon} />
                            <span class={styles.evaluatTitle}>节奏</span>
                          </div>
                        ),
                        text: () => (
                          <span class={styles.fraction}>
                            {data.value?.cadence}
                            <span>分</span>
                          </span>
                        ),
                      }}
                    ></GridItem>
                    <div class={styles.line}></div>
                    {detailState.isPercussion ? null : (
                      <GridItem
                        vSlots={{
                          icon: () => (
                            <div>
                              <img class={styles.evaluatIcon} src={IntegrityIcon} />
                              <span class={styles.evaluatTitle}>完整性</span>
                            </div>
                          ),
                          text: () => (
                            <span class={styles.fraction}>
                              {data.value?.integrity}
                              <span>分</span>
                            </span>
                          ),
                        }}
                      ></GridItem>
                    )}
                  </Grid>
                </div>

                <div class={styles.tips}>{scoreInfos[info].tips}</div>
              </div>
              <div class={styles.btns}>
                {detailState.frozenMode || isUnitTest ? null : (
                  <Button
                    onClick={() => {
                      runtime.evaluatingStatus = false
                      detailState.evaluatings = {}
                      evaluatingShow.value = false
                      onChangeModelType('practice')
                    }}
                  >
                    <img class={styles.btnIcon} src={iconLianxi} />
                  </Button>
                )}
                <Button
                  style={{ margin: '0 4px' }}
                  onClick={() => {
                    detailState.evaluatings = {}
                    emit('restart')
                  }}
                >
                  <img class={styles.btnIcon} src={TryIcon} />
                </Button>
                {isUnitTest ? null : (
                  <Button onClick={viewReport}>
                    <img class={styles.btnIcon} src={iconReport} alt="查看报告" />
                  </Button>
                )}
              </div>
              {isUnitTest ? null : (
                <div class={styles.rigthBtns}>
                  <div class={styles.skepBtn} onClick={() => emit('upload')}>
                    <img src={iconUpload} />
                    上传
                  </div>
                  {/* <div class={styles.skepBtn} onClick={() => (shareShow.value = true)}>
                  <img src={iconShare} />
                  分享
                </div> */}
                </div>
              )}
            </div>
            <Popup
              teleport="body"
              show={shareShow.value}
              style={{
                background: 'transparent',
              }}
            >
              <div style={{ textAlign: 'right' }}>
                <Button class={styles.sbtn} onClick={shareNext} round type="primary" color="#2DC7AA">
                  分享
                </Button>
                <Button class={styles.sbtn} onClick={() => (shareShow.value = false)} round>
                  关闭
                </Button>
              </div>
              <iframe
                style={{
                  width: '50vw',
                  border: 'none',
                  height: '70vh',
                  marginTop: '1vh',
                }}
                src={getShareUrl()}
                onLoad={shareLoaded}
              />
            </Popup>
            <Button class={styles.button} icon={backIcon} onClick={() => emit('restart')}></Button>
          </div>
        </div>
      )
    }
  },
})
