import { defineComponent, onMounted, reactive, watch, computed } from "vue";
import { Popover } from "vant";
import styles from "./index.module.less";
import state from "/src/state";
import icon1 from "../icons/1.png";
import { storeData } from "/src/store";
import { evaluatingData } from "/src/view/evaluating";
import iconBack from "/src/page-instrument/header-top/image/icon-back.png";
import bg1Img from "./img/bg1.png";
import bg2Img from "./img/bg2.png";
import ckzpImg from "./img/ckzp.png";
import bczpImg from "./img/bczp.png";
import bczpJzImg from "./img/bczpJz.png";
import zlycImg from "./img/zlyc.png";
import iconBadge from "./img/icon-badge.png";
import yzImg from "./img/yz.png";
import jzImg from "./img/jz.png";
import wzxImg from "./img/wzx.png";
import closeImg from "./img/close.png";
import { getQuery } from "/src/utils/queryString";
import { browser, getBehaviorId } from "/src/utils";
import { api_musicPracticeRecordSave } from "../../api";
import { getAudioDuration } from "/src/view/audio-list";
import { debounce } from "/src/utils";
import { EvaluatingResultDriver } from "../../custom-plugins/guide-driver";

export default defineComponent({
  name: "evaluatResult",
  emits: ["close"],
  setup(props, { emit }) {
    const query = getQuery();
    const data = reactive({
      saveLoading: true,
      showPopover: true,
    });
    const level: any = {
      BEGINNER: "入门级",
      ADVANCED: "进阶级",
      PERFORMER: "大师级",
    };
    /** 添加评测记录 */
    const handleAddRecord = async () => {
      console.log("结束", evaluatingData.resultData);
      /** 生成评测记录的时候，记录当前评测的谱面类型，用于评测报告默认展示的谱面类型 */
      evaluatingData.resultData.scoreData.musicType = state.musicRenderType;
      // 评测的速度，如果是选段，则选选段开头小节的速度
      const evaluatSpeed = state.sectionStatus && state.section.length === 2 && state.section[0].measureSpeed ? state.section[0].measureSpeed * state.basePlayRate : state.speed;  
      const rate = state.basePlayRate * state.originAudioPlayRate; // 播放倍率    
      const body: any = {
        deviceType: browser().android ? "ANDROID" : "IOS", // 设备类型
        intonation: evaluatingData.resultData.intonation, // 音准
        cadence: evaluatingData.resultData.cadence, // 节奏
        integrity: evaluatingData.resultData.integrity, // 完成度
        scoreData: JSON.stringify(evaluatingData.resultData.scoreData), // 评测数据
        behaviorId: getBehaviorId(), // 行为id
        sourceTime: getAudioDuration(), // 音频时长
        partIndex: state.partIndex, // 音轨
        speed: evaluatingData.evaluatSpeed || evaluatSpeed, // 速度
        practiceSource: query.workRecord ? "LESSON_TRAINING" : "EVALUATION", // 练习来源
        score: evaluatingData.resultData.score, // 分数
        clientType: storeData.user.clientType, // 客户端类型
        musicSheetId: state.examSongId, // 乐谱id
        feature: "EVALUATION", // 特征
        playTime: evaluatingData.resultData.playTime / 1000, // 播放时长
        heardLevel: state.setting.evaluationDifficulty, // 听力等级
        recordFilePath: evaluatingData.resultData.url, // 录音文件路径
        delFlag: evaluatingData.oneselfCancleEvaluating,
        instrumentId: state.instrumentId,
        playRate: rate,
        providerType: state.tenantAlbumId ? "TENANT" : "PLATFORM"
      };
      // 如果是评测作业模式，需要添加作业id
      if (query.evaluatingRecord) {
        body.lessonDetailId = query.evaluatingRecord
      }
      data.saveLoading = true;
      const res = await api_musicPracticeRecordSave(body);
      if (res?.code === 200) {
        evaluatingData.resultData.recordId = res.data;
      }
      evaluatingData.needReplayEvaluat = evaluatingData.oneselfCancleEvaluating ? true : false;
      data.saveLoading = false;
    };

    const saveResult = () => {
      emit("close", "update");
    };

    // 播放倍率不等于1，或者是选段评测，APP暂时不支持保存演奏，需要给出提示
    const noSaveTips = computed(() => {
      let tipContent = '';
      const rate = state.basePlayRate * state.originAudioPlayRate; // 播放倍率
      console.log('123456',state.systemType)
      if (query.workRecord || state.section.length === 2 || state.isAppPlay || rate != 1 || !state.accompany || state.systemType === 'web') {
        tipContent = (state.systemType === 'web') ? '暂不支持保存作品噢～' : query.workRecord ? '评测作业暂不支持保存作品噢～' : (!state.accompany || state.isAppPlay) ? '该曲目暂不支持保存作品噢～' : state.section.length === 2 ? '选段后暂不支持保存作品噢～' : rate != 1 ? '调速后暂不支持保存作品噢～' : '';
      }
      return tipContent
    })

    const isHuaWeiPad = navigator?.userAgent?.includes("UAWEIVRD-W09") ? true : false
    onMounted(() => {
      // if (!evaluatingData.isErrorState) {
      //   handleAddRecord();
      // }
      // console.log('评测等级',evaluatingData.resultData.leve)
    });

    watch(
      () => evaluatingData.resulstMode,
      (val) => {
        // # 9402，评测异常操作：都改为不生成评测记录
        if (val) {
          setTimeout(() => {
            if (!evaluatingData.isErrorState) {
              handleAddRecord();
            }
          }, 0);
        }
      },
      {
        immediate: true
      }
    );
    return () => (
      <>
        {!evaluatingData.hideResultModal && (
          <div class={styles.evaluatResult}>
            <div class={styles.closeBtn} onClick={() => emit("close")}>
              <img src={iconBack} />
            </div>
            <div class={[styles.fraction, state.isPercussion && styles.fractionPercussion]}>
              <img class={styles.bg} src={state.isPercussion ? bg2Img : bg1Img} />
              <div class={styles.top}>
                {evaluatingData.resultData.score > 79 && <img class={styles.badge} src={iconBadge} />}
                <div class={[styles.text, evaluatingData.resultData.score > 79 && styles.badgeText]}>
                  <div class={[styles.scoreSection, "evaluting-result-1"]}>
                    <div class={styles.num}>{evaluatingData.resultData.score}</div>
                    <div class={styles.score}>分</div>
                    <div class={[styles.level, isHuaWeiPad && styles.huaWeiLevel]}>
                      <div>{level[evaluatingData.resultData.heardLevel]}</div>
                      <span>|</span>
                      <div>速度{evaluatingData.resultData.speed || state.speed}</div>
                    </div>
                  </div>
                </div>
                <img class={styles.rightBadge} src={evaluatingData.resultData.img} />
              </div>
              {!state.isPercussion && (
                <div class={styles.detail}>
                  <div class={styles.progressitem}>
                    <div>
                      <img src={yzImg} />
                      <span>音准</span>
                    </div>
                    <div><span class={styles.scoresNum}>{evaluatingData.resultData.intonation}</span><span class={styles.scores}>分</span></div>
                  </div>
                  <div class={styles.progressitem}>
                    <div>
                      <img src={jzImg} />
                      <span>节奏</span>
                    </div>
                    <div><span class={styles.scoresNum}>{evaluatingData.resultData.cadence}</span><span class={styles.scores}>分</span></div>
                  </div>
                  <div class={styles.progressitem}>
                    <div>
                      <img src={wzxImg} />
                      <span>完成度</span>
                    </div>
                    <div><span class={styles.scoresNum}>{evaluatingData.resultData.integrity}</span><span class={styles.scores}>分</span></div>
                  </div>
                </div>
              )}
              <div class={styles.tips}>{state.isPercussion ? evaluatingData.resultData.djytip : evaluatingData.resultData.clxtip}</div>
              <div class={styles.ctrls}>
                <img src={zlycImg} class={[styles.ctrlsBtn, "evaluting-result-2"]} onClick={() => emit("close", "tryagain")} />
                {evaluatingData.resultData.recordId ? (
                  <div class={styles.saveBtn}>
                    <img
                      src={noSaveTips.value ? bczpJzImg : bczpImg}
                      class={[styles.ctrlsBtn, "evaluting-result-3"]}
                      style={{ opacity: state.isHideEvaluatReportSaveBtn ? 0.4 : 1 }}
                      onClick={() => {
                        if (!noSaveTips.value && !state.isHideEvaluatReportSaveBtn) {
                          saveResult();
                        }
                      }}
                    />
                    {noSaveTips.value && state.noSavePopShow ? (
                      <div class={[styles.noSaveTip]}>
                        <span class={styles.arrowIcon}></span>
                        <span>{noSaveTips.value}</span>
                        <i onClick={() => (state.noSavePopShow = false)}></i>
                      </div>
                    ) : null}
                  </div>
                ) : null}
                <img src={ckzpImg} class={[styles.ctrlsBtn, "evaluting-result-4", data.saveLoading ? styles.disablued : ""]} onClick={() => emit("close", "look")} />
              </div>
            </div>

            {/* 评测模式-结果弹窗 功能引导 加载音频完成 不是会员 */}
            {evaluatingData.resulstMode && !evaluatingData.hideResultModal && !evaluatingData.earphoneMode && !query.isCbs && state.audioDone && !data.saveLoading && <EvaluatingResultDriver saveBtn={evaluatingData.resultData.recordId ? true : false} />}
          </div>
        )}
      </>
    );
  },
});
