<template>
  <view>
    <view id="top-box"
          class="cu-bar bg-white solid-bottom">
      <view class="action text-black">
        <text v-if="currentType===1">判断题</text>
        <text v-else-if="currentType===2">单选题</text>
        <text v-else-if="currentType===3">多选题</text>
        <text v-else-if="currentType===4">填空题</text>
        <text v-else-if="currentType===5">问答题</text>
      </view>
      <view v-if="!isBl">剩余作答时间:</view>
      <!-- exam.exam_time -->
      <tui-countdown v-if="!isBl"
                     :time="exam.exam_time"
                     borderColor="#fff"
                     color="#cf1322"
                     :size="40"
                     :colonSize="45"
                     colonColor="#cf1322"
                     returnTime
                     @time="subTime"
                     @end="clickSubmit(false)"></tui-countdown>
      <view class="action">
        <button class="cu-btn bg-blue shadow"
                @tap="showCardModal"
                data-target="modalCard">答题卡</button>
      </view>
    </view>
    <view class="cu-modal"
          :class="modalCard=='modalCard'?'show':''"
          @tap="hideCardModal">
      <view class="cu-dialog"
            @tap.stop>

        <scroll-view class="page padding"
                     :scroll-y=true
                     :style="{'height':swiperHeight}">
          <view class="cu-bar solid-bottom">
            <view class="action">
              <text class="cuIcon-title text-red"></text>答题卡
            </view>
          </view>
          <view class="grid col-5 ">
            <view class="margin-tb-sm text-center"
                  v-for="(subject,index) in subjectList"
                  :key="index">
              <button class="cu-btn round"
                      :class="[subject.userAnswer.length===0?'line-grey':'bg-blue']"
                      @click="AppointedSubject(index)">{{index+1}}</button>
            </view>
          </view>

        </scroll-view>
      </view>
    </view>
    <view class="cu-modal padding "
          :class="modalError=='modalError'?'show':''"
          @tap="hideErrorModal">
      <view class="cu-dialog bg-white"
            @tap.stop>

        <view class="cu-bar solid-bottom ">
          <view class="action">
            <text class="cuIcon-title text-red"></text>试题纠错
          </view>
        </view>

        <radio-group class="block">
          <view class="cu-list menu text-left">
            <view class="cu-item cu-item-error"
                  v-for="(error,index) in errorList"
                  :key="index">
              <radio :value="error"></radio>
              <view class="title text-black margin-left">{{error}}</view>
            </view>
          </view>
        </radio-group>

        <view class="padding flex flex-direction ">
          <button class="cu-btn bg-red margin-tb-sm lg"
                  @click="SubmitError">提 交</button>
        </view>
      </view>
    </view>
    <form>
      <swiper :current="subjectIndex"
              class="swiper-box"
              @change="SwiperChange"
              :style="{'height':swiperHeight}">
        <swiper-item v-for="(subject,index) in subjectList"
                     :key="index">

          <view v-if="index-subjectIndex>=-1&&index-subjectIndex<=1">

            <view class="cu-bar bg-white solid-bottom">
              <view class="action text-black">
                <text class="cuIcon-title text-blue"></text>{{index+1+'.'}} {{subject.title}}
              </view>
            </view>
            <view>

              <radio-group class="block"
                           @change="RadioboxChange"
                           v-if="subject.type===1||subject.type===2">
                <view class="cu-form-group"
                      v-for="(option,index) in subject.optionList"
                      :key="index">
                  <radio :value="option.id"
                         :checked="subject.userAnswer.indexOf(option.id) > -1?true:false"></radio>
                  <view class="title text-black">{{option.id}}.{{option.content}}</view>
                </view>
              </radio-group>

              <checkbox-group class="block"
                              @change="CheckboxChange"
                              v-else-if="subject.type===3">
                <view class="cu-form-group"
                      v-for="(option,index) in subject.optionList"
                      :key='index'>
                  <checkbox :value="option.id"
                            :class="subject.userAnswer.indexOf(option.id) > -1?'checked':''"
                            :checked="subject.userAnswer.indexOf(option.id) > -1?true:false"></checkbox>
                  <view class="title  text-black">{{option.id}}.{{option.content}}</view>
                </view>
              </checkbox-group>

              <view v-else-if="subject.type===4">
                <view class="cu-form-group solid-bottom">
                  <view class="title  text-black">
                    答：
                  </view>
                  <input placeholder="文本输入框"
                         name="input"
                         v-model="subject.userAnswer"
                         @blur="textInput"></input>
                </view>
              </view>

              <view v-else-if="subject.type===5">
                <view class="cu-bar cu-bar-title bg-white margin-top">
                  <view class="action  text-black">
                    答：
                  </view>
                </view>
                <view class="cu-form-group solid margin">
                  <textarea maxlength="-1"
                            @blur="textInput"
                            v-model="subject.userAnswer"
                            placeholder="多行文本输入框"></textarea>
                </view>
              </view>

            </view>

            <view v-show="subject.showAnswer"
                  class="margin-top solid-top">
              <view class="cu-bar">
                <view class="action  text-grey">
                  <text>正确答案：</text>
                  <text class="solid-bottom  padding-left text-green">{{subject.answer}}</text>
                </view>
              </view>
              <view class="cu-bar cu-bar-title">
                <view class="action  text-grey">
                  <text>解析：</text>
                </view>
              </view>
              <view class="text-content padding  text-grey">
                {{subject.explain}}
              </view>
            </view>

          </view>
          <tui-button v-if="subjectIndex == subjectList.length - 1 &&!isBl"
                      width="80%"
                      shape="circle"
                      :preventClick="true"
                      style="margin: 10px auto;"
                      @click="clickSubmit">提交</tui-button>
          <tui-modal :show="modal"
                     @click="handleClick"
                     @cancel="hideModal"
                     title="提示"
                     content="还有题目没有作答!是否继续提交?"
                     :button="[{
                      text: '取消',type: 'plain',plain: true
                    },
                    {
                      text: '确定',type: 'primary',plain: false
                    }]"></tui-modal>
        </swiper-item>
      </swiper>

    </form>

    <view id="foot-box"
          class="cu-bar tabbar bg-white shadow foot">
      <view class="action"
            @click="MoveSubject(-1)">
        <view class="cuIcon-cu-image">
          <text class="lg cuIcon-back text-gray"></text>
        </view>
        <view class="text-gray">上一题</view>
      </view>
      <view class="action"
            @click="MoveSubject(1)">
        <view class="cuIcon-cu-image">
          <text class="lg text-gray cuIcon-right"></text>
        </view>
        <view class="text-gray">下一题</view>
      </view>

      <!-- <view class="action"
            @click="FavorSubject">
        <view class="cuIcon-cu-image">
          <text class="lg cuIcon-favor"
                :class="[userFavor?'text-red':'text-gray']"></text>
        </view>
        <view :class="[userFavor?'text-red':'text-gray']">收藏</view>
      </view> -->

      <view class="action"
            @click="ShowAnswerChange">
        <view class="cuIcon-cu-image">
          <text class="lg text-gray cuIcon-question"></text>
        </view>
        <view class="text-gray">解答</view>
      </view>
      <view class="action"
            @tap="showErrorModal"
            data-target="modalError">
        <view class="cuIcon-cu-image">
          <text class="lg text-gray cuIcon-warn"></text>
        </view>
        <view class="text-gray">纠错</view>
      </view>

    </view>
    <tui-modal :show="modalMsg"
               @click="handleClickMsg"
               @cancel="hideModalMsg"
               :content="contentMsg"
               :button="[{
                text: '取消',type: 'plain',plain: true
              },
               {
                text: '确定',type: 'primary',plain: false
               }]">

    </tui-modal>
  </view>
