<template>
  <div class="ev-list-container">

    <div class="ev-header">
      <Icon type="md-bookmarks" size="30" color="rgb(16, 171, 231)" />
      <span class="ev-title">题库列表</span>
      <span class="ev-length">共 {{list.length}} 道题</span>
    </div>
    <!-- 筛选部分 -->
    <div class="filter-wrap">
      <div class="filter-item">
        <span class="filter-title">来源:</span>
        <RadioGroup v-model="filterOrigin" type="button" @on-change="filterOriginChange">
          <Radio label="self">个人私有库</Radio>
          <Radio label="school">学校公用库</Radio>
          <Radio label="system">系统公用库</Radio>
        </RadioGroup>
      </div>
      <div class="filter-item">
        <span class="filter-title">题型:</span>
        <RadioGroup v-model="filterType" type="button" @on-change="filterTypeChange">
          <Radio label="all">全部</Radio>
          <Radio label="Single">单选</Radio>
          <Radio label="Multiple">多选</Radio>
          <Radio label="Judge">判断</Radio>
          <Radio label="Complete">填空</Radio>
          <Radio label="Subjective">问答</Radio>
        </RadioGroup>
      </div>
      <div class="filter-item">
        <span class="filter-title">难度:</span>
        <RadioGroup v-model="filterDiff" type="button" @on-change="filterDiffChange">
          <Radio label="all">全部</Radio>
          <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="filterSort" type="button" @on-change="filterSortChange">
          <Radio label="0">新增时间<Icon type="md-arrow-round-down" /></Radio>
          <Radio label="1">使用次数<Icon type="md-arrow-round-down" /></Radio>
        </RadioGroup>
      </div>
    </div>
    <div class="ev-list-operation">
      <Checkbox v-model="isShowAnswer">展示答案与解析</Checkbox>
      <span class="import-exercise">
        <Upload multiple action="api/ImportExercise/uploadWord" :headers="headers" :show-upload-list="isShowUploadList" :on-success="uploadSuccess">
          <Button type="info">导入习题</Button>
        </Upload>
      </span>
      <div class="operation-cart" id="questionCart">
        <Poptip trigger="click" title="我的试题篮" placement="top">
          <Badge :count="basketCount" show-zero type="success">
            <img src="../../../assets/icon/icon_cart.png" />
          </Badge>
          <div class="basket-content" slot="content">
            <p class="basket-title">共计 {{basketCount}} 道题</p>
            <div class="basket-body">
              <div class="basket-item">
                <span>单选题</span>
                <Progress :percent="basketList.all.length ? Number((basketList.Single.length / basketList.all.length)*100) : 0" stroke-color="rgb(16, 171, 231)" hide-info />
                <span style="margin-left:10px">{{ basketList.Single.length }} 道 <span class="basket-delete" @click="handleBasketDelete('Single')">删除</span></span>
              </div>
              <div class="basket-item">
                <span>多选题</span>
                <Progress :percent="basketList.all.length ? Number((basketList.Multiple.length / basketList.all.length)*100) : 0" stroke-color="rgb(16, 171, 231)" hide-info />
                <span style="margin-left:10px">{{ basketList.Multiple.length}} 道 <span class="basket-delete" @click="handleBasketDelete('Multiple')">删除</span></span>
              </div>
              <div class="basket-item">
                <span>判断题</span>
                <Progress :percent="basketList.all.length ? Number((basketList.Judge.length / basketList.all.length)*100) : 0" stroke-color="rgb(16, 171, 231)" hide-info />
                <span style="margin-left:10px">{{ basketList.Judge.length}} 道 <span class="basket-delete" @click="handleBasketDelete('Judge')">删除</span></span>
              </div>
              <div class="basket-item">
                <span>填空题</span>
                <Progress :percent="basketList.all.length ? Number((basketList.Complete.length / basketList.all.length)*100) : 0" stroke-color="rgb(16, 171, 231)" hide-info />
                <span style="margin-left:10px">{{ basketList.Complete.length}} 道 <span class="basket-delete" @click="handleBasketDelete('Complete')">删除</span></span>
              </div>
              <div class="basket-item">
                <span>问答题</span>
                <Progress :percent="basketList.all.length ? Number((basketList.Subjective.length / basketList.all.length)*100) : 0" stroke-color="rgb(16, 171, 231)" hide-info />
                <span style="margin-left:10px">{{ basketList.Subjective.length}} 道 <span class="basket-delete" @click="handleBasketDelete('Subjective')">删除</span></span>
              </div>
              <div class="basket-item">
                <span>综合题</span>
                <Progress :percent="basketList.all.length ? Number((basketList.Compose.length / basketList.all.length)*100) : 0" stroke-color="rgb(16, 171, 231)" hide-info />
                <span style="margin-left:10px">{{ basketList.Compose.length}} 道 <span class="basket-delete" @click="handleBasketDelete('Compose')">删除</span></span>
              </div>
            </div>
            <div :class="[basketList.all.length ? 'basket-footer' : 'basket-footer-no']">
              <p @click="handleSubmitPaper">进入组卷中心</p>
            </div>
          </div>
        </Poptip>
      </div>
    </div>
    <!-- 筛选部分结束 -->


    <!-- 题目列表部分 -->
    <div v-if="list.length == 0" class="no-data-text">
      <img src="../../../assets/icon/no_data.svg" width="120"/>
      <span style="margin-top:15px;color:#808080">暂无数据</span>
    </div>
    <div class="content-wrap" v-else>
      <Loading v-show="importLoading"></Loading>

      <div class="exercise-item" v-for="(item,index) of list">
        <!-- 题目难度类型以及绑定知识点 -->
        <div class="item-types">
          <span class="item-difficulty" :style="{backgroundColor:diffColors[item.difficulty || 3]}">{{exersicesDiff[item.difficulty || 3]}}</span>
          <span class="item-type">{{exersicesType[item.type]}}</span>
          <span class="item-relevant-points">
            <span class="item-tools-bind">
              <span class="item-tools-tool">
                <span class="item-bind-point">已关联知识点:</span>
                <span class="item-bind-point" v-for="concept in item.concept" v-show="item.concept"><Tag color="success">{{concept.name}}</Tag></span>
                <span class="item-bind-point"  v-show="!item.concept">暂未关联</span>
                <Icon type="md-link" size="20" />
                <span @click="handleBindPoint(item.concept || [])">绑定知识点</span>
              </span>
            </span>
          </span>
        </div>
        <!-- 题干部分 --> 
        <div class="item-question">
          <p>{{index+1}} : <span v-html="item.question"></span></p>
        </div>
        <!-- 选项部分 -->
        <div v-for="(option,optionIndex) in item.option">
          <p>{{String.fromCharCode(64 + parseInt(optionIndex+1))}} : <span v-html="option.value"></span></p>
        </div>

        <!-- 如果是组合题 -->
        <div v-for="(childQuestion,childIndex) in item.children" v-if="item.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>
            <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-answer" v-show="item.type != 'Compose'">
          <span class="answer-title-line"></span>
          <span class="answer-title" @click="showAnswer($event,'answer')">答案：点击展开答案详情</span>
          <div class="item-answer-details">
            <span v-html="item.answer" v-if="item.type == 'Subjective'"></span>
            <span :class="[ item.type == 'Complete' ? 'item-answer-item':'']" v-for="answer in item.answer" v-else-if="item.type == 'Complete'" v-html="answer"></span>
            <span :class="[ item.type == 'Complete' ? 'item-answer-item':'']" v-for="answer in item.answer" v-else>{{answer}}</span>
          </div>
        </div>
        <!-- 解析部分 -->
        <div class="item-explain" v-show="item.type != 'Compose'">
          <span class="explain-title-line"></span>
          <span class="explain-title" @click="showAnswer($event,'explain')">解析：点击展开解析详情</span>
          <div class="item-explain-details">
            <span v-html="item.explain"></span>
          </div>
        </div>
        <!-- 底部题目操作栏 -->
        <div class="item-tools">
          <span class="item-tools-info">来源：浙江省温州市2019年中考数学试卷</span>
          <span class="item-tools-info">使用次数：98 次</span>
          <span class="item-tools-info" style="border:0">更新时间：2019-07-01</span>
          <Button type="info" :style="{backgroundColor:basketList.all.indexOf(item) > -1 ? '#bbbbbb' : ''}" @click="handleChoose(item)">{{basketList.all.indexOf(item) > -1 ? '已选入' : '选题'}} </Button>
          <Button type="primary" @click="handleEdit(item)" style="margin-right:10px">编辑题目</Button>
          <!--小球-->
          <div>
            <transition name="drop" @before-enter="beforeDrop" @enter="dropping" @after-enter="afterDrop">
              <div class="ball" v-show="ball.show">
                <div class="inner inner-hook">
                  <img src="../../../assets/icon/icon_paper.png" />
                </div>
              </div>
            </transition>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部分页区域 -->
    <Page :total="totalNum"
          show-sizer
          @on-page-size-change="pageSizeChange"
          @on-change="pageChange"
          :page-size-opts="[5,10,15,20]" />
    <Button type="success" @click="backToAdd" style="margin:10px;">返回</Button>
    <Button type="success" @click="backToPaper" style="margin:10px;">试卷</Button>

    <!-- 绑定知识点弹窗开始 -->
    <Modal v-model="bindPointModal"
           title="绑定知识点"
           width="500"
           class-name="transferModal"
           @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 IconText from '@/components/evaluation/IconText.vue'
  import Loading from '@/common/Loading.vue'
  import questions from './list.json'
