import { Button, Dialog, Grid, GridItem, Popup, Toast } from 'vant'
import { defineComponent, ref, toRefs, computed } 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.png'
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, * as RuntimeUtils 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,
          c_orientation: 0,
        },
      })
    }

    // 播放倍率不等于1，或者是选段评测，APP暂时不支持保存演奏，需要给出提示
    const noSaveTips = computed(() => {
      let tipContent = '';
      if (isUnitTest || detailState.section.length === 2 || detailState.activeDetail.isAppPlay || runtime.basePlayRate != 1 || !runtime.songs.background) {
        tipContent = isUnitTest ? '单元测验暂不支持保存作品噢～' : (!runtime.songs.background || detailState.activeDetail.isAppPlay) ? '该曲目暂不支持保存作品噢～' : detailState.section.length === 2 ? '选段后暂不支持保存作品噢～' : runtime.basePlayRate != 1 ? '调速后暂不支持保存作品噢～' : '';
      }
      return tipContent
    })

    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>
                {detailState.isPercussion ? null : (
                  <div class={styles.evaluatWrap}>
                    <Grid>
                      <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>
                      <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}>
                  <div style={detailState.isPercussion ? { height: '45px', fontSize: '15px' } : ''}>
                    {scoreInfos[info].tips}
                  </div>
                  <div class={styles.btns} style={{ justifyContent: isUnitTest ? 'center' : '' }}>
                    {detailState.frozenMode || isUnitTest ? null : (
                      <Button
                        onClick={() => {
                          runtime.evaluatingStatus = false
                          detailState.evaluatings = {}
                          evaluatingShow.value = false
                          RuntimeUtils.clearSectionStatus()
                          onChangeModelType('practice')
                        }}
                      >
                        <img class={styles.btnIcon} src={iconLianxi} />
                      </Button>
                    )}
                    <Button
                      style={{ margin: '0 4px' }}
                      onClick={() => {
                        runtime.initShow = true;
                        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>
                </div>
              </div>

              { !detailState.isHideEvaluatReportSaveBtn ? (
                // <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 class={styles.headerButton}>
                  <div class={[styles.headBtn, noSaveTips.value ? styles.headBtnDisable : '']} onClick={() => {
                    if (!noSaveTips.value) {
                      emit('upload')
                    }
                  }}>
                    保存作品
                  </div>
                  {
                    noSaveTips.value && runtime.initShow ? 
                    <div class={[styles.noSaveTip]}>
                      <span class={styles.arrowIcon}></span>
                      {noSaveTips.value}
                      <i onClick={() => runtime.initShow = false}></i>
                    </div> : null                   
                  }
                </div>                
              ) : null}
            </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={() => {
              detailState.evaluatings = {}
              emit('restart')
            }}></Button>
          </div>
        </div>
      )
    }
  },
})
