<template>
  <div class="paper-container">
    <div class="ev-header">
      <Icon type="md-paper" size="30" color="rgb(16, 171, 231)" />
      <span class="ev-title" @click="backToAdd">测试组卷</span>
      <span class="ev-length">共 {{paperInfo.ItemId.length}} 道题</span>
    </div>
    <!-- 试卷编辑工具栏 -->
    <div class="paper-toolbar filter-wrap">

      <div class="filter-item">
        <span class="filter-title">测试用途:</span>
        <RadioGroup v-model="testAttr.testType" type="button" @on-change="filterTypeChange">
          <Radio label="0">正式考试</Radio>
          <Radio label="1">普通测试</Radio>
          <Radio label="2">统计</Radio>
        </RadioGroup>
      </div>
      <div class="filter-item">
        <span class="filter-title">测试情景:</span>
        <RadioGroup v-model="testAttr.testScene" type="button" @on-change="filterSceneChange">
          <Radio label="0">模拟</Radio>
          <Radio label="1">段考</Radio>
          <Radio label="2">周考</Radio>
          <Radio label="3">小考</Radio>
          <Radio label="4">自定义</Radio>
        </RadioGroup>
      </div>
      <!--<div class="filter-item">
        <span class="filter-title">测试对象:</span>
        <RadioGroup v-model="testAttr.testTarget" type="button" @on-change="filterTargetChange">
          <Radio label="0">同年级</Radio>
          <Radio label="1">跨年级</Radio>
          <Radio label="2">跨学校</Radio>
        </RadioGroup>
      </div>-->
      <!--<div class="filter-item">
        <span class="filter-title">创建方式:</span>
        <RadioGroup v-model="testAttr.createType" type="button" @on-change="filterCreateChange">
          <Radio label="0">自动组题</Radio>
          <Radio label="1">批量导入</Radio>
          <Radio label="2">题库挑选</Radio>
        </RadioGroup>
      </div>-->
      <div class="paper-tools">
        <span class="paper-tools-title">选择展示:</span>
        <Checkbox v-model="isShowAnswer">答案与解析</Checkbox>
        <Checkbox v-model="isShowConcept">关联知识点</Checkbox>
        <Checkbox v-model="isShowTitle">评测标题</Checkbox>
        <Checkbox v-model="isShowInfo">评测信息</Checkbox>
        <Checkbox v-model="isShowPart">题块</Checkbox>
      </div>
    </div>

    <!-- 试卷内容 -->
    <div class="paper-content">
      <!--<div class="paper-line">
        <div id="pui_seal" title="点击设置&quot;装订线&quot;" style="display: block;">
          <img alt="装订线" title="装订线" src="http://zujuan.xkw.com/resource/image/v2/peal_line.png" width="58" height="">
        </div>
      </div>-->
      <div class="paper-body">
        <!-- 试卷头部信息 -->
        <div class="paper-header flex-col-center">
          <Tooltip content="点击可编辑修改主标题" placement="right">
            <p class="paper-title" v-show="isShowTitle" contenteditable="true" @blur="titleChange($event)">{{paperInfo.title}}</p>
          </Tooltip>
          <Tooltip content="点击可编辑修改副标题" placement="right">
            <p class="paper-subTitle" v-show="isShowInfo" contenteditable="true" @blur="subTitleChange($event)">{{paperInfo.subTitle}}</p>
          </Tooltip>
            <p class="paper-info" v-show="isShowInfo">考试时间：<span contenteditable="true" @blur="timeChange($event)">{{paperInfo.time}}</span> 出卷人：{{paperInfo.builder}}</p>
        </div>
        <!-- 题目类型及列表 -->
        <div class="paper-part" v-for="(item,order) in paperInfo.parts">
          <div class="paper-content-section" v-show="isShowPart">{{numberConvertToUppercase(order)+'、'+item.name}}<span>(共6题，每题5分，共30分)</span></div>
          <div v-if="list.length == 0">暂无数据</div>
          <div class="content-wrap" v-else>
            <div class="exercise-item" v-for="(question,index) of item.questions" @mouseenter="exerciseMouseover($event)" @mouseleave="exerciseMouseleave($event)">
              <div class="item-tools">
                <div class="item-tools-t flex-row-center"><Icon type="ios-list-box-outline" />试题挑错</div>
                <div class="item-tools-t flex-row-center" @click="handleBindPoint([])"><Icon type="ios-list-box-outline" />绑定知识点</div>
                <div class="item-tools-t flex-row-center" @click="handleToolEdit(question)"><Icon type="ios-brush-outline" />编辑</div>
                <div class="item-tools-t flex-row-center"><Icon type="ios-archive-outline" />删除</div>
                <div class="item-tools-t flex-row-center" v-show="index != 0" @click="handleMoveUp(item.questions,index)"><Icon type="md-arrow-up" />上移</div>
                <div class="item-tools-t flex-row-center" v-show="index != (item.questions.length - 1)" @click="handleMoveDown(item.questions,index)"><Icon type="md-arrow-down" />下移</div>
              </div>
              <div class="item-question">
                <p>{{index+1}} : <span v-html="question.question"></span></p>
              </div>
              <div v-for="(option,optionIndex) in question.option">
                <p>{{String.fromCharCode(64 + parseInt(optionIndex+1))}} : <span v-html="option.value"></span></p>
              </div>

              <!-- 如果是组合题 -->
              <div v-for="(childQuestion,childIndex) in question.children" v-if="question.children.length">
                <div class="item-question">
                  <p>{{childIndex+1}} : <span v-html="childQuestion.question"></span></p>
                </div>
                <div v-for="(childOption,childOptionIndex) in childQuestion.option">
                  <p>{{String.fromCharCode(64 + parseInt(childOptionIndex+1))}} : <span v-html="childOption.value"></span></p>
                </div>
                <div class="item-answer" v-show="isShowAnswer">
                  <span style="color:#01b4ef">【知识点】:</span>
                </div>
                <div class="item-answer" v-show="isShowAnswer">
                  <span style="color:#01b4ef">【答案】:</span>
                  <span v-html="childQuestion.answer[0] || childQuestion.answer" v-if="childQuestion.type == 'Subjective'"></span>
                  <span :class="[ childQuestion.type == 'Complete' ? 'item-answer-item':'']" v-for="answer in childQuestion.answer" v-else-if="childQuestion.type == 'Complete'" v-html="answer"></span>
                  <span :class="[ childQuestion.type == 'Complete' ? 'item-answer-item':'']" v-for="answer in childQuestion.answer" v-else>{{answer}}</span>
                </div>
                <div class="item-explain" v-show="isShowAnswer">
                  <span style="color:#01b4ef">【解析】:</span>
                  <span v-html="childQuestion.explain"></span>
                </div>
              </div>


              <!-- 答案与解析部分选择是否展示 -->
              <div class="item-concept" v-show="isShowConcept">
                <span style="color:#01b4ef">【知识点】:</span>
              </div>
              <div class="item-answer" v-show="isShowAnswer && question.type != 'Compose'">
                <span style="color:#01b4ef">【答案】:</span>
                <span v-html="question.answer[0] || question.answer" v-if="question.type == 'Subjective'"></span>
                <span :class="[ question.type == 'Complete' ? 'item-answer-item':'']" v-for="answer in question.answer" v-else-if="question.type == 'Complete'" v-html="answer"></span>
                <span :class="[ question.type == 'Complete' ? 'item-answer-item':'']" v-for="answer in question.answer" v-else>{{answer}}</span>
              </div>
              <div class="item-explain" v-show="isShowAnswer && question.type != 'Compose'">
                <span style="color:#01b4ef">【解析】:</span>
                <span v-html="question.explain"></span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="paper-footer">
      <Button type="primary">保存试卷</Button>
    </div>
    <!-- 绑定知识点弹窗开始 -->
    <Modal v-model="bindPointModal"
           title="绑定知识点"
           width="500"
           class-name="paperTransferModal"
           @on-ok="handleTransferBlock"
           @on-cancel="">
      <div class="point-list">
        <p class="bind-title">选择知识点</p>
        <Input search placeholder="搜索知识点..." v-model="searchWord" @on-change="filterChange" />
        <Tabs v-model="tabSelectVal">
          <TabPane label="校本知识点" name="school">
            <Tree :data="knowPointList" ref="pointTree" :render="renderContent" check-strictly></Tree>
          </TabPane>
          <TabPane label="标准知识点" name="all">
            <Tree :data="allPointList" ref="pointTree" :render="renderContent" check-strictly></Tree>
          </TabPane>
        </Tabs>
        <Spin fix v-show="pointListLoading"></Spin>
      </div>
      <div class="selected-point-list">
        <p class="bind-title">已选知识点<span style="font-weight:500;font-size:12px"> (最多绑定5个知识点,颜色代表不同来源)</span><span class="btn-clear" @click="handleClearChecked">清空</span></p>
        <span class="checked-point" :style="{background:item.origin=='school'?'#10abe7':'#12b9ab'}" v-for="item in checkedPointList">{{item.name}}<Icon type="md-close" color="#fff" style="margin-left:5px;cursor:pointer" @click="deleteCheckedPoint(item)" /></span>
      </div>
    </Modal>
    <!-- 绑定知识点弹窗结束 -->
  </div>
</template>
<script>

  import questions from './list.json'
  import paper from './paper.json'
  export default {
    data() {
      return {
        list: [],
        schoolInfo: {},
        paperInfo: {},
        exersicesType: {
          single: "单选",
          multiple: "多选",
          judge: "判断",
          complete: "填空",
          subjective: "问答"
        },
        testAttr: {
          testScene: '0',
          testType: '0',
          testTarget: '0',
          testMode: '0',
          createType: '0',
          questionFilter: []
        },
        exersicesDiff: ["容易", "较易", "一般", "较难", "困难"],
        diffColors: ['#32CF74', '#E8BE15', '#F19300', '#EB5E00', '#D30000'],
        filterType: "0",
        filterDiff: "0",
        filterSort: "0",
        pageSize: 5,
        pageNum: 1,
        totalNum: 100,
        allList: questions.result.data,
        isShowAnswer: false,
        isShowPart: false,
        isShowConcept: false,
        isShowTitle: true,
        isShowInfo:false,
        bindPointModal: false,
        knowPointList: [],
        schoolPointList: [],
        allPointList: [],
        checkedPointList: [],
        searchWord: '',
        pointListLoading: true,
        tabSelectVal: "school"
      }
    },
    created() {
      this.schoolInfo = JSON.parse(localStorage.getItem('c_role_info')).roleClaim[0];
      this.list = questions.result.data;
      this.paperInfo = paper;
      let flag = this.$route.params.flag;
      if (flag == 1) {
        console.log(JSON.parse(localStorage.getItem('questions')));
        this.paperInfo.parts[0].questions = JSON.parse(localStorage.getItem('questions'))
      }

    },
    methods: {

      titleChange(e) {
        this.paperInfo.title = e.target.innerHTML
      },

      subTitleChange(e) {
        this.paperInfo.subTitle = e.target.innerHTML
      },
  
      timeChange(e) {
        this.paperInfo.time = e.target.innerHTML
      },

      //返回创建评测页面
      backToAdd() {
        this.$router.push({
          path: '/testPaperList',//或者路径跳转path: '/addCreditCards',
        })
      },

      //数字与中文转换
      numberConvertToUppercase(num) {
        num = Number(num + 1);
        var upperCaseNumber = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '百', '千', '万', '亿'];
        var length = String(num).length;
        if (length == 1) {
          return upperCaseNumber[num];
        } else if (length == 2) {
          if (num == 10) {
            return upperCaseNumber[num];
          } else if (num > 10 && num < 20) {
            return '十' + upperCaseNumber[String(num).charAt(1)];
          } else {
            return upperCaseNumber[String(num).charAt(0)] + '十' + upperCaseNumber[String(num).charAt(1)].replace('零', '');
          }
        }
      },

      //切换页码
      pageChange(page) {
        let start = this.pageSize * (page - 1);
        let end = this.pageSize * page;
        let list = questions.result.data;
        this.list = list.slice(start, end);
        window.scroll(0, 0);
      },

      //切换分页Size
      pageSizeChange(val) {
        this.pageSize = val;
        this.pageChange(1);
      },

      //题目鼠标滑过事件
      exerciseMouseover(e) {
        e.preventDefault();
        e.target.children[0].style.display = "block";
      },

      //题目鼠标移出事件
      exerciseMouseleave(e) {
        e.preventDefault();
        e.target.children[0].style.display = "none";
      },

      //测试用途
      filterTypeChange(val) {

      },

      //测试情景
      filterSceneChange(val) {

      },

      //测试对象
      filterTargetChange(val) {

      },

      //创建方式
      filterCreateChange(val) {

      },

      handleToolEdit(item) {
        item.options = item.option;
        item.difficulty = item.difficulty || 2;
        this.$router.push({
          name: item.type == 'Compose' ? 'createCompose':'createExercises',
          params: {
            item: item,
          }
        })
      },

      //确认编辑知识块
      handleTransferBlock() {

      },

      //绑定知识点操作
      handleBindPoint(concepts) {
        this.bindPointModal = true;
        //this.checkedPointList = concepts;
        this.checkedPointList = [];
        this.knowPointList = this.schoolPointList;
        console.log(concepts);
      },

      //获取标准知识块数据
      getStandardList() {
        let data = {
          periods: ["Period_21"],
          pointParams: {
            SubjectCode: "Subject_Chinese",
            PartitionKey: "zh-CN",
          }
        }
        this.$api.FindKnowledgeBlockAndPointByDict(data).then(res => {
          let list = res.result.data;
          this.allPointList = list;
        })
      },

      //获取学校知识块仓库数据
      getSchoolPoints() {
        let data = {
          pointParams: {
            SubjectCode: "Subject_Chinese",
            PartitionKey: "zh-CN",
            SchoolCode: this.schoolInfo.claim[0].claimCode,
            Status: 1
          }
        }
        this.$api.FindSchoolBlockAndPointByDict(data).then(res => {
          let list = res.result.data;
          list.forEach(item => {
            item.expand = !item.expand;
          })
          this.schoolPointList = list;
          this.pointListLoading = false;
        })
      },

      //知识点树形结构渲染
      renderContent(h, { root, node, data }) {
        return h(
          "span",
          {
            domProps: {
              className: "singleClass"
            },
            on: {
              click: () => {
                this.titleClick(root, node, data, event);
              }
            }
          }, [
            h("span", [
              h("Icon", {
                props: {
                  type:
                    data.children && data.children.length > 0
                      ? "md-albums"
                      : "ios-paper-outline"
                },
                style: {
                  marginRight: "5px",
                }
              }),
              h("span", data.name),
              h('span', {
                domProps: {
                  className: this.checkedPointList.map(item => item.knowledgeId).indexOf(data.knowledgeId || data.rowKey) > -1 ? "point-checkbox point-checked" : "point-checkbox point-unchecked"
                },
                style: {
                  display: data.children && data.children.length > 0
                    ? "none"
                    : "inline-block"
                },
                on: {
                  click: () => {
                    let conceptData = {};
                    if (this.checkedPointList.map(item => item.knowledgeId).indexOf(data.knowledgeId || data.rowKey) == -1) {
                      if (this.checkedPointList.length < 5) {
                        conceptData.origin = this.tabSelectVal;
                        conceptData.knowledgeId = data.knowledgeId || data.rowKey;
                        conceptData.name = data.name;
                        conceptData.subjectCode = data.subjectCode;
                        this.checkedPointList.push(conceptData);
                      } else {
                        this.$Message.warning("最多绑定5个知识点！");
                      }
                    } else {
                      this.checkedPointList.splice(this.checkedPointList.map(item => item.knowledgeId).indexOf(data.knowledgeId || data.rowKey), 1);
                    }

                    console.log(this.checkedPointList);
                  }
                }
              })
            ])
          ]
        );
      },
      //标题点击收缩展开
      titleClick(root, node, data, event) {
        data.expand = !data.expand;
      },

      //清空已选知识点
      handleClearChecked() {
        this.checkedPointList = [];
      },

      //删除指定知识点
      deleteCheckedPoint(item) {
        this.checkedPointList.splice(this.checkedPointList.indexOf(item), 1);
      },

      //知识点筛选功能
      filterChange() {
        this.knowPointList = !this.searchWord ? this.schoolPointList : this.schoolPointList.filter(item => item.name.toUpperCase().indexOf(this.searchWord.toUpperCase()) > -1)
      },

      //子题顺序操作
      moveItems(arr, index1, index2) {
        arr[index1] = arr.splice(index2, 1, arr[index1])[0];
        return arr;
      },

      //子题上移操作
      handleMoveUp(arr,index) {
        this.moveItems(arr, index, index - 1);
      },

      //子题下移操作
      handleMoveDown(arr,index) {
        this.moveItems(arr, index, index + 1);
      }


    },
    mounted() {
      this.getStandardList();
      this.getSchoolPoints();
    }
  }
</script>
<!--<style src="../index/TestPaper.css" scoped></style>-->
<style src="../index/ExercisesList.css" scoped></style>

<style src="../index/TestPaper.css" scoped>
  /*@import "../index/TestPaper.css";*/
</style>
<style>

  .content-wrap .exercise-item p {
    margin: 10px 0;
    display: inherit;
    word-break: break-all;
  }

  .complete-line {
    padding: 0 45px;
    border-bottom: 2px solid rgb(128, 128, 128);
  }
</style>
