<template>
  <div class="survey-container">
    <div class="header">
      <div class="title">清控紫荆课堂教学服务评估表</div>
      <div class="sub-title">您好！为保证我们能够为您提供更优质的课程，提高教学质量及服务，请您对此次课程提出宝贵的意见和建议。感谢您对我们工作的支持！（请您选择星级，选中1颗星为1分，最高5颗星）。请用1（低）到5（高）为每一项打分，并加上任何您想写的评论。</div>
      <!-- <img src="./logo-header.jpg" alt=""> -->
      <div class="sub-left">课程名称：{{headerInfo.title}}
        <!-- <div class="sub-right">授课人：{{}}</div> -->
      </div>
    </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 || item.type === 4">
          <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(index, 1, index1)" @mouseenter="hoverStar(index, 1, index1)"></i>
                    <i :class="['icon', (item1.star >= 2 ? 'el-icon-self-star_full' : 'el-icon-self-wujiaoxing')]" @click="setStar(index, 2, index1)" @mouseenter="hoverStar(index, 2, index1)"></i>
                    <i :class="['icon', (item1.star >= 3 ? 'el-icon-self-star_full' : 'el-icon-self-wujiaoxing')]" @click="setStar(index, 3, index1)" @mouseenter="hoverStar(index, 3, index1)"></i>
                    <i :class="['icon', (item1.star >= 4 ? 'el-icon-self-star_full' : 'el-icon-self-wujiaoxing')]" @click="setStar(index, 4, index1)" @mouseenter="hoverStar(index, 4, index1)"></i>
                    <i :class="['icon', (item1.star === 5 ? 'el-icon-self-star_full' : 'el-icon-self-wujiaoxing')]" @click="setStar(index, 5, index1)" @mouseenter="hoverStar(index, 5, index1)"></i>
                  </div>
                </template>
              </div>
            </template>
            <div style="width: 100%; height: 20px;"></div>
            <template v-if='item.area !== undefined'>
              <el-input
                type="textarea"
                :rows="4"
                placeholder="还有哪些需要改进的方面"
                v-model="item.area" @blur="leaveSave">
              </el-input>
            </template>
          </div>
        </template>
      </template>
      <div class="bottom">如果您在清控紫荆课堂的收获比较大，我们会非常感谢您帮助我们推荐和您一样优秀的学员加入到清控紫荆课堂的大家庭，具体请联系您所在班的班主任。</div>
      <div :class="['btn', this.curPage > 1 ? '' : 'none']" @click="prevPage">上一页</div>
      <template v-if="lastPage">
        <div class="btn" @click="goSubmit">提交</div>
      </template>
      <template v-else>
        <div class="btn" @click="nextPage">下一页</div>
      </template>
    </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: _.cloneDeep(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 () {
      for (let i = 0; i < qData.question.length; i++) {
        let _item = qData.question[i]
        if (_item.type === 3) {
          for (let j = 0; j < _item.arr.length; j++) {
            if (_item.arr[j].star === 0) {
              this.$message.error('尚有内容未填写，请填写完整每一项')
              return
            }
          }
        }
        if (_item.type === 4) {
          if (_item.area === '') {
            this.$message.error('尚有内容未填写，请填写完整每一项')
            return
          }
        }
      }
      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 => {
        let a = 1
        if (a) {
          this.$message.success('感谢你的宝贵意见。')
          /* 答题成功，清空本地缓存 */
          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()
          setTimeout(() => {
            this.$router.push({ path: `/app/my-learn/course-detail/${this.cid}` })
          }, 2000)
        }
      }).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
        }
      }
      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--
      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 (index, len, i) {

    },
    /* 点击选中星星 */
    setStar (index, len, i) {
      this.exam.group[index].arr[i].star = len
      /* 答题 记录计入本地缓存 */
      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)
    },
    /* 内容离开保存 */
    leaveSave () {
      /* 答题 记录计入本地缓存 */
      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)
    }
  }
}
</script>

<style lang="scss" scoped>
@import './index.css';
.survey-container {
  display: block;
  max-width: 900px;
  margin: 0 auto;
  .bottom {
    float: left;
    margin-top: 20px;
    font-size: 20px;
    text-align: justify;
  }
  .header {
    padding: 20px;
    background: #ffffff;
    .title {
      font-size: 30px;
      text-align: center;
      margin-bottom: 10px;
    }
    .sub-title {
      padding: 0 30px;
      text-indent: 40px;
      font-size: 16px;
      text-align: justify;
      margin-bottom: 20px;
    }
    .sub-left {
      font-size: 20px;
      padding-left: 30px;
      .sub-right {
        float: right;
      }
    }
    width: 100%;
    img {
      display: block;
      width: 100%;
    }
  }
  .progress {
    width: 100%;
    height: 6px;
    background: #b5b5b5;
    .cur-progress {
      display: block;
      height: 100%;
      background: #ebbb14;
    }
  }
  .exam-box {
    padding: 55px 8.7% 100px 8.7%;
    background: #ffffff;
    overflow: hidden;
    /* 选择样式 */
    .q-group {
      padding: 20px 0 10px 0;
      font-size: 20px;
      color: #313131;
      border-bottom: 1px dashed #dcdcdc;
      overflow: hidden;
      .q-item {
        display: block;
        font-weight: 700;
        margin-bottom: 10px;
      }
      .star-item {
        line-height: 2;
        overflow: hidden;
        .left-txt {
          float: left;
          width: 70%;
        }
        .right-stars {
          float: right;
          .icon {
            font-size: 24px;
            cursor: pointer;
            &.el-icon-self-star_full {
              color: #a98c58;
            }
          }
        }
      }
    }
    .q-group:last-child {
      border-bottom: none;
    }
    .btn {
      float: left;
      width: 150px;
      height: 42px;
      margin-top: 50px;
      margin-right: 25px;
      text-align: center;
      font-size: 18px;
      line-height: 42px;
      color: #eedfb1;
      background: #b01b3c;
      border-radius: 6px;
      cursor: pointer;
      &.none {
        display: none;
      }
    }
  }
}
</style>
