<template>
  <div class="survey-container">
    <div class="header">
      <!-- <img src="./logo-header-phone.jpg" alt=""> -->
      {{headerInfo.title}}（课程评估）
    </div>
    <div class="progress">
      <div class="cur-progress" :style="{ width: progress}"></div>
    </div>
    <div class="exam-box">
      <template v-for='(item, index) in exam.group'>
        <template v-if='item.type === 1'>
          <div v-bind:key="index" class='q-group' @click="radioClick" :data-index='index'>
            <div class='q-item'>{{item.title}}</div>
            <el-radio-group class='radio-group' @change='radioChange' v-model="item.sel">
              <template v-for='(item1, index1) in item.arr'>
                <!-- checked='{{item1.selected}}' -->
                <el-radio v-bind:key="index1" :label='index1' :disabled='!!item.cur' :class='["radio"]'>{{item1.option}}</el-radio>
                <template v-if="item1.txt !== undefined && item1.selected">
                  <el-input v-bind:key="item1.id" v-model="item1.txt" placeholder="请说明"></el-input>
                </template>
              </template>
            </el-radio-group>
          </div>
        </template>
        <template v-if='item.type === 2'>
          <div v-bind:key="index" class='q-group' @click="checkboxClick" :data-index='index'>
            <div class='q-item'>{{item.title}}</div>
            <el-checkbox-group class='checkbox-group' @change='checkboxChange' v-model="item.arrSel">
              <template v-for='(item1, index1) in item.arr'>
                <!-- value='{{index1}}' -->
                <el-checkbox v-bind:key="item1.id" :label='index1' :disabled='!!item.cur' :class='["checkbox"]'>{{item1.option}}</el-checkbox>
                <template v-if="item1.txt !== undefined && item1.selected">
                  <el-input v-bind:key="index1" v-model="item1.txt" placeholder="请说明"></el-input>
                </template>
              </template>
            </el-checkbox-group>
          </div>
        </template>
        <template v-if="item.type === 3">
          <div v-bind:key="index" class='q-group'>
            <div class='q-item'>{{item.title}}</div>
            <template v-for='(item1, index1) in item.arr'>
              <div v-bind:key="item1.id" class="star-item">
                <div class="left-txt">{{item1.option}}</div>
                <template v-if="item1.star !== undefined">
                  <div class="right-stars">
                    <i :class="['icon', (item1.star >= 1 ? 'el-icon-self-star_full' : 'el-icon-self-wujiaoxing')]" @click="setStar(1, index1)" @mouseenter="hoverStar(1, index1)"></i>
                    <i :class="['icon', (item1.star >= 2 ? 'el-icon-self-star_full' : 'el-icon-self-wujiaoxing')]" @click="setStar(2, index1)" @mouseenter="hoverStar(2, index1)"></i>
                    <i :class="['icon', (item1.star >= 3 ? 'el-icon-self-star_full' : 'el-icon-self-wujiaoxing')]" @click="setStar(3, index1)" @mouseenter="hoverStar(3, index1)"></i>
                    <i :class="['icon', (item1.star >= 4 ? 'el-icon-self-star_full' : 'el-icon-self-wujiaoxing')]" @click="setStar(4, index1)" @mouseenter="hoverStar(4, index1)"></i>
                    <i :class="['icon', (item1.star === 5 ? 'el-icon-self-star_full' : 'el-icon-self-wujiaoxing')]" @click="setStar(5, index1)" @mouseenter="hoverStar(5, index1)"></i>
                  </div>
                </template>
              </div>
            </template>
            <div style="width: 100%; height: 20px;"></div>
            <el-input
              type="textarea"
              :rows="4"
              placeholder="还有哪些需要改进的方面"
              v-model="item.textarea">
            </el-input>
          </div>
        </template>
      </template>
      <div class="btns-fix">
        <div :class="['btn', this.curPage > 1 ? 'two c-btn' : 'none']" @click="prevPage">上一页</div>
        <template v-if="lastPage">
          <div :class="['btn', this.lastPage ? 'two' : '']" @click="goSubmit">提交</div>
        </template>
        <template v-else>
          <div :class="['btn', this.curPage > 1 ? 'two' : '']" @click="nextPage">下一页</div>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import qData from './store/data'
import cAction from '@actions'
import Base64 from 'Base64'
import _ from 'lodash'

export default {
  props: {
    sid: { type: String, require: false },
    cid: { type: String, require: false }
  },
  data () {
    let _headerInfo = JSON.parse(window.localStorage.getItem('headerInfo') || '{}')
    return {
      dataQuestion: _.assignIn({}, qData.question),
      headerInfo: _headerInfo,
      exam: {
        id: '',
        semester_id: '',
        title: '',
        score: '',
        work_contents: '',
        group: []
      },
      // 提交时，传入的参数值
      param: {
        semester_id: '',
        course_id: '',
        raw: '' // base64
      },
      count: 0,
      /* 进入页面记录初试时间 */
      startTime: '',
      setTime: null,
      /* 当前 radio点击 */
      radioCur: '',
      /* 当前 checkbox点击 */
      checkCur: '',
      /* 记录当前页 */
      curPage: 1,
      /* 记录 区分选择项 */
      selectId: '',
      /* 记录页数进度 */
      progress: '',
      /* 总共题目数 */
      total: 7,
      /* 最后一页 */
      lastPage: false
    }
  },
  mounted () {
    /* 读取本地缓存 */
    let quesLocal = window.localStorage.getItem('quesLocal' + this.sid + this.cid)
    let quesPage = window.localStorage.getItem('quesPage' + this.sid + this.cid)
    let quesSelectId = window.localStorage.getItem('quesSelectId' + this.sid + this.cid)
    if (quesLocal) {
      qData.question = JSON.parse(quesLocal)
      this.curPage = quesPage
      this.selectId = quesSelectId
    }

    this.loadQuestion()
  },
  destroyed () {
    qData.question = this.dataQuestion
  },
  methods: {
    /* 提交数据 */
    goSubmit () {
      const loading = this.$loading({ lock: true, text: '', spinner: '', background: 'rgba(255, 255, 255, 0.9)' })
      cAction.chapterAction.updateSurveyAnswer({
        semester_id: this.sid,
        course_id: this.cid,
        raw: Base64.encode(JSON.stringify(qData.question))
      }).then(res => {
        if (res.id) {
          this.$router.push({ path: `/result/${this.iphone}/${encodeURIComponent(this.email)}/${res.id}` })
        }
        /* 答题成功，清空本地缓存 */
        window.localStorage.removeItem('quesLocal' + this.sid + this.cid)
        window.localStorage.removeItem('quesPage' + this.sid + this.cid)
        window.localStorage.removeItem('quesSelectId' + this.sid + this.cid)
        loading.close()
      }).catch(e => {
        /* 答题 记录计入本地缓存 */
        window.localStorage.setItem('quesLocal' + this.sid + this.cid, JSON.stringify(qData.question))
        window.localStorage.setItem('quesPage' + this.sid + this.cid, this.curPage)
        window.localStorage.setItem('quesSelectId' + this.sid + this.cid, this.selectId)
        this.$message.error('提交失败，请稍后刷新重试')
        loading.close()
      })
    },
    /* 按照id编号规则 放入 exam.group中 */
    loadQuestion () {
      this.exam.group = []
      for (let i = 0; i < qData.question.length; i++) {
        let exp = new RegExp('$\\d+-' + this.curPage, 'gi')
        if (exp.test(qData.question[i].id)) {
          this.exam.group.push(qData.question[i])
          if (qData.question[i].submit) {
            this.lastPage = true
          } else {
            this.lastPage = false
          }
        }
      }
      this.progress = ((this.curPage - 1) / this.total * 100) + '%'
    },
    /* 点击下一页 */
    nextPage () {
      for (let i = 0; i < this.exam.group.length; i++) {
        if (!this.exam.group[i].flag) {
          this.$message.error('本页尚有题目未填写')
          return
        }
      }
      /* 做区分，需要特殊判断 */
      if (this.curPage === 4) {
        if (this.exam.group[0].arr[3].selected) {
          this.selectId = '4-4'
        } else {
          this.selectId = '4-1'
        }
      }
      this.curPage++
      this.loadQuestion()

      /* 答题 记录计入本地缓存 */
      window.localStorage.setItem('quesLocal' + this.sid + this.cid, JSON.stringify(qData.question))
      window.localStorage.setItem('quesPage' + this.sid + this.cid, this.curPage)
      window.localStorage.setItem('quesSelectId' + this.sid + this.cid, this.selectId)
    },
    /* 点击上一页 */
    prevPage () {
      this.curPage--
      if (this.curPage <= 4) {
        this.selectId = ''
      }
      this.loadQuestion()
    },
    /**
     * 辅助 radio选择
     */
    radioClick (e) {
      this.radioCur = e.currentTarget.dataset.index
    },
    /**
     * radio选择
     * PC端 值会 返回 选择的 值
     */
    radioChange (val) {
      let i = this.radioCur
      let arr = this.exam.group[i].arr
      let value = val
      for (let j = 0; j < arr.length; j++) {
        arr[j]['selected'] = 0
      }
      arr[value].selected = 1
      /* 记录 题目是否 已经选过 */
      this.exam.group[i].flag = true
    },
    /**
     * 辅助 checkbox选择
     */
    checkboxClick (e) {
      this.checkboxCur = e.currentTarget.dataset.index
    },
    /**
     * checkbox选择
     */
    checkboxChange (val) {
      let i = this.checkboxCur
      let arr = this.exam.group[i].arr
      let value = val
      for (let j = 0; j < arr.length; j++) {
        arr[j]['selected'] = 0
      }
      for (let j = 0; j < value.length; j++) {
        arr[value[j]].selected = 1
      }
      /* 记录 题目是否 已经选过 */
      if (!value.length) {
        this.exam.group[i].flag = false
      } else {
        this.exam.group[i].flag = true
      }
    },
    /* hover选中星星 */
    hoverStar (len, i) {

    },
    /* 点击选中星星 */
    setStar (len, i) {
      this.exam.group[0].arr[i].star = len
    }
  }
}
</script>

<style lang="scss" scoped>
@import './index.css';
.survey-container {
  display: block;
  max-width: 640px;
  height: 100%;
  margin: 0 auto;
  background: #ffffff;
  .header {
    font-size: 20px;
    text-align: center;
    padding: 20px;
    background: #ffffff;
    width: 100%;
    img {
      display: block;
      width: 100%;
    }
  }
  .progress {
    width: 100%;
    height: 6px;
    background: #b5b5b5;
    .cur-progress {
      display: block;
      height: 100%;
      background: #ebbb14;
    }
  }
  .exam-box {
    position: relative;
    padding: 20px 20px 70px 20px;
    background: #ffffff;
    overflow: hidden;
    /* 选择样式 */
    .q-group {
      padding: 0;
      font-size: 20px;
      color: #313131;
      overflow: hidden;
      .q-item {
        display: block;
        font-weight: 700;
        margin-bottom: 10px;
      }
      .star-item {
        line-height: 2;
        overflow: hidden;
        .left-txt {
          float: left;
          width: 58%;
          font-size: 18px;
          line-height: 40px;
        }
        .right-stars {
          float: right;
          .icon {
            font-size: 18px;
            cursor: pointer;
            &.el-icon-self-star_full {
              color: #a98c58;
            }
          }
        }
      }
    }
    .q-group:last-child {
      border-bottom: none;
    }
    .btns-fix {
      position: fixed;
      left: 0;
      bottom: 0;
      width: 100%;
      .btn {
        float: left;
        width: 100%;
        height: 50px;
        text-align: center;
        font-size: 18px;
        line-height: 50px;
        color: #eedfb1;
        background: #b01b3c;
        cursor: pointer;
        &.none {
          display: none;
        }
        &.two {
          width: 50%;
        }
        &.c-btn {
          background: #b5b5b5;
          color: #ffffff;
        }
      }
    }
  }
}
</style>