</template>

<script>
/*
 *
 *  需要二次开发或项目外包的请加QQ 271478027 或 微信 jialongvip
 *
 */
import { mapState } from "vuex";
export default {
  computed: {
    ...mapState(["userinfo"]),
  },
  data() {
    return {
      modalMsg: false,
      contentMsg: "是否进入答题",
      seconds: 0,
      modal: false,
      userFavor: false, //是否已收藏
      currentType: 0, //当前题型
      subjectIndex: 0, //跳转索引
      autoShowAnswer: false, //答错是否显答案
      autoRadioNext: true, //判断题、单项题，自动移下一题
      swiperHeight: "800px", //
      title: "考试",
      exam: {
        exam_time: 999999, //答题总时间
        question_num: null, //试题总数
        score: null, //试题总分数
      },
      subjectList: [],
      modalCard: null, //显示答题卡
      modalError: null, //纠错卡
      errorList: [
        "题目不完整",
        "答案不正确",
        "含有错别字",
        "图片不存在",
        "解析不完整",
        "其他错误",
      ],
      isBl: false,
    };
  },
  onBackPress() {
    // if (!this.isBl) this.showModalMsg("退出答题会删除答题结果!是否退出答题?");
    // return false;
  },
  onReady() {
    var tempHeight = 800;
    var _me = this;
    uni.getSystemInfo({
      //获取手机屏幕高度信息，让swiper的高度和手机屏幕一样高
      success: function (res) {
        tempHeight = res.windowHeight;
        //console.log("屏幕可用高度 " + tempHeight);
        uni
          .createSelectorQuery()
          .select("#top-box")
          .fields(
            {
              size: true,
              scrollOffset: true,
            },
            (data) => {
              tempHeight -= data.height;
              //  console.log("减掉顶部后的高度 " + tempHeight);
              uni
                .createSelectorQuery()
                .select("#foot-box")
                .fields(
                  {
                    size: true,
                    scrollOffset: true,
                  },
                  (data) => {
                    tempHeight -= data.height;
                    // console.log("减掉底部后的高度 " + tempHeight);
                    _me.swiperHeight = tempHeight + "px";
                    //  console.log("滑屏最后高度 " + _me.swiperHeight);
                  }
                )
                .exec();
            }
          )
          .exec();
      },
    });
  },
  async onLoad() {
    let routes = getCurrentPages();
    let dataQuestionArr = routes[routes.length - 1]?.options?.data;
    if (!!dataQuestionArr) {
      this.isBl = true;
      dataQuestionArr = JSON.parse(dataQuestionArr);
      dataQuestionArr.forEach((element, index) => {
        this.subjectList.push({
          title: element.question_name,
          type: this.getType(element.question_type),
          optionList: this.getParseTypeOption(
            element.question_type,
            element.q_options
          ),
          answer: element.answer,
          userAnswer: element.user_answer,
          userFavor: false,
          explain: element.desctext,
          ...element,
        });
      });
      // 添加用户显示答案字段
      for (var i = 0; i < this.subjectList.length; i++) {
        this.$set(this.subjectList[i], "showAnswer", true);
      }
    } else {
      this.showModalMsg("是否进入答题");
      await this.getQuestion();
    }
    //题目类型
    this.currentType = this.subjectList[0].type;
    // uni.setNavigationBarTitle({
    //   title: this.title,
    // });
  },
  methods: {
    async getQuestion() {
      try {
        const res = await this.$request.post(
          `examination/Question/setQuestion`
        );
        res.data.questionArr.forEach((element, index) => {
          this.subjectList.push({
            title: element.question_name, //题目
            type: this.getType(element.question_type),
            optionList: this.getParseTypeOption(
              element.question_type,
              element.q_options
            ), //选项--**
            answer: element.answer, //答案
            userAnswer: "",
            userFavor: false,
            explain: element.desctext,
            ...element,
          });
        });
        this.exam = res.data.exam;
        this.exam.exam_time = this.exam.exam_time * 60;
      } catch (error) {
        console.log("error:", error);
        uni.showToast({
          title: "网络错误",
          icon: "none",
        });
      }
    },
    getType(type) {
      switch (type) {
        //填空
        case 1:
          return 4;
        case 2:
          return 2;
        case 3:
          return 3;
        case 4:
          return 2;
      }
    },

    getParseTypeOption(type, option) {
      // console.log("getParseTypeOption转换中:", option);
      switch (type) {
        case 1:
          return [{ id: "", content: "" }];
        // 单选题
        case 2:
          let arr2 = [];
          for (let i = 0; i < option.length; i++) {
            arr2.push({ id: option[i].item, content: option[i].value });
          }
          return arr2;
        case 3:
          let arr3 = [];
          for (let i = 0; i < option.length; i++) {
            arr3.push({ id: option[i].item, content: option[i].value });
          }
          return arr3;
        case 4:
          let arr4 = [];
          for (let i = 0; i < option.length; i++) {
            arr4.push({ id: option[i].item, content: option[i].value });
          }
          return arr4;
      }
    },
    //提交
    async clickSubmit(bl = true) {
      // 题目是否作答检测
      if (bl) {
        for (let i = 0; i < this.subjectList.length; i++) {
          if (this.subjectList[i].userAnswer == "") {
            this.showModal();
            return;
          }
        }
      }
      uni.showLoading({
        title: "正在提交",
        mask: true,
      });
      try {
        let subQuestionArr = this.subConvertQuestionArr(
          JSON.parse(JSON.stringify(this.subjectList))
        );
        //console.log("用户编号", this.userinfo);
        await this.$request.post("examination/Question/submitQuestion", {
          body: {
            user_id: this.userinfo.userId,
            score: this.exam.score,
            total_score: subQuestionArr.total_score, //用户分数
            exam_time: this.exam.exam_time,
            user_exam_time: Math.ceil(
              (this.exam.exam_time - this.seconds) / 60
            ), //使用时间
            questionArr: subQuestionArr.questionArr,
          },
        });
        uni.showToast({
          title: "试卷提交成功",
          icon: "success",
        });
        uni.redirectTo({
          url: "/pages/template/exam/examIndex",
        });
      } catch (e) {
        // console.log(e);
      }
    },
    subTime(data) {
      this.seconds = data.seconds;
    },

    subConvertQuestionArr(questionArr) {
      let total_score = 0;
      questionArr.forEach((element) => {
        delete element.title;

        delete element.optionList;
        delete element.userFavor;
        delete element.explain;
        element.user_answer = element.userAnswer;
        delete element.userAnswer;
        if (element.type == 3) {
          let str = "";
          for (let i = 0; i < element.user_answer.length; i++) {
            str += element.user_answer[i] + ",";
          }
          element.user_answer = str.slice(0, -1);
        }
        //判题
        if (element.user_answer == element.answer) {
          element.user_score = Number(element.score);
          total_score += Number(element.score);
        } else {
          element.user_score = 0;
        }
        delete element.type;
      });
      return { questionArr, total_score };
    },
    showCardModal(e) {
      this.modalCard = e.currentTarget.dataset.target;
    },
    hideCardModal(e) {
      this.modalCard = null;
    },
    showErrorModal(e) {
      this.modalError = e.currentTarget.dataset.target;
    },
    hideErrorModal(e) {
      this.modalError = null;
    },
    SwiperChange(e) {
      //滑动事件

      let index = e.target.current;

      if (index != undefined) {
        this.subjectIndex = index;
        this.currentType = this.subjectList[index].type;
        // this.userFavor = this.subjectList[index].userFavor;//收藏
      }
    },
    RadioboxChange(e) {
      //单选选中
      var items = this.subjectList[this.subjectIndex].optionList;
      var values = e.detail.value;
      this.subjectList[this.subjectIndex].userAnswer = values;
      //console.log("subjectList单选选中length:", this.subjectList);
      if (
        this.autoRadioNext &&
        this.subjectIndex < this.subjectList.length - 1
      ) {
        this.subjectIndex += 1;
      }
    },
    CheckboxChange(e) {
      //复选选中
      // console.log(
      //   "CheckboxChange单选this.subjectList[this.subjectIndex].optionList选中length:",
      //   this.subjectList[this.subjectIndex].optionList
      // );
      var items = this.subjectList[this.subjectIndex].optionList;
      var values = e.detail.value;
      this.subjectList[this.subjectIndex].userAnswer = "";
      for (var i = 0, lenI = items.length; i < lenI; ++i) {
        for (var j = 0, lenJ = values.length; j < lenJ; ++j) {
          if (items[i].id == values[j]) {
            this.subjectList[this.subjectIndex].userAnswer += items[i].id;
            break;
          }
        }
      }
    },
    textInput(e) {
      //填空题

      this.subjectList[this.subjectIndex].userAnswer = e.detail.value;
    },
    ShowAnswerChange: function (e) {
      //显示答案

      if (this.subjectList[this.subjectIndex].showAnswer) {
        this.subjectList[this.subjectIndex].showAnswer = false;
      } else {
        this.subjectList[this.subjectIndex].showAnswer = true;
      }
    },

    FavorSubject: function (e) {
      //收藏题

      if (this.userFavor) {
        this.userFavor = false;
        this.subjectList[this.subjectIndex].userFavor = false;
      } else {
        this.userFavor = true;
        this.subjectList[this.subjectIndex].userFavor = true;
      }
    },

    MoveSubject: function (e) {
      //上一题、下一题

      if (e === -1 && this.subjectIndex != 0) {
        this.subjectIndex -= 1;
      }
      if (e === 1 && this.subjectIndex < this.subjectList.length - 1) {
        this.subjectIndex += 1;
      }
    },
    //调用此方法显示组件
    showModal() {
      this.modal = true;
    },
    //隐藏组件
    hideModal() {
      this.modal = false;
    },
    handleClick(e) {
      let index = e.index;
      if (index === 0) {
      } else {
        this.clickSubmit(false);
      }
      this.hideModal();
    },
    //调用此方法显示组件
    showModalMsg(msg) {
      this.contentMsg = msg;
      this.modalMsg = true;
    },
    //隐藏组件
    hideModalMsg() {
      this.modalMsg = false;
    },
    handleClickMsg(e) {
      let index = e.index;
      if (this.contentMsg == "退出答题会删除答题结果!是否退出答题?") {
        if (index === 0) {
          // this.tui.toast("你点击了取消按钮");
          // this.modalMsg = false;
        } else {
          // this.tui.toast("你点击了确定按钮");
          this.modalMsg = false;
          uni.navigateBack();
        }
        return;
      }
      if (index === 0) {
        // this.tui.toast("你点击了取消按钮");
        uni.navigateBack();
      } else {
        // this.tui.toast("你点击了确定按钮");
        this.modalMsg = false;
      }
      this.hideModal();
    },
    AppointedSubject: function (e) {
      //题卡指定
      this.modalCard = null;
      this.subjectIndex = e;
    },

    SubmitError: function (e) {
      //提交纠错

      this.modalError = null;
    },
  },
};
</script>

<style>
@import "colorui/main.css";
@import "colorui/icon.css";
@import "./colorui/animation.css";
page {
  background-color: #ffffff;
}

.cu-form-group {
  justify-content: flex-start;
}

.cu-form-group .title {
  padding-left: 30upx;
  padding-right: 0upx;
}

.cu-form-group + .cu-form-group {
  border-top: none;
}

.cu-bar-title {
  min-height: 50upx;
}

.cu-list.menu > .cu-item-error {
  justify-content: flex-start;
}
</style>
