<script setup lang='ts'>
import { TypeMap } from "~/pages/detail/util";
import { user } from '~/store'
import { showFailToast, showSuccessToast } from "vant";

let fromZlb = localStorage.getItem('fromZlb') === '1'
const router = useRouter();
const route = useRoute();
let tmk_id = route.query.tmk_id;
let te_id = route.query.te_id;
let tq_id = route.query.tq_id;
import Img from '~/assets/icon-no-data.png'
let te_name = $ref("");
let te_file = $ref("");
let kcDetailData = $ref({});
getDetail();
function getDetail() {
  request({
    url: "/txwx/mszy_kc/detail",
    data: {
      tmk_id,
    },
  }).then((res) => {
    if (res.code == "1") {
      kcDetailData = res.data.one_info;
     kcDetailData?.txwx_exam?.map((item) => {
    if (item.te_id == te_id) {
      te_name = item.te_name;
      te_file = item.te_file;
    }
  });
   // 判断章节试题存在
  if (te_id) getTest(te_id, tq_id, "init");
    }
  });
}let testInfo = $ref([]);
let wordVisiable = $ref(true);
let answerVisiable = $ref(false);
let totalQuestions = 0;
let correctAnswers = 0;
let incorrectAnswers = 0;
function getTest(tqr_pos, tq_id, type) {
  request({
    url: "/txwx/question/index",
    data: {
      tq_id,
      tqr_data_type: "5",
      tqr_data_id: tmk_id,
      tqr_pos,
       limit: "9999",
    },
  }).then((res) => {
    if (res.code == "1") {
      testInfo = res.data.page_data;
        //判断答题是否正确
      correctAnswers = 0;
      incorrectAnswers = 0;
      totalQuestions = testInfo.length;
      testInfo?.map((item) => {
        if (item.my_answer?.tqr_user_answer == item.tq_answer) {
          correctAnswers++;
        } else {
          incorrectAnswers++;
        }
      });
      if (type === "init") {
        res.data.page_data.forEach((item) => {
          if (item.my_answer.length !== 0) {
            answerVisiable = true;
            wordVisiable = false;
          } else {
            answerVisiable = false;
            wordVisiable = true;
          }
        });
      } else {
        answerVisiable = true;
      }
    }
  });
}

let question = $ref([]);
let flag = $ref(true);
function isFlag(info) {
  question = [];
  flag = true;
  info.forEach((item, index) => {
    // 单选题或判断题
    if (item.tq_type == "1" || item.tq_type == "3") {
      if (!item.answer) {
       showFailToast(`第${index + 1}题未选择`);
        flag = false;
      }
      question.push({
        tq_id: item.tq_id,
        user_answer: item.answer,
      });
    } else {
      // 多选题
      if (!item.answers || item.answers?.length == 0) {
        showFailToast(`第${index + 1}题未选择`);
        flag = false;
      }
      question.push({
        tq_id: item.tq_id,
        user_answer: item.answers,
      });
      question.forEach((el) => {
        if (Array.isArray(el.user_answer)) {
          // 重新排序使选中数据的顺序为ABC....
          el = el.user_answer?.sort((a, b) => {
            return (
              item.tq_option_choosen?.indexOf(a) -
              item.tq_option_choosen?.indexOf(b)
            );
          });
        }
      });
    }
  });
}
function submitTest(tqr_pos) {
  isFlag(testInfo);
  if (flag) {
    question.forEach((el) => {
      if (Array.isArray(el.user_answer))
        el.user_answer = el.user_answer.join("");
    });
    // request({
    //   url: "/txwx/question_record/save",
    //   data: {
    //     tqr_data_type: "5",
    //     tqr_data_id: tmk_id,
    //     tqr_pos,
    //     question,
    //   },
    // }).then((res) => {
    //   if (res.code == "1") {

    //   }
    // });
    let data1 = {
      token: user.value.token,
      client: "web",
      api: "json",
      site: "txwx",
      tqr_data_type: "5",
      tqr_data_id: tmk_id,
      tqr_pos,
      question,
      M5jxrcL: "",
      limit: "9999",
    };
    var data = JSON.stringify(data1);

    var xhr = new XMLHttpRequest();
    xhr.withCredentials = true;

    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        if (JSON.parse(xhr.responseText).code == "1") {
         showSuccessToast(JSON.parse(xhr.responseText).msg);
          wordVisiable = false;
          getTest(tqr_pos, tq_id, "1");
        }
      }
    };

    xhr.open(
      "POST",
      "https://txwxopenapi.txhlwxx.com/txwx/question_record/save"
    );
    xhr.setRequestHeader("Content-Type", "text/plain");
    xhr.setRequestHeader("Accept", "*/*");
    xhr.setRequestHeader("Host", "txwxopenapi.txhlwxx.com");
    xhr.setRequestHeader("Connection", "keep-alive");
    // WARNING: Cookies will be stripped away by the browser before sending the request.
    xhr.setRequestHeader(
      "Cookie",
      "MU80_saltkey=Q3D3Wl1d; MU80_language=sc; MU80_auth=48363nz7HP8AUMVAC3gRT7bbma969cAiLUSEFz3iMRLbyc1n6EgTwci6g_aqI1u5ENuOJ79nYiS4m_aE9sxXbC_a6G_atq7XyxZd78FFBg; MU80_lastvisit=1715410071; MU80_stat_visit=1"
    );

    xhr.send(data);
  }
}
function downloadFile(url) {
window.open(url)
}
</script>

