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

// 单选和多选题
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
    },
    // 学员详情显示分数
    showScore: {
      type: Boolean,
      default: false
    },
    showRate: {
      type: Boolean,
      default: false
    },
    showAnalysis: {
      // 是否显示解析
      type: Boolean,
      default: false
    },
    analysis: {
      type: Object,
      default: () => ({
        message: '',
        topic: false, // 是否显示结果
        userResult: true, // 用户答题对错
        score: 0 // 分数
      })
    }
  },
  emits: ['update:value'],
  setup(props, { emit, slots }) {
    console.log(props, 'props');
    const state = reactive({
      list: [] as any,
      score: 0
    });

    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', () => {
        if (browser().android) {
          const instance: any =
            (window as any).ORCHESTRA ||
            (window as any).webkit?.messageHandlers?.ORCHESTRA;

          console.log(instance, '-------------');
          const result = instance.getCache2('h5-orchestra-unit');
          console.log('🚀 ~ listenerMessage ~ result', result);
          const tempResult = result ? JSON.parse(result) : {};
          if (tempResult.questionId === props.data.id) {
            const tempScore = tempResult.score || 0;
            // 跟上一次分数对比
            if (state.score < tempScore) {
              state.score = tempResult.score || 0;
            }

            // 置空，存的缓存
            promisefiyPostMessage({
              api: 'setCache',
              content: {
                key: 'h5-orchestra-unit',
                value: ''
              }
            });
          }
          emit('update:value', [
            {
              answerId: '',
              answer: state.score,
              answerExtra: ''
            }
          ]);
          // 关闭页面监听
          removeListenerMessage('webViewOnResume', () => {
            //
          });
        } else {
          promisefiyPostMessage({
            api: 'getCache',
            content: { key: 'h5-orchestra-unit' }
          }).then((res: any) => {
            const content = res.content;
            if (content.value) {
              console.log(
                '🚀 ~ listenerMessage ~ content.value',
                content.value,
                '---------------'
              );
              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', () => {
              //
            });
          });
        }
      });
    };

    onMounted(() => {
      //
      const userValue: any = props.value || [];
      if (userValue.length > 0) {
        state.score = userValue[0].answer;
      }
    });

    return () => (
      <>
        <div class={styles.unitSubject}>
          {slots.title && slots.title()}
          {/* 标题 */}
          <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 || props.showScore) && (
              <div class={['van-hairline--top', styles.unitScoreNum]}>
                <div class={styles.score}>{state.score}</div>
                <div class={styles.scoreTitle}>评测分数</div>
                {!props.showScore && (
                  <div class={styles.scoreTips}>
                    多次评测取完整评测的最高分数
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
        {props.showAnalysis && (
          <AnswerAnalysis
            answerAnalysis={props.analysis.message}
            topic={props.analysis.topic}
            userResult={props.analysis.userResult}
            rightFlagText={'合格'}
            errorFlagText={'不合格'}
          />
        )}
      </>
    );
  }
});