import { setTimeout } from 'core-js';
  export default {
    components: {
      IconText,
      Loading
    },
    data() {
      return {
        list: [],
        flag:false,
        searchWord: '',
        basketCount: 0,
        basketList: {
          all:[],
          Single: [],
          Multiple: [],
          Judge: [],
          Complete: [],
          Subjective: [],
          Compose:[]
        },
        pointListLoading: true,
        isShowUploadList:false,
        schoolInfo: {},
        bindPointModal: false,
        exersicesType: {
          Single: "单选",
          Multiple: "多选",
          Judge: "判断",
          Complete: "填空",
          Subjective:"问答",
          Compose:"综合题"
        },
        exersicesDiff: ["容易", "较易", "一般", "较难", "困难"],
        diffColors: ['#32CF74', '#E8BE15', '#F19300', '#EB5E00', '#D30000'],
        filterType: "all",
        filterOrigin:"self",
        filterDiff:"all",
        filterSort: "0",
        pageSize: 5,
        pageNum: 1,
        totalNum: 100,
        allList: questions.result.data,
        knowPointList: [],
        schoolPointList: [],
        allPointList:[],
        checkedPointList: [],
        isShowAnswer: true,
        importLoading:false,
        tabSelectVal: "school",
				ball:{ show: false },
				dropBalls: [],
      }
    },
    created() {
      this.schoolInfo = JSON.parse(localStorage.getItem('c_role_info')).roleClaim[0];
      this.list = questions.result.data;
      this.totalNum = questions.result.data.length;
      if (this.$route.params.exerciseItem) {
        this.list.unshift(this.$route.params.exerciseItem);
      }
    },
    methods: {

			drop(el) { //抛物
				this.ball.show = true;
				this.ball.el = el;
				this.dropBalls.push(this.ball);
				return;
			},
			beforeDrop(el) { /* 购物车小球动画实现 */
					let ball = this.ball;
          if (ball.show) {
						let rect = ball.el.getBoundingClientRect(); //元素相对于视口的位置
						let x = -(window.innerWidth - rect.x - 152);
						let y = -(window.innerHeight - rect.top - 22); //获取y
						el.style.display = '';
						el.style.webkitTransform = 'translateY(' + y + 'px)'; //translateY
						el.style.transform = 'translateY(' + y + 'px)';
						let inner = el.getElementsByClassName('inner-hook')[0];
						inner.style.webkitTransform = 'translateX(' + x + 'px)';
						inner.style.transform = 'translateX(' + x + 'px)';
				}
			},
			dropping(el, done) { /*重置小球数量  样式重置*/
				let rf = el.offsetHeight;
				el.style.webkitTransform = 'translate3d(0,0,0)';
				el.style.transform = 'translate3d(0,0,0)';
				let inner = el.getElementsByClassName('inner-hook')[0];
				inner.style.webkitTransform = 'translate3d(0,0,0)';
				inner.style.transform = 'translate3d(0,0,0)';
        el.addEventListener('transitionend', done);
        let cartClassList = document.getElementById('questionCart').classList;
          cartClassList.add('animated');
          cartClassList.add('heartBeat');
			},
			afterDrop(el) { /*初始化小球*/
				let ball = this.dropBalls.shift();
				if(ball) {
					ball.show = false;
          el.style.display = 'none';
          let cartClassList = document.getElementById('questionCart').classList;
            cartClassList.remove('animated');
            cartClassList.remove('heartBeat');
				  }
					},

      //根据题库加载题目
      filterOriginChange(origin) {
        console.log(origin);
      },

      //筛选题型
      filterTypeChange(val) {
        if (val == "all") {
          this.list = questions.result.data;
        } else {
          this.list = questions.result.data.filter(item => item.type == val);
        }
      },

      //筛选难度
      filterDiffChange(val) {
         if (val == "all") {
          this.list = questions.result.data;
         } else {
           this.list = questions.result.data.filter(item => item.difficulty == val);
        }
      },

      //排序条件更换
      filterSortChange(val) {
        console.log(val);
      },

      //展开与收起答案
      showAnswer(e, type) {
        let el = e.currentTarget;
        let isShow = e.currentTarget.nextElementSibling.style.display||"none";
        setTimeout(function () {
          if (type == "explain") {
            el.nextElementSibling.style.display = isShow == "none" ? "block" : "none";
            el.innerHTML = isShow == "none" ? "解析：点击收起解析详情" : "解析：点击展开解析详情";
          } else {
            el.nextElementSibling.style.display = isShow == "none" ? "block" : "none";
            el.innerHTML = isShow == "none" ? "答案：点击收起答案详情" : "答案：点击展开答案详情";
          }

        },100)
      },

      backToAdd() {
        this.$router.push({
            path: '/createExercises',//或者路径跳转path: '/addCreditCards',
          })
      },

      backToPaper() {
        this.$router.push({
            path: '/testPaper',//或者路径跳转path: '/addCreditCards',
          })
      },

      //切换页码
      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);
      },

      //编辑习题
      handleEdit(item) {
        item.options = item.option;
        item.difficulty = item.difficulty || 2;
        this.$router.push({
            name: 'createExercises',
            params:{
              item: item,
            }
          })
      },

      //选题
      handleChoose(item) {
        let that = this;
        if (this.basketList.all.indexOf(item) > -1) {
          this.$Message.warning("该试题已存在试卷篮！");
        } else {
          this.drop(event.target);
          let cartClassList = document.getElementById('questionCart').classList;
          this.basketList[item.type].push(item);
          this.basketList.all.push(item);
          setTimeout(function () {
            that.basketCount += 1;
          }, 400);
        }
      },


      //从试题篮删除题型
      handleBasketDelete(type) {
        let arr = JSON.parse(JSON.stringify(this.basketList.all))
        this.$Modal.confirm({
          title: '删除题型',
          content: '<p>确认删除该题型吗？</p>',
          okText:"确认",
          cancelText:"取消",
          onOk: () => {
            for (let i = 0; i < arr.length; i++) {
              let shaCodeArr = this.basketList.all.map(item => item.shaCode);
              let index = shaCodeArr.indexOf(arr[i].shaCode);
              if (arr[i].type == type && index > -1) {
                this.basketList.all.splice(index, 1);
              }
            }
            this.basketList[type] = [];
            this.basketCount = this.basketList.all.length;
            this.$Message.success("删除成功！");
          }
        });


      },

      //进入组卷中心
      handleSubmitPaper() {
        if (this.basketList.all.length) {
          this.$router.push({
            name:'testPaper'
          })
        }
      },

      //绑定知识点操作
      handleBindPoint(concepts) {
        this.bindPointModal = true;
        this.checkedPointList = concepts;
        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;
        })
      },

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

      //知识点绑定选中事件
      //pointTreeCheck(val, data) {
      //  let points = val.filter(item => item.children.length == 0);
      //  if (points.length > 5) {
      //    this.checkedPointList = points.slice(0, 5);
      //    this.$Message.warning("最多绑定5个知识点！");
      //  } else {
      //    this.checkedPointList = points;
      //  }
      //  console.log(val, data);
      //},

      //知识点树形结构渲染
       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)
      },

      //导入试题
      uploadSuccess(response, file, fileList) {
        let that = this;
        this.importLoading = true;
        if (response.error == null) {
          let requestData = { htmlString: response.result.data.HtmlString }
          this.$api.SaveAnalyzeHtml(requestData).then(res => {
            if (res.error == null) {
              setTimeout(function () {
                that.$Message.success('文件上传解析成功！');
                that.list = res.result.data;
                that.importLoading = false;
              },1000)
              //this.saveItemBank(res.result.data);
            }
          });
        } else {
          this.$Message.error('对不起，文档解析失败！');
        }
      },

      //保存试题到数据库
      saveItemBank(list) {
        this.$api.SaveItemBank(list).then(res => {
          console.log(res);
        })

      }

    },
    mounted() {
        this.getStandardList();
        this.getSchoolPoints();
        //this.getAllPoints();
    },
    computed: {
      headers(){
        let hd = {}
        hd["Authorization"] = "Bearer "+ localStorage.getItem("token");
        return hd;
      }
    }
  }
</script>
<style scoped>
@import "../index/ExercisesList.css";
</style>

<style>
  .circle {
    border: solid 1px red;
    background-color: red;
    border-radius: 50%;
    width: 50px;
    height: 50px;
  }
</style>

<!--<style src="../index/ExercisesList.css" scoped></style>-->
<!--<style>
    .content-wrap .exercise-item p {
      margin:10px 0;
      display:inline-block;
      word-break:break-all;
    }

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