<template>
  <div class="exam">
    <div v-if="flag == true">
      <van-progress :percentage="exampercentage" :show-pivot="false" />
    </div>
    <van-row v-if="flag == false">
      <van-cell center title="显示中文">
            <template #right-icon>
              <van-switch v-model="chineseFlag" size="24" />
            </template>
          </van-cell>
          <van-cell center style="margin-bottom:4vh" title="自动播放">
            <template #right-icon>
              <van-switch v-model="autoPlayFlag" size="24" />
            </template>
          </van-cell>
    </van-row>
    <van-row type="flex" justify="center">
      <van-col span="22" class="word-center">
        <div style="padding-top: 2rem" v-if="flag == false">
          <van-button
            type="info"
            loading-text="加载中..."
            :loading="examLoading"
            @click="exam">开始考试</van-button>
          <p style="padding-top: 2rem">近期考试情况</p>
          <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
            <van-list
              v-model="loading"
              :finished="finished"
              finished-text="没有更多了"
              @load="onLoad"
            >
              <van-cell v-for="item in list" :key="item" :title="item" />
            </van-list>
          </van-pull-refresh>
        </div>
        <van-popup
          v-model="showCountDown"
          :style="{ height: '100%', width: '100%' }"
        >
          <div style="padding-top: 60%; font-size: 40px">
            <van-circle
              v-model="currentRate"
              :rate="rate"
              :speed="50"
              size="240px"
              :clockwise="false"
              text="考试即将开始"
            />
          </div>
        </van-popup>
        <div class="word word-center" v-if="flag == true">
          <span>{{ word.split("_")[0] }}</span
          ><span style="color: green">{{ key }}</span
          ><span>{{ word.split("_")[1] }}</span>
          <span v-if="chineseFlag" id="translation">
            {{ translation[wordIndex] }}
          </span>
        </div>
        <audio id="audio" preload="auto" controls v-show="flag == true">
          <source :src="chats[0]" />
        </audio>
      </van-col>
    </van-row>
    <van-row type="flex" justify="center">
      <van-col span="4">
        <div style="margin-top: 1.5rem; margin-bottom: 1.5rem">
          <!-- <van-count-down
            v-show="showWordCountDown"
            ref="countDown"
            @finish="finish"
            :auto-start="false"
            millisecond
            :time="time"
            format="mm:ss:SS"
          /> -->
          <van-count-down
            :auto-start="false"
            @finish="finish"
            ref="countDown"
            :time="time"
            v-show="showWordCountDown"
          >
            <template #default="timeData">
              <span class="block">{{ timeData.seconds }}</span>
            </template>
          </van-count-down>
          <!-- <van-icon name="volume-o" /> -->
        </div>
      </van-col>
    </van-row>
    <van-row>
      <!-- <div style="margin-top: 2rem" v-if="flag == true">
        <van-field v-model="key" label="答案" readonly  />
      </div> -->
    </van-row>
    <van-row type="flex" justify="center" v-if="flag == true">
      <van-col span="2">
        <van-button round @click="inputKey('q')" type="info">Q</van-button>
        <van-divider />
        <van-button round @click="inputKey('a')" type="info">A</van-button>
        <van-divider />
        <van-button round @click="inputKey('z')" type="info">Z</van-button>
      </van-col>
      <van-col span="2">
        <van-button round @click="inputKey('w')" type="info">W</van-button>
        <van-divider />
        <van-button round @click="inputKey('s')" type="info">S</van-button>
        <van-divider />
        <van-button round @click="inputKey('x')" type="info">X</van-button>
      </van-col>
      <van-col span="2">
        <van-button round @click="inputKey('e')" type="info">E</van-button>
        <van-divider />
        <van-button round @click="inputKey('d')" type="info">D</van-button>
        <van-divider />
        <van-button round @click="inputKey('c')" type="info">C</van-button>
      </van-col>
      <van-col span="2">
        <van-button round @click="inputKey('r')" type="info">R</van-button>
        <van-divider />
        <van-button round @click="inputKey('f')" type="info">F</van-button>
        <van-divider />
        <van-button round @click="inputKey('v')" type="info">V</van-button>
      </van-col>
      <van-col span="2">
        <van-button round @click="inputKey('t')" type="info">T</van-button>
        <van-divider />
        <van-button round @click="inputKey('g')" type="info">G</van-button>
        <van-divider />
        <van-button round @click="inputKey('b')" type="info">B</van-button>
      </van-col>
      <van-col span="2">
        <van-button round @click="inputKey('y')" type="info">Y</van-button>
        <van-divider />
        <van-button round @click="inputKey('h')" type="info">H</van-button>
        <van-divider />
        <van-button round @click="inputKey('n')" type="info">N</van-button>
      </van-col>
      <van-col span="2">
        <van-button round @click="inputKey('u')" type="info">U</van-button>
        <van-divider />
        <van-button round @click="inputKey('j')" type="info">J</van-button>
        <van-divider />
        <van-button round @click="inputKey('m')" type="info">M</van-button>
      </van-col>
      <van-col span="2">
        <van-button round @click="inputKey('i')" type="info">I</van-button>
        <van-divider />
        <van-button round @click="inputKey('k')" type="info">K</van-button>
        <van-divider />
        <van-button round @click="inputKey('o')" type="info">O</van-button>
      </van-col>
      <van-col span="2">
        <van-button round @click="inputKey('l')" type="info">L</van-button>
        <van-divider />
        <van-button round @click="inputKey('p')" type="info">P</van-button>
      </van-col>
    </van-row>
    <van-row type="flex" justify="end">
      <div v-if="flag == true" style="margin-top: 0.6rem">
        <van-button round @click="nextBtn" type="info">下一题</van-button>
      </div>
    </van-row>
  </div>
</template>

<script>
import { Dialog, Toast } from "vant";
import Cookies from "js-cookie";
import apiFunc from "@/apis/api";
export default {
  name: "index2",
  data() {
    return {
      flag: false,
      showWordCountDown: false,
      examLoading: false,
      showCountDown: false,
      words: [],
      keys: [],
      word: "",
      key: "_",
      exampercentage: 0,
      showCountDownTime: 3000,
      time: 10 * 1000,
      currentRate: 100,
      rate: 100,
      wordIndex: 0,
      chats: [],
      correctKeys: [],
      list: [],
      translation: [],
      chineseFlag: true,
      autoPlayFlag: true,
      loading: false,
      finished: false,
      refreshing: false,
    };
  },
  mounted() {
    let words = localStorage.getItem(
      new Date().getMonth() + 1 + "-" + new Date().getDate() + "words"
    );
    let keys = localStorage.getItem(
      new Date().getMonth() + 1 + "-" + new Date().getDate() + "keys"
    );
    let translations = localStorage.getItem(
      new Date().getMonth() + 1 + "-" + new Date().getDate() + "translations"
    );
    let chats = localStorage.getItem(
      new Date().getMonth() + 1 + "-" + new Date().getDate() + "chats"
    );
    let correctKeys = localStorage.getItem(
      new Date().getMonth() + 1 + "-" + new Date().getDate() + "correctKeys"
    );
    if (words.split(",").length > keys.split(",").length) {
      Dialog.confirm({
        title: "温馨提示",
        message: "检测到您今天还有未完成的考试,是否继续作答?",
      })
        .then(() => {
          this.words = words.split(",");
          this.correctKeys = correctKeys.split(",");
          this.keys = keys.split(",");
          this.translation = translations.split(".,");
          this.chats = chats.split(",");
          this.wordIndex = this.keys.length;
          this.word = this.words[this.wordIndex];
          this.showCountDown = true;
          for (let i = 0; i < 2; i++) {
            this.rate = this.rate - 50;
            setTimeout(() => {
              this.rate = this.rate - 50;
            }, 1000);
          }
          // on confirm
        })
        .then(() => {
          setTimeout(() => {
            this.showCountDown = false;
            this.flag = true;
            this.showWordCountDown = true;
            this.$refs.countDown.start();
            this.exampercentage =
              this.exampercentage +
              ((this.keys.length + 1) * 100) / this.words.length;
              let audio = document.getElementById("audio");
            audio.src = this.chats[this.wordIndex];
            if(this.autoPlayFlag === true){
          audio.play();
        }
          }, 2000);
        })
        .catch(() => {
          localStorage.clear();
          // on cancel
        });
    } else {
      localStorage.clear();
    }
  },
  methods: {
    exam() {
      this.examLoading = true;
      apiFunc.getWords().then((res) => {
        this.wordInfo = res.data;
        for (let i = 0; i < 50; i++) {
          this.words.push(res.data[i].subWord);
          this.chats.push(res.data[i].online);
          this.correctKeys.push(res.data[i].key);
          this.translation.push(res.data[i].chinese + ".");
        }
        localStorage.setItem(
          new Date().getMonth() + 1 + "-" + new Date().getDate() + "words",
          this.words
        );
        localStorage.setItem(
          new Date().getMonth() +
            1 +
            "-" +
            new Date().getDate() +
            "translations",
          this.translation
        );
        localStorage.setItem(
          new Date().getMonth() + 1 + "-" + new Date().getDate() + "chats",
          this.chats
        );
        localStorage.setItem(
          new Date().getMonth() +
            1 +
            "-" +
            new Date().getDate() +
            "correctKeys",
          this.correctKeys
        );
        this.examLoading = false;
        this.showCountDown = true;
        for (let i = 0; i < 2; i++) {
          this.rate = this.rate - 50;
          setTimeout(() => {
            this.rate = this.rate - 50;
          }, 1000);
        }
        setTimeout(() => {
          this.showCountDown = false;
          this.flag = true;
          this.showWordCountDown = true;
          this.$refs.countDown.start();
          this.exampercentage = this.exampercentage + 100 / this.words.length;
          this.word = this.words[this.wordIndex];
          let audio = document.getElementById("audio");
          if(this.autoPlayFlag === true){
          audio.play();
        }
        }, 2000);
      });
    },
    finish() {
      this.wordIndex++;
      if (this.wordIndex < this.words.length) {
        this.keys.push(this.key);
        localStorage.setItem(
          new Date().getMonth() + 1 + "-" + new Date().getDate() + "keys",
          this.keys
        );
        this.key = "_";
        this.exampercentage = this.exampercentage + 100 / this.words.length;
        this.word = this.words[this.wordIndex];
        this.$refs.countDown.reset();
        this.$refs.countDown.start();
        let audio = document.getElementById("audio");
        audio.src = this.chats[this.wordIndex];
        if(this.autoPlayFlag === true){
          audio.play();
        }
      }
      if (this.wordIndex == this.words.length) {
        this.keys.push(this.key);
        localStorage.setItem(
          new Date().getMonth() + 1 + "-" + new Date().getDate() + "keys",
          this.keys
        );
        this.$refs.countDown.pause();
        let score = 0;
        for (let i = 0; i < 50; i++) {
          if (this.keys[i] == this.correctKeys[i]) {
            score += 2;
          }
        }
        apiFunc.submitGrade(score, Cookies.get("userName")).then((res) => {
          if (res.data === 1) {
            Dialog.alert({
              message: "考试结束,分数为" + score,
            }).then(() => {
              // on close
              this.flag = false;
              this.showWordCountDown = false;
              this.onRefresh();
            });
          }
        });
      }
    },
    nextBtn() {
      this.wordIndex++;
      if (this.wordIndex < this.words.length) {
        this.keys.push(this.key);
        localStorage.setItem(
          new Date().getMonth() + 1 + "-" + new Date().getDate() + "keys",
          this.keys
        );
        this.key = "_";
        this.exampercentage = this.exampercentage + 100 / this.words.length;
        this.word = this.words[this.wordIndex];
        this.$refs.countDown.reset();
        this.$refs.countDown.start();
        let audio = document.getElementById("audio");
        audio.src = this.chats[this.wordIndex];
        if(this.autoPlayFlag === true){
          audio.play();
        }
      }
      if (this.wordIndex == this.words.length) {
        this.keys.push(this.key);
        localStorage.setItem(
          new Date().getMonth() + 1 + "-" + new Date().getDate() + "keys",
          this.keys
        );
        this.$refs.countDown.pause();
        let score = 0;
        for (let i = 0; i < 50; i++) {
          if (this.keys[i] == this.correctKeys[i]) {
            score += 2;
          }
        }
        apiFunc.submitGrade(score, Cookies.get("userName")).then((res) => {
          if (res.data === 1) {
            Dialog.alert({
              message: "考试结束,分数为" + score,
            }).then(() => {
              // on close
              this.flag = false;
              this.showWordCountDown = false;
              this.onRefresh();
            });
          }
        });
      }
    },
    inputKey(char) {
      this.key = char;
    },
    onLoad() {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      apiFunc.getGrade(Cookies.get("userName")).then((res) => {
        for (let i = 0; i < res.data.length; i++) {
          this.list.push(
            "分数：" + res.data[i].grade + "\t日期：" + res.data[i].date
          );
        }

        // 加载状态结束
        this.loading = false;

        // 数据全部加载完成
        this.finished = true;
      });
    },
    onRefresh() {
      // 清空列表数据
      this.finished = false;
      this.list.length = 0;
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true;
      this.onLoad();
      this.refreshing = false;
    },
  },
};
</script>
<style scoped>
.exam {
  background-color: #fafafa;
}
.word-center {
  text-align: center;
}
.word {
  height: 14rem;
  line-height: 14rem;
  font-size: 45px;
  font-weight: 900;
  color: lightslategray;
  font-family: "Gentona Free Demo";
}
.block {
  display: inline-block;
  border-radius: 100%;
  width: 4rem;
  height: 4rem;
  color: #fff;
  font-size: 3rem;
  text-align: center;
  line-height: 4rem;
  background-color: #ee0a24;
}
#translation {
  color: black;
  font-size: 1rem;
  line-height: 1rem;
  display: block;
  margin-top: -4.5rem;
}
</style>