<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: 1rem" v-if="flag == false">    

              <p style="font-size:14px;">近5条记录</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>

              <p style="padding-top: 1rem"></p>

              <van-button round class="start-btn" 
                type="info"
                loading-text="加载中..."
                :loading="examLoading"
                @click="exam">开 始 测 试
              </van-button>
        </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="220px"
                      :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="meta" 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: 1rem; margin-bottom: 1rem">
          <!-- <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  />   type="flex" justify="center"
      </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="center">
          <div v-if="flag == true" style="margin-top: 2.1rem">
            <van-button round class="next-btn" @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,
      score: 0,
      errorStr:"",
    };
  },
  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(" ,"); // add this " " for split translation,otherwise if contain "," use "," split will occur error
          this.chats = chats.split(",");
          this.wordIndex = this.keys.length;
          this.word = this.words[this.wordIndex];
          this.showCountDown = true;
          this.currentRate=100;
          this.rate =100;
          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[i] = res.data[i].subWord;//this.words.push(res.data[i].subWord);,不使用push，不退页面，连续测试时，永远取得是第1次的前50个
          this.chats[i] = res.data[i].online;
          this.correctKeys[i] = res.data[i].key;
          this.translation[i] = res.data[i].chinese + " ";// add this " " for split translation,otherwise if contain "," use "," split will occur error
        }
        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;
        this.currentRate=100;
        this.rate =100;
        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");
              audio.src = this.chats[this.wordIndex];
          if(this.autoPlayFlag === true){
          audio.play();
        }
        }, 2000);
      });
    },
    finish() {
      this.wordIndex++;
      if (this.wordIndex < this.words.length) {
        let indexKey = this.wordIndex - 1;
        this.keys[indexKey] = 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) {
        let indexKey = this.wordIndex - 1;
        this.keys[indexKey] = this.key;   
        localStorage.setItem(
          new Date().getMonth() + 1 + "-" + new Date().getDate() + "keys",
          this.keys
        );
        this.$refs.countDown.pause();
        this.score = 0;
        this.errorStr = "";
        for (let i = 0; i < 50; i++) {
          if (this.keys[i].toLowerCase() == this.correctKeys[i].toLowerCase()) {
            this.score += 2;
          }else{
            this.errorStr = this.errorStr + this.words[i] + " 所填 " + this.keys[i] +  " 答案 " + this.correctKeys[i] + "\n";
          }
        }
        apiFunc.submitGrade(this.score, Cookies.get("userName")).then((res) => {
          if (res.data === 1) {
                          // on close
                          this.flag = false;
              this.showWordCountDown = false;
              this.exampercentage = 0;
              this.wordIndex = 0;
              this.onRefresh(); //页面不会闪白

            Dialog.alert({
              title: "测试结束",
              message: "分数为 " + this.score,
            }).then(() => {
              
              if (this.score < 100) {
                //this.scoreLess100 = true;
                Dialog.alert(
                  {                    
                     message:  "答错" + "\n" + this.errorStr,
                  }
                )
              };
              //this.$router.go(0);路由重定向，页面会闪白，解决测试1次后，不退出，再测试，分数不变的问题，Dialog.alert,不能阻塞后面的语句             
            });
          }
        });
      }
    },
    nextBtn() {
      this.wordIndex++;
      if (this.wordIndex < this.words.length) {
        let indexKey = this.wordIndex - 1;
        this.keys[indexKey] = 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) {
        let indexKey = this.wordIndex - 1;
        this.keys[indexKey] = this.key; 
        localStorage.setItem(
          new Date().getMonth() + 1 + "-" + new Date().getDate() + "keys",
          this.keys
        );
        this.$refs.countDown.pause();
        this.score = 0;
        this.errorStr = "";
        for (let i = 0; i < 50; i++) {
          if (this.keys[i].toLowerCase() == this.correctKeys[i].toLowerCase()) {
            this.score += 2;
          }else{
            this.errorStr = this.errorStr + this.words[i] + " 所填 " + this.keys[i] +  " 答案 " + this.correctKeys[i] + "\n";
          }
        }
        apiFunc.submitGrade(this.score, Cookies.get("userName")).then((res) => {
          if (res.data === 1) {
                                      // on close
                                      this.flag = false;
              this.showWordCountDown = false;
              this.exampercentage = 0;
              this.wordIndex = 0;
              this.onRefresh(); //页面不会闪白

            Dialog.alert({
              title: "测试结束",
              message: "分数为 " + this.score,
            }).then(() => {
             
              if (this.score < 100) {
                //this.scoreLess100 = true;
                Dialog.alert(
                  {                    
                     message:  "答错" + "\n" + this.errorStr,
                  }
                )
              };
               //this.$router.go(0);路由重定向，页面会闪白，解决测试1次后，不退出，再测试，分数不变的问题，Dialog.alert,不能阻塞后面的语句
            });
          }
        });
      }
    },
    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[i] =  "分数：" + 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;
}
.start-btn {
  width: 278px;
  height: 48px;

}
.next-btn {
  width: 278px;
  height: 48px;

}
.word-center {
  text-align: center;
}
.word {
  height: 9rem;
  line-height: 9rem;
  font-size: 40px;
  font-weight: 900;
  color: lightslategray;
  font-family: "Gentona Free Demo";
}
.block {
  display: inline-block;
  border-radius: 100%;
  width: 3rem;
  height: 3rem;
  color: #fff;
  font-size: 2rem;
  text-align: center;
  line-height: 3rem;
  background-color: #ee0a24;
}
#translation {
  color: black;
  font-size: 1rem;
  line-height: 1rem;
  display: block;
  margin-top: -2.5rem;
}
</style>