
<template>
  <div class="know-main center">
    <div class="content-wrap">
      <div class="header-wrap">
        <Input placeholder="关键词搜索知识点" style="width:25% !important;" />
        <div class="list-type center">
          <Icon type="md-menu" size="20" :class="listType==0?'list-type-active':''" @click="changeListType(0)" />
          <Icon type="ios-keypad" size="20" :class="listType==2?'list-type-active':''" @click="changeListType(2)" />
          <Icon type="md-cube" size="20" :class="listType==1?'list-type-active':''" @click="changeListType(1)" />

        </div>
        <div class="header-right">
          <div class="header-right-item" @click="addPoint" v-show="listType == 2">
            <Icon type="logo-buffer" size="18" />
            <span>新增知识点</span>
          </div>
          <div class="header-right-item" @click="composeBlock" v-show="listType == 2">
            <Icon type="logo-buffer" size="18" />
            <span>组成知识块</span>
          </div>
          <div class="header-right-item" @click="addBlock" v-show="listType==0">
            <Icon type="ios-browsers" size="18" />
            <span>新增知识块</span>
          </div>
          <div class="header-right-item">
            <Icon type="ios-cloud-download" size="18" />
            <span>导入知识点</span>
          </div>
        </div>
      </div>
      <div class="sy-list-wrap">
        <!-- 知识块 -->
        <div class="list-col" v-if="listType == 0">
          <Spin fix v-show="blockLoading"></Spin>
          <!--<p style="font-size:20px;padding:10px 30px;font-weight:bold;border-bottom:1px solid #000">私有知识块仓库</p>-->
          <Collapse simple accordion @on-change="collapseChange" v-if="knowBlockList.length > 1">
            <Panel v-for="(item,index) in knowBlockList" class="know-block-item" :key="index" :name="item.period">
              <Input v-if="item.knowledgeId==block_edit_id" :ref="'block'+item.knowledgeId" clearable type="text" v-model="item.alias"
                     @on-blur="editKnowBlock(item)"
                     @keyup.enter.native="$event.target.blur"
                     @click.stop.native="inputFocus($event)" />
              <span class="know-block-name" v-else>{{item.alias}} | {{item.children.length}}</span>

              <span class="know-block-builder">建立者 | 郭大侠</span>
              <span class="k-block-tools">
                <Icon type="md-create" @click="handleEditBlock(item,$event)" title="编辑名称" />
                <Icon type="md-add-circle" title="编辑知识点" @click.stop.native="editBlockPoint(item)" />
                <Icon type="md-trash" @click="handleDeleteBlock(item)" title="删除" />
              </span>
              <div slot="content" class="knowpoints">
                <div class="knowpoint-item" v-for="(point,index) in item.children" @mouseover="knowMouseover" @mouseout="knowMouseout">
                  <Input v-if="point.rowKey==point_edit_id" :ref="'point'+point.rowKey" clearable type="text" v-model="point.alias"
                         @on-blur="editKnowPoint(point)"
                         @keyup.enter.native="$event.target.blur"
                         @click.stop.native="inputFocus($event)" />
                  <span v-else class="overflow-text" :title="point.alias">{{point.alias}} </span>
                  <span class="k-tools">
                    <Icon type="md-create" @click="handleEditPoint(point,$event)" />
                    <Icon type="md-trash" @click.stop.native="handleDeleteBlockPoint(point)" />
                  </span>
                </div>
              </div>
            </Panel>
          </Collapse>
          <div v-else class="no-data-text">暂无数据</div>
        </div>

        <!-- 标准知识块 -->
        <div class="list-col" v-else-if="listType == 1">
          <Spin fix v-show="standardLoading"></Spin>
          <p style="font-size:20px;margin:20px 40px;font-weight:bold;">标准知识块数据</p>
          <KnowTree :treeDatas="treeData" v-if="treeData.length > 0"></KnowTree>
          <div v-else class="no-data-text">暂无数据</div>
        </div>

        <!-- 知识点仓库 -->
        <div class="list-col list-knowpoints" v-else>
          <Spin fix v-show="allPointsLoading"></Spin>
          <p style="font-size:20px;margin:20px 30px;font-weight:bold;">私有知识点仓库</p>

          <!--<div class="knowpoints-filter">
      <span :class="filter_index == 0 ? 'sort-active':''" @click="filterSort(0)">综合排序</span>
      <span :class="filter_index == 1 ? 'sort-active':''" @click="filterSort(1)">名称排序</span>
      <span :class="filter_index == 2 ? 'sort-active':''" @click="filterSort(2)">创建时间排序</span>
    </div>-->
          <div class="knowpoints">
            <div v-for="(item,index) in knowPointList" :class="['knowpoint-item',pointCheckedList.indexOf(item) != -1?'knowpoint-item-active':'']" :title="item.description" @mouseover="knowMouseover" @mouseout="knowMouseout" @click="pointClick(item)">
              <Input v-if="item.knowledgeId==point_edit_id" :ref="'point'+item.knowledgeId" clearable type="text" v-model="item.alias"
                     @on-blur="editSchoolPoint(item)"
                     @keyup.enter.native="$event.target.blur"
                     @click.stop.native="inputFocus($event)" />
              <span v-else class="overflow-text" :title="item.alias">{{item.alias}} </span>
              <!--<Icon type="ios-checkmark-circle" color="#00fa00" class="icon-checked"/>-->
              <span class="k-tools">
                <Icon type="md-create" @click="handleEditPoint(item,$event)" />
                <Icon type="md-trash" @click.stop.native="handleDeleteSchoolPoint(item)" />
              </span>
            </div>
          </div>
          <Page show-total
                :current="1"
                :total="schoolAllPoint.length"
                :page-size="pageSize"
                class="center"
                @on-change="pageChange"
                style="margin:20px 0" />
        </div>

        <!-- 新增知识块弹窗 -->
        <Modal v-model="addBlockModal"
               title="新增知识块"
               width="520"
               ok-text="确认"
               cancel-text="取消"
               @on-ok="handleAddBlock"
               @on-cancel="">
          <p class="modal-title">请输入知识块名称</p>
          <Input v-model="newBlockName" placeholder="知识块 名称" style="margin:5px;width:90%" />
        </Modal>

        <!-- 新增知识点弹窗 -->
        <Modal v-model="addPointModal"
               title="新增知识点"
               width="520"
               ok-text="确认"
               cancel-text="取消"
               @on-ok="handleAddPoint"
               @on-cancel="">
          <p class="modal-title">请输入知识点名称</p>
          <Input v-model="newPointName" placeholder="输入名称" style="margin:5px" />
        </Modal>

        <!-- 编辑知识块弹窗 Transfer -->
        <Modal v-model="editBlockPointModal"
               title="编辑知识块"
               width="600"
               ok-text="确认"
               cancel-text="取消"
               class-name="transferModal"
               @on-ok="handleTransferBlock"
               @on-cancel="">
          <Transfer :data="data3"
                    :target-keys="targetKeys"
                    :list-style="listStyle"
                    :render-format="renderTransfer"
                    :operations="['撤回知识库','加入知识块']"
                    filter-placeholder="请输入搜索内容"
                    :titles="[transferStatus?'私有知识库':'标准知识库', '当前知识块']"
                    not-found-text="列表为空"
                    filterable
                    :filter-method="filterMethod"
                    @on-change="handleChangeTransfer">
            <div :style="{float: 'right', margin: '5px'}">
              <Button size="small" type="primary" @click="changePointData(!transferStatus)" class="transferBtn">{{ transferStatus ? '从标准库添加': "从私有库添加"}}</Button>
              <Button size="small" @click="reloadPointData(transferStatus)">刷新</Button>
            </div>
          </Transfer>
        </Modal>

        <!-- 组成知识块弹窗 Tabs -->
        <Modal v-model="composeBlockModal"
               title="组成知识块"
               width="400"
               ok-text="确认"
               cancel-text="取消"
               @on-ok="handleComposeBlock"
               @on-cancel="">
          <Tabs v-model="composeTabName" class="compose-block-tab">
            <TabPane label="建立新的知识块" name="newBlock">
              <p class="modal-title">请输入知识块名称</p>
              <Input v-model="newComposeName" placeholder="请输入" style="margin:5px" />
              <p class="modal-title">当前选中知识点</p>
              <div class="checked-points">
                <div v-for="item in pointCheckedList" class="knowpoint-item knowpoint-item-active">{{item.name}}</div>
              </div>
            </TabPane>
            <TabPane label="移动到现有知识块" name="moveToBlock">
              <RadioGroup v-model="checkedBlock">
                <Radio v-for="(item,index) in knowBlockList" :key="index"  :label="item.knowledgeId"  :name="item.rowKey">{{item.name}}</Radio>
              </RadioGroup>
            </TabPane>
          </Tabs>
        </Modal>

      </div>
    </div>
  </div>
</template>

<script scoped>
    import KnowTree from '@/components/syllabus/KnowTree.vue'
  export default {
    name: "KnowPoint",
    components: {
      KnowTree
    },
    data() {
      return {
        treeData: [],
        schoolInfo: {},
        allPointList: [],
        schoolAllPoint:[],
        knowPointList: [],
        knowBlockList: [],
        pointCheckedList: [],
        checkedBlock:"知识块名称0",
        isShowBlock: false,
        standardLoading: true,
        allPointsLoading: true,
        blockLoading:true,
        listType: 0,
        filter_index: 0,
        pageSize:52,
        newBlockName:"",
        newPointName:"",
        newComposeName:"",
        block_edit_id: null,  //当前知识块编辑索引
        point_edit_id: null,  //当前知识点编辑索引
        point_click_id:null,
        addBlockModal: false, //新增知识块开关
        addPointModal: false, //新增知识点开关
        editBlockPointModal: false, //编辑知识块开关
        composeBlockModal: false, //编辑知识块开关
        composeTabName:"newBlock",
        currentEditBlock: {},
        data3: [],
        targetKeys: [],
        listStyle: {
          width: '220px',
          height: '420px'
        },
        transferStatus:false,
      }
    },
    created() {

      this.schoolInfo = JSON.parse(localStorage.getItem('c_role_info')).roleClaim[0]; //默认选中第一个学校
      let schoolClaims = this.schoolInfo.claim;
      for (let i in schoolClaims) {
        if (schoolClaims[i].claimType == "SchoolCode") {
          this.schoolInfo = schoolClaims[i]
        }
      }

      //获取标准知识块数据
      this.getStandardList();
      this.getAllPoints();
      this.getSchoolBlocks();
      this.getSchoolPoints();
    },
    methods: {
      //获取标准知识块数据
      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.treeData = list;
          this.standardLoading = false;
        })
      },

      //获取标准知识点仓库数据
      getAllPoints() {
         let data = {
          pointParams: {
              SubjectCode: "Subject_Chinese",
              PartitionKey: "zh-CN",
            }
        }
        this.$api.FindKnowledgePointByDict(data).then(res => {
          this.allPointList = res.result.data;
        })
      },

      //获取学校知识点仓库数据
      getSchoolPoints() {
        this.allPointsLoading = true;
         let data = {
              SubjectCode: "Subject_Chinese",
              PartitionKey: "zh-CN",
              SchoolCode: this.schoolInfo.claimCode,
              Status:1
        }
        this.$api.FindSchoolPointByDict(data).then(res => {
          this.schoolAllPoint = res.result.data;
          this.knowPointList = res.result.data.slice(0, this.pageSize);
          this.allPointsLoading = false;
        })
      },

      //获取学校知识块数据
      getSchoolBlocks() {
         this.blockLoading = true;
         let data = {
          pointParams: {
              SubjectCode: "Subject_Chinese",
             PartitionKey: this.schoolInfo.partitionKey,
             SchoolCode: this.schoolInfo.claimCode,
             Status:1
            }
        }
        this.$api.FindSchoolBlockAndPointByDict(data).then(res => {
          this.knowBlockList = res.result.data;
          this.blockLoading = false;
        })
      },

      //切换页码返回截取数据
      pageChange(page) {
        let start = this.pageSize * (page - 1);
        let end = this.pageSize * page;
        this.knowPointList = this.schoolAllPoint.slice(start, end);
      },

      //知识点与知识块切换
      changeListType(status) {
        this.listType = status;
        this.isShowBlock = status == 0;
        if (status == 0) {
          this.getSchoolBlocks();
        } else if (status == 1) {
          this.getStandardList();
        } else {
          this.getSchoolPoints();
        }
      },
      //鼠标滑入事件显示操作选项
      knowMouseover(e) {
        e.stopPropagation();
        e.currentTarget.lastElementChild.style.visibility = 'visible';
      },
      //鼠标滑出事件隐藏操作选项
      knowMouseout(e) {
        e.stopPropagation();
        e.currentTarget.lastElementChild.style.visibility = 'hidden';
      },
      //折叠版切换回调
      collapseChange(arr) {
        this.block_edit_id = null;
          let list = document.getElementsByClassName('k-block-tools');
          for (let i = 0 ; i < list.length ;i++) {
            if (arr.indexOf(i.toString()) != -1) {
              list[i].style.visibility = "visible";
            } else {
              list[i].style.visibility = "hidden";
            }
        }
      },
      //知识点仓库排序操作
      filterSort(index) {
        this.filter_index = index;
      },

      //点击编辑知识块
      handleEditBlock(data, e) {
        e.stopPropagation();
        this.block_edit_id = data.knowledgeId;
        this.$nextTick(() => {
          this.$refs['block' + data.knowledgeId][0].focus();
        })
      },
      //编辑知识块input失焦
      editKnowBlock(data) {
        delete data.rowKey;
        this.$api.SaveOrUpdateSchoolBlock(data).then(res => {
          if (res.result.message == "Success") {
            this.$Message.success("修改成功");
          }
        })
        this.block_edit_id = null;
      },

      //点击编辑知识点
      handleEditPoint(data, e) {
        e.stopPropagation();
        this.point_edit_id = data.knowledgeId;
        this.$nextTick(() => {
          this.$refs['point'+data.knowledgeId][0].focus();
        })
      },
      //编辑知识块包含的知识点input失焦
      editKnowPoint(data) {
        this.$api.SaveOrUpdateAllSchoolBlockPoint([data]).then(res => {
          if (res.result.message == "Success") {
            this.$Message.success("修改成功");
          }
        })
        this.point_edit_id = null;
      },

      //编辑学校知识点input失焦
      editSchoolPoint(data) {
        this.$api.SaveOrUpdateAllSchoolPoint(data).then(res => {
          if (res.result.message == "Success") {
            this.$Message.success("修改成功");
          }
        })
        this.point_edit_id = null;
      },

      //input聚焦
      inputFocus(e) {
        e.cancelBubble = true;
      },

      //点击新增知识块弹窗
      addBlock() {
        this.addBlockModal = true;
      },

       //request新增知识块
      handleAddBlock() {
        if (this.newBlockName && this.newBlockName.replace(/\s*/g, "").length != 0) {
          let addBlockData = {
            schoolCode: this.schoolInfo.claimCode,
            subjectCode: "Subject_Chinese",
            partitionKey: this.schoolInfo.partitionKey,
            knowledgeId: this.common.guid(),
            name: this.newBlockName,
            alias: this.newBlockName,
            pid: "Root",
            order: 0,
            type: 0,
            source: 1
          };
          this.$api.SaveOrUpdateSchoolBlock(addBlockData).then(res => {
            this.getSchoolBlocks();
          });
        } else {
          this.$Message.warning("名称不能为空！");
        }
          this.newBlockName = "";

      },

      //点击新增知识块弹窗
      addPoint() {
        this.addPointModal = true;
      },
      //点击组成知识块弹窗
      composeBlock() {
        if (this.pointCheckedList.length < 1) {
          this.$Message.info('请先勾选需要操作的知识点！');
        } else {
          this.composeBlockModal = true;
          this.checkedBlock = this.knowBlockList[0].knowledgeId;
        }
      },
      //点击编辑知识块弹窗
      editBlockPoint(data) {
        this.currentEditBlock = data;
        this.data3 = this.getPointList(this.transferStatus);
        this.targetKeys = this.getTargetKeys();
        this.editBlockPointModal = true;
        this.reloadPointData(this.transferStatus);
        document.getElementsByClassName('transferBtn')[1].style.display = "none";
      },


      //request-新增知识点
      handleAddPoint() {
        if (this.newPointName && this.newPointName.replace(/\s*/g, "").length != 0) {
        let addPointData = {
          schoolCode: this.schoolInfo.claimCode,
          subjectCode: "Subject_Chinese",
          partitionKey: this.schoolInfo.partitionKey,
          knowledgeId: this.common.guid(),
          name: this.newPointName,
          alias: this.newPointName,
          pid: "Root",
          order: 0,
          type: 0,
          source:1
        };
        this.$api.SaveOrUpdateAllSchoolPoint(addPointData).then(res => {
          this.getSchoolPoints();
        });
          } else {
          this.$Message.warning("名称不能为空！");
        }
        this.newPointName = "";
      },
      //request-编辑知识块
      handleEditBlockPoint() {
        console.log(this.targetKeys);

      },

      //request-组成知识块
      handleComposeBlock() {
        let datas = [];
        let pointCheckedList = this.pointCheckedList;
        if (this.composeTabName == "newBlock" && this.newComposeName && this.newComposeName.replace(/\s*/g, "").length != 0) {
          let addBlockData = {
            schoolCode: this.schoolInfo.claimCode,
            subjectCode: "Subject_Chinese",
            partitionKey: this.schoolInfo.partitionKey,
            knowledgeId: this.common.guid(),
            name: this.newComposeName,
            alias: this.newComposeName,
            pid: "Root",
            order: 0,
            type: 0,
            source: 1
          };
          this.$api.SaveOrUpdateSchoolBlock(addBlockData).then(res => {
            for (let i in pointCheckedList) {
              let point = pointCheckedList[i];
              point.type = point.type || 1;
              point.knowledgeId = point.knowledgeId || point.rowKey;
              point.alias = point.alias || point.name;
              point.pid = res.result.data.knowledgeId;
              point.schoolCode = point.schoolCode || this.schoolInfo.claimCode;
              point.source = this.transferStatus ? "1" : "0";
              point.status = 1;
              delete point.rowKey;
              datas.push(point);
            }
            this.$api.SaveOrUpdateAllSchoolBlockPoint(datas).then(res => {
              if (res.result.message == "Success") {
                this.$Message.success("添加成功");
                this.changeListType(0);
              }
            })
          });
        } else if (this.composeTabName == "moveToBlock") {
          for (let i in pointCheckedList) {
            let point = pointCheckedList[i];
            point.type = point.type || 1;
            point.knowledgeId = point.knowledgeId || point.rowKey;
            point.alias = point.alias || point.name;
            point.pid = this.checkedBlock;
            point.schoolCode = point.schoolCode || this.schoolInfo.claimCode;
            point.source = this.transferStatus ? "1" : "0";
            point.status = 1;
            delete point.rowKey;
            datas.push(point);
          }
          this.$api.SaveOrUpdateAllSchoolBlockPoint(datas).then(res => {
            if (res.result.message == "Success") {
              this.$Message.success("添加成功");
              this.changeListType(0);
            }
          })
        } else if (this.composeTabName == "newBlock" && !this.newComposeName && this.newComposeName.replace(/\s*/g, "").length == 0) {
            this.$Message.warning("名称不能为空！");
        }
        this.newComposeName = "";
        this.pointCheckedList = [];

      },

      pointClick(data) {
        //this.point_click_id = data.id;
        let list = this.pointCheckedList;
        if (list.indexOf(data) == -1) {
          list.push(data);
        } else {
          list.splice(list.indexOf(data), 1);
        }
      },
      //获取transfer的知识点数据源
      getPointList(status) {
        let mockData = [];
        let list = status ? this.schoolAllPoint : this.allPointList ;
        for (let i = 0; i < list.length; i++) {
          mockData.push({
            id: i,
            key: i.toString(),
            label: i.toString(),
            name: list[i].name,
            termNum: i + 5,
            blockId: i + 1,
            description: list[i].name
          });
        }
        return mockData;
      },
      getTargetKeys() {
        let targetArr = [];
        return targetArr;
      },
      handleChangeTransfer(newTargetKeys) {
        this.targetKeys = newTargetKeys;
      },
      renderTransfer(item) {
        return item.name;
      },
      //重置数据
      reloadPointData(status) {
        this.data3 = this.getPointList(status);
        this.targetKeys = this.getTargetKeys();
      },
      //切换数据源
      changePointData(status) {
        this.data3 = this.getPointList(status);
        this.targetKeys = this.getTargetKeys();
        this.transferStatus = status;
      },
      //确认编辑知识块
      handleTransferBlock() {
        let datas = [];
        let list = this.transferStatus ? this.schoolAllPoint : this.allPointList;
        let keys = this.targetKeys;
        for (let i in keys) {
          let point = list[keys[i]];
          point.type = point.type || 1;
          point.knowledgeId = point.knowledgeId || point.rowKey;
          point.alias = point.alias || point.name;
          point.pid = this.currentEditBlock.knowledgeId;
          point.schoolCode = point.schoolCode || this.schoolInfo.claimCode;
          point.source = this.transferStatus ? "1" : "0";
          point.status = 1;
          delete point.rowKey;
          datas.push(point);
        }
        this.$api.SaveOrUpdateAllSchoolBlockPoint(datas).then(res => {
          this.$Message.success("添加成功");
          this.getSchoolBlocks();
        });
      },
      //transfer Input 筛选数据
      filterMethod(data, query) {
        let val = data.name;
        return val.toUpperCase().indexOf(query.toUpperCase()) > -1;
      },

      //删除知识块中的知识点
      handleDeleteBlockPoint(data) {
         this.$Modal.confirm({
          title: '移除知识点',
          content: '<p>确认移除该知识点吗？</p>',
          okText:"确认",
          cancelText:"取消",
           onOk: () => {
             let params = {
               PartitionKey: data.partitionKey,
               RowKey: data.rowKey,
               KnowledgeId: data.knowledgeId,
               SubjectCode: data.subjectCode,
               SchoolCode: data.schoolCode
             }
            this.$api.RemoveSchoolBlockPoint(params).then(res => {
              this.getSchoolBlocks();
            });
          },
          onCancel: () => {
            //this.$Message.info('Clicked cancel');
          }
        });
      },

      //删除知识块
      handleDeleteBlock(data) {
         this.$Modal.confirm({
          title: '移除知识块',
          content: '<p>确认移除该知识块吗？</p>',
          okText:"确认",
          cancelText:"取消",
           onOk: () => {
             data.status = 0;
            this.$api.SaveOrUpdateSchoolBlock(data).then(res => {
              if (res.result.message == "Success") {
                this.$Message.success("修改成功");
                this.getSchoolBlocks();
                }
            });
          },
          onCancel: () => {
            this.$Message.info('Clicked cancel');
          }
        });
      },
      //删除知识块
      handleDeleteSchoolPoint(data) {
         this.$Modal.confirm({
          title: '移除知识点',
          content: '<p>确认移除该知识点吗？</p>',
          okText:"确认",
          cancelText:"取消",
           onOk: () => {
             data.status = 0;
            this.$api.SaveOrUpdateAllSchoolPoint(data).then(res => {
              if (res.result.message == "Success") {
                this.$Message.success("修改成功");
                this.getSchoolPoints();
                }
            });
          },
          onCancel: () => {
            //this.$Message.info('Clicked cancel');
          }
        });
      }
    }
  }
</script>
