import { Tag, Image, Button, Cell, Icon } from 'vant'
import { computed, defineComponent, nextTick, onMounted, PropType, reactive } from 'vue'
import styles from './index.module.less'
import {
  listenerMessage,
  postMessage,
  promisefiyPostMessage,
  removeListenerMessage
} from '@/helpers/native-message'
import deepClone from '@/helpers/deep-clone'
import iconSong from '../../images/icon-song.png'
import AnserTitle from '../anser-title'
import { QuestionType } from '../../unit'
import AnswerAnalysis from '../answer-analysis'

// 单选和多选题
export default defineComponent({
  name: 'choice-question',
  props: {
    value: {
      type: Array,
      default: () => []
    },
    index: {
      // 题目是第几道
      type: Number,
      default: 1
    },
    data: {
      type: Object,
      default: () => ({})
    },
    // 测试编号
    unitId: {
      type: String,
      default: ''
    },
    /* 只读 */
    readOnly: {
      type: Boolean,
      default: false
    },
    showRate: {
      type: Boolean,
      default: false
    },
    showAnalysis: {
      // 是否显示解析
      type: Boolean,
      default: false
    },
    analysis: {
      type: Object,
      default: () => ({
        message: '',
        topic: false, // 是否显示结果
        userResult: true // 用户答题对错
      })
    }
  },
  emits: ['update:value'],
  setup(props, { emit }) {
    console.log(props)
    const state = reactive({
      list: [] as any,
      score: 0
    })

    // const mediaUrls = computed(() => (props.data.mediaUrls ? props.data.mediaUrls.split(',') : ''))

    const questionExtendsInfo = computed(() =>
      props.data.questionExtendsInfo ? JSON.parse(props.data.questionExtendsInfo) : ''
    )

    /**
     * @description 进行评测
     */
    const onEvaluation = () => {
      const info = questionExtendsInfo.value
      if (!info) return
      console.log(props.unitId)
      postMessage({
        api: 'openAccompanyWebView',
        content: {
          // url: `https://ponline.colexiu.com/orchestra-music-score/?id=${info.musicSheetId}&modelType=evaluation&unitId=${props.unitId}&questionId=${props.data.id}`,
          url: `${location.origin}/orchestra-music-score/?id=${info.musicSheetId}&modelType=evaluation&unitId=${props.unitId}&questionId=${props.data.id}`,
          orientation: 0,
          isHideTitle: true,
          statusBarTextColor: false,
          isOpenLight: true
        }
      })

      // 打开页面监听
      listenerMessage('webViewOnResume', () => {
        promisefiyPostMessage({ api: 'getCache', content: { key: 'h5-orchestra-unit' } }).then(
          (res: any) => {
            const content = res.content
            if (content.value) {
              console.log(content.value, 'h5-orchestra-unit')
              const result = content.value ? JSON.parse(content.value) : {}
              console.log('🚀 ~ listenerMessage ~ result', result, props.data.questionId)

              if (result.questionId === props.data.id) {
                const tempScore = result.score || 0
                // 跟上一次分数对比
                if (state.score < tempScore) {
                  state.score = result.score || 0
                }
              }

              emit('update:value', [
                {
                  answerId: '',
                  answer: state.score,
                  answerExtra: ''
                }
              ])

              // 置空，存的缓存
              promisefiyPostMessage({
                api: 'setCache',
                content: {
                  key: 'h5-orchestra-unit',
                  value: ''
                }
              })
            }

            // 关闭页面监听
            removeListenerMessage('webViewOnResume', () => {
              //
            })
          }
        )
      })
    }

    return () => (
      <>
        <div class={styles.unitSubject}>
          {/* 标题 */}
          <AnserTitle
            index={props.index}
            name={props.data.name}
            score={props.data.totalScore}
            showRate={props.showRate}
            answerType={QuestionType.PLAY}
            extra={{
              questionDetail: props.data.questionDetail,
              mediaUrls: '',
              rightRate: props.data.rightRate
            }}
          />

          <div class={[styles.unitAnswers]}>
            {questionExtendsInfo.value && (
              <Cell
                class={styles.playSection}
                center
                titleClass={['van-ellipsis', styles.playTitle]}
              >
                {{
                  icon: () => <Image class={styles.img} src={iconSong} />,
                  title: () => <>{questionExtendsInfo.value.musicName}</>,
                  value: () => (
                    <Button
                      round
                      class={styles.playBtn}
                      type="primary"
                      onClick={onEvaluation}
                      disabled={props.readOnly}
                    >
                      点击评测
                      <Icon name="play" />
                    </Button>
                  )
                }}
              </Cell>
            )}

            {!props.readOnly && (
              <div class={['van-hairline--top', styles.unitScoreNum]}>
                <div class={styles.score}>{state.score}</div>
                <div class={styles.scoreTitle}>评测分数</div>
                <div class={styles.scoreTips}>多次评测取完整评测的最高分数</div>
              </div>
            )}
          </div>
        </div>
        {props.showAnalysis && (
          <div class={styles.unitSubject}>
            <AnswerAnalysis
              answerAnalysis={props.analysis.message}
              topic={props.analysis.topic}
              userResult={props.analysis.userResult}
            />
          </div>
        )}
      </>
    )
  }
})
