<script setup lang="ts">
import {
  ref,
  reactive,
  toRefs,
  onMounted,
  watch,
  computed,
  onBeforeUnmount,
} from "vue";
import NavBarPage from "../components/NavBarPage.vue";
import randarPage from "./result/randarPage.vue";
import { useRoute } from "vue-router";
import { fetchTaskScore } from "./utils/api";
import { Toast } from "vant";

const route = useRoute();

const score = ref(0);
const data = ref(null);
const scoresList = ref(null);
const defectsList = ref(null);
const taskId = computed(() => route.query.conversationId); // 会话ID "2c64eb8b69be432ca0bb9ae55bc78def"
const randarlist = ref([0, 0, 0, 0, 0,0]);
const loading = ref(false);

const nameMapping = {
  settle_reason: "提前结清原因（10分）",
  speech_retention: "话术挽留客户（20分）",
  strategic_retention: "策略挽留客户（30分）",
  other_retentions: "其他挽留客户（10分）",
  call_ratio:"通话比例（10分）",
  persistence:"坚持力度（20分）",
  penalty_points: "扣分项",
  defects: "评分详解"
};

const handleResult = async () => {
  let res;
  let shouldContinue = true; // 控制是否继续调用接口的标志
  loading.value = true;

  while (shouldContinue) {
    res = await fetchTaskScore(taskId.value);

    if (res.code !== 200) {
      // 当返回错误时，停止调用接口
      loading.value = false
      shouldContinue = false;
    } else if (res.body && Object.keys(res.body).length !== 0) {
      // 当res.body有值时，停止调用接口
      data.value = res.body;
      shouldContinue = false;
    } else {
      await new Promise((resolve) => setTimeout(resolve, 3000));
    }
  }
  if (res && res.code === 200 && res.body) {
    loading.value = false;
    const scores = extractScores(res.body);
    score.value = scores.reduce((sum, score) => sum + score, 0);
    scoresList.value = Object.keys(res.body).reduce((acc, key) => {
      if (key !== "defects") {
        acc[key] = {
          ...res.body[key],
          name: nameMapping[key], // 添加 name 字段
        };
      }
      return acc;
    }, {});
    defectsList.value = res.body.defects;
    console.log(defectsList.value, '000000000');
    const obj = extractScores(scoresList.value);
    randarlist.value = Object.values(obj);
  }
};

// 处理“分”字
const extractScores = (data) => {
  return Object.values(data).map((item) => {
    // 确保 score 是一个字符串，并且去除可能的 "分" 字
    let scoreStr = String(item.score).replace("分", "");

    // 将 score 转换为整数，如果转换失败则返回 0
    const score = parseInt(scoreStr, 10);
    return isNaN(score) ? 0 : score;
  });
};

onMounted(() => {
  handleResult();
  window.addEventListener("popstate", function (event) {
    // 执行一些操作，例如关闭当前页面或跳转到其他页面
    window.location.href = "/#/home";
  });
});

onBeforeUnmount(() => {
  window.removeEventListener("popstate", function (event) {
    // 执行一些操作，例如关闭当前页面或跳转到其他页面
    window.location.href = "/#/home";
  });
});
</script>
<template>
  <div class="result" style="overflow: hidden">
    <NavBarPage title="考试" type="home" />
    <div style="height: 46px"></div>
    <div class="score">
      <span>最终得分</span>
      <p class="score-num">
        <span style="margin-right: 0.2rem;">{{ score }}</span>分
      </p>
    </div>
    <div style="height: 9.06rem; visibility: hidden"></div>
    <div class="content">
      <div style="width: 100vw; height: 19.06rem">
        <randarPage :randarList="randarlist" />
      </div>
      <div class="loading" v-show="loading">
       <van-loading color="#0094ff" size="26px" vertical>加载中...</van-loading>
      </div>
      <div class="standard">
        <div class="standard-title">
          <img src="../assets/robot.jpg" alt="" />
          <span>评分标准</span>
        </div>
        <div class="standard-content" v-for="(item, key) in scoresList" :key="key">
          <div class="standard-subtitle">
            <span class="pro">{{ item.name == "扣分项" ? item.name : `${item.name}` }}：</span>
            <span>{{ item.score }}</span>
          </div>
          <p>
            <span>得分原因：</span>
            <span>{{ item.reason }}</span>
          </p>
        </div>
        <div class="standard-content" style="margin-top: 1.5rem;">
          <div class="standard-title">
          <img src="../assets/robot.jpg" alt="" />
          <span>评分详解</span>
        </div>
          <div class="standard-content" v-for="(item, index) in defectsList" :key="index">
            <div class="standard-subtitle">
            <span class="pro">轮次{{item.rounds}}：</span>
          </div>
            <p>
              <span>原句：</span>
              <span>{{ item.original_sentence }}</span>
            </p>
            <p>
              <span>不足：</span>
              <span>{{ item.defect }}</span>
            </p>
            <p>
              <span>建议：</span>
              <span>{{ item.example }}</span>
            </p>
          </div>
        </div>
      </div>

    </div>
  </div>
</template>

<style scoped lang="less">
html,
body {
  margin: 0;
  padding: 0;
  height: 100vh;
  overflow: hidden;
  /* 禁止页面整体滚动 */
}

.result {
  width: 100%;
  height: 100%;
  /* height: 100vh; */
  overflow: hidden;
}

.score {
  position: fixed;
  z-index: 999;
  width: 100%;
  height: 9.06rem;
  background-color: rgba(243, 249, 255, 1);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  span {
    display: flex;
    width: 5.06rem;
    height: 2.88rem;
    font-weight: bold;
    line-height: 2.88rem;
    color: rgba(64, 149, 229, 1);
    font-size: 1rem;
    text-align: center;
    font-family: Times New Roman-regular;
  }

  .score-num {
    display: flex;
    align-items: last baseline;
    color: rgba(64, 149, 229, 1);
    font-size: 1rem;

    span {
      display: block;
      width: 5.06rem;
      height: 3.31rem;
      line-height: 4.25rem;
      font-size: 3rem;
      text-align: center;
      font-family: Times New Roman-regular;
    }
  }
}

.content {
  width: 100%;
  height: 100%;
  overflow: scroll;
}

.standard-title {
  display: flex;
  align-items: center;
  padding: 0 0.94rem;
  margin-bottom: 0.63rem;

  img {
    width: 1.5rem;
    height: 1.5rem;
  }

  span {
    display: inline-block;
    width: 4rem;
    height: 1.44rem;
    line-height: 1.44rem;
    margin-left: 0.33rem;
    color: rgba(64, 149, 229, 1);
    font-size: 1rem;
    text-align: center;
    font-family: Times New Roman-regular;
  }
}

.standard-subtitle {
  padding: 0.56rem 1rem;
  height: 1.06rem;
  font-size: 0.88rem;
  font-family: Times New Roman-regular;

  span {
    color: rgba(64, 149, 229, 1);
    font-weight: 600;
  }

  .pro {
    display: inline-block;
    height: 1.06rem;
    line-height: 1.06rem;
    padding: 0 0.3rem;
    font-weight: normal;
    color: rgba(102, 102, 102, 1);
    border-left: 0.3rem solid rgba(64, 149, 229, 1);
  }
}

.standard-content p {
  padding: 0 1.63rem;
  margin-bottom: 0.31rem;
  line-height: 1.25rem;
  color: rgba(102, 102, 102, 1);
  font-size: 0.88rem;
  text-align: left;
  font-family: SourceHanSansSC-bold;
}

.standard-content p span:nth-child(1) {
  font-weight: 600;
}

.loading {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}
</style>