<template>
  <van-nav-bar
    :left-arrow="!fromZlb"
    :title="te_name"
    @click-left="() => router.back()"
  />
  <div>
     <div class="mt-10px" v-if="answerVisiable && testInfo.length > 0">
        <div class="text-14px pl-20px">
          <div class="my-8px text-18px">检测结果分析：</div>
         <div class="my-8px">
           <span class="w-1/2 inline-block"
            >答题数量：{{ totalQuestions }}题</span
          ><span class="w-1/2 inline-block"
            >正确数：{{ correctAnswers }}题</span
          ></div><div class="my-8px">
            <span class="w-1/2 inline-block"
            >答错数：{{ incorrectAnswers }}题</span
          ><span class="w-1/2 inline-block"
            >正确率：{{
              ((correctAnswers / totalQuestions) * 100).toFixed(2)
            }}%</span >
          </div>
          <div class="my-8px">
            <span class="w-1/2 inline-block"
            >获取积分：30分</span
          >
          </div>

        </div>
          <div class="pl-20px my-15px">
          <div class="my-8px text-18px">试题答案解析：</div>
         <div  class="text-14px my-8px">
          <span style="color: #1259A1;cursor:pointer;text-decoration:underline" v-if="te_file" @click="downloadFile(te_file)">{{ te_file.split("/").pop() }}</span>
          <span v-else> 暂无答案解析</span>
          </div>
        </div>
      </div>





    <div v-if="wordVisiable && testInfo.length > 0">
      <div class="text-14px space-y-20px px-20px" v-if="testInfo.length > 0">
        <div v-for="item in testInfo" :key="item.tq_id">
          <div class="flex justify-between">
            <div class="leading-18px" v-html="item.tq_content" />
            <div class="min-w-60px mt-8px ml-10px">
              <span
                class="py-3px px-10px rounded-10px bg-hex-1259A1 text-white text-12px"
                >{{ item.tq_type_name }}</span
              >
            </div>
          </div>
          <van-radio-group
            direction="horizontal"
            v-if="item.tq_type == '1'"
            v-model="item.answer"
            fill="#1259a1"
            class="mt-10px mb-20px"
          >
            <van-radio
              v-for="e in item.tq_option_choosen"
              :key="e"
              size="30"
              class="mx-10px"
              :name="e"
            >
              {{ e }}
            </van-radio>
          </van-radio-group>
          <van-checkbox-group
            v-else-if="item.tq_type == '2'"
            v-model="item.answers"
            fill="#1259a1"
            class="mt-10px mb-20px"
          >
            <van-checkbox
              v-for="e in item.tq_option_choosen"
              :key="e"
              class="mx-10px"
              :name="e"

            >
              {{ e }}
            </van-checkbox>
          </van-checkbox-group>
          <van-radio-group
            direction="horizontal"
            v-else
            v-model="item.answer"
            fill="#1259a1"
            class="mt-10px mb-20px"
            size="30"
          >
            <van-radio
              horizontal
              v-for="e in item.tq_option_choosen"
              :key="e"
              size="30"
              class="mx-10px"
              :name="e"
            >
              <span class="px-10px">{{ e }}</span>
            </van-radio>
          </van-radio-group>
        </div>
        <div class="flex justify-center">
          <span
            class="w-80px h-35px leading-35px text-center rounded-10px bg-hex-1259A1 text-white text-18px"
            @click="submitTest(te_id)"
            >提交</span
          >
        </div>
      </div>
      <empty v-else />
    </div>

    <div
      v-else-if="answerVisiable && testInfo.length > 0"
      class="res-list bg-hex-fff w-full "
    >
      <div v-if="testInfo.length > 0">
        <div class="text-14px space-y-20px px-20px" v-for="item in testInfo" :key="item.tq_id">
          <div class="flex justify-between">
            <div class="leading-18px" v-html="item.tq_content" />
            <div class="min-w-60px mt-8px ml-10px">
              <span
                class="py-3px px-10px rounded-10px bg-hex-1259A1 text-white text-12px"
                >{{ item.tq_type_name }}</span
              >
            </div>
          </div>
          <div class="flex my-15px text-16px">
            <p class="mr-10px">正确答案:</p>
            <p class="text-hex-5dc248">
              {{ item.tq_answer }}
            </p>
          </div>
          <div class="flex text-16px">
            <p class="mr-10px">你的答案:</p>
            <p
              :class="
                item.my_answer.tqr_correct == '0'
                  ? 'text-red-500'
                  : 'text-hex-1259A1'
              "
            >
              {{ item.my_answer?.tqr_user_answer }}
            </p>
          </div>
          <div class="mb-25px mt-15px text-16px">
            <p class="text-red-500 my-10px">解析:</p>
            <p class="leading-loose" v-html="item.tq_alyz" />
          </div>
        </div>
      </div>
    </div>
    <div v-if="testInfo.length === 0" class="py-40px text-center">
      <div>
        <img
          :src="Img"
          width="138"
          class="block m-0-auto"
          alt=""
        />
        <h3 class="text-18px color-050026 mt-20px">暂无数据，敬请期待！</h3>
      </div>
    </div>

  </div>
</template>
