<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--档案目录数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="muName"
            placeholder="请输入档案目录名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="dangAnOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--档案上传-->
      <el-col :span="20" :xs="24">
        <div style="display: flex; justify-content: space-between">
          <el-button icon="el-icon-upload2" type="primary" @click="handleImport">点击上传</el-button>
          <el-button icon="el-icon-full-screen" type="primary" v-if="pictureRecard.length>0" @click="OCRRecognition">OCR识别</el-button>
        </div>

        <div style="margin-top: 100px;">
          <el-empty :image-size="240" v-if="pictureRecard.length===0"></el-empty>

          <div v-if="pictureRecard.length>0">
            <el-checkbox v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
            <div style="margin: 15px 0;"></div>
            <el-checkbox v-for="item in pictureRecard" :label="item.picName" :key="item.id" v-model="item.checked" @change="handleCheckChange(item)">
              <div style="width: 150px;">
                <el-image
                  style="width: 120px; height: 120px"
                  :src="item.picUrl"
                  :preview-src-list="[item.picUrl]">
                </el-image>
                <p>{{ item.picName }}</p>
                <p>{{ item.muPath }}</p>
                <p>{{ item.wlsjPath }}</p>
              </div>
            </el-checkbox>
          </div>

        </div>

      </el-col>

    </el-row>

    <el-dialog title="档案文件上传" :visible.sync="upload.open" width="700px" append-to-body>
      <div style="margin-bottom: 30px;display: flex;min-height: 250px">
        <div style="width:250px;border: 1px solid #eee; padding: 10px;">
          <div style="margin-bottom: 5px;">物理书架：</div>
          <el-tree
            :data="shuJiaOptions"
            :props="{
            children: 'children',
            label: 'name'
          }"
            :expand-on-click-node="false"
            ref="myTreeSelect"
            node-key="shelfId"
            default-expand-all
            highlight-current
            @node-click="selectTree"
          />
        </div>

        <div v-show="upload.shelfId" style="width: 360px;margin-left: 20px;">
          <el-upload :show-file-list="false"
                     ref="upload"
                     action="#"
                     drag
                     :before-upload="beforeUpload"
                     :http-request="httpRequest"
                     multiple
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>

          <ul class="el-upload-list el-upload-list--text" style="max-height:200px;overflow-y:scroll;padding: 15px;">
            <li tabindex="0" class="el-upload-list__item is-success" v-for="(item,index) in fileList" :key="item.uid">
              <a class="el-upload-list__item-name">
                <i class="el-icon-document"></i>
                {{ item.name }}
              </a>
              <label class="el-upload-list__item-status-label">
                <i class="el-icon-upload-success el-icon-circle-check"></i>
              </label>
              <i class="el-icon-close" @click="deleteFile(index)"></i>
            </li>
          </ul>

        </div>

      </div>

      <div style="text-align: center">
        <el-button style="width:300px;" type="primary" @click="submitFiles">确定上传</el-button>
      </div>

    </el-dialog>

  </div>
</template>

<script>
import { catalogTreeselect } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listBookshelf } from "@/api/dangan/bookshelf";
import { collectSaves, collectRecongnize } from "@/api/dangan/collection";

export default {
  name: "Collection",
  components: {Treeselect},
  data() {
    return {
      fileList: [],
      dangAnID: '',
      dangAnNode: undefined,
      // 档案目录树选项
      dangAnOptions: undefined,
      // 档案目录名称
      muName: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        shelfId: undefined,
        wlsjNode: undefined
      },
      // 书架树选项
      shuJiaOptions: [],
      pictureRecard: [],
      // 是否全选
      checkAll: false,
    };
  },
  watch: {
    // 根据名称筛选档案目录树
    muName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getDeptTree();
  },
  methods: {
    /** 查询档案目录下拉树结构 */
    getDeptTree() {
      catalogTreeselect().then(response => {
        this.dangAnOptions = response.data;

        this.$nextTick(() => {
          this.$refs.tree.setCurrentKey(this.$route.query.id);
          this.dangAnNode = this.$refs.tree.getNode(this.$route.query.id)
        });

      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data, Node) {
      this.dangAnID = data.id;
      this.dangAnNode = Node;
    },
    /** 导入按钮操作 */
    handleImport() {
      this.getTreeselect();
      this.fileList = []
      this.upload.shelfId=undefined;
      this.upload.wlsjNode=undefined;
      this.upload.open = true;
    },
    /** 查询目录下拉树结构 */
    getTreeselect() {
      listBookshelf().then(response => {
        this.shuJiaOptions = this.handleTree(response.rows, "shelfId", "pid")
      });
    },
    // 上传文件之前的钩子
    beforeUpload(file) {
      this.$refs.upload.clearFiles();
      this.fileList.push(file);
    },
    httpRequest(file) {
      console.log('httpRequest', this.fileList, file);
    },
    submitFiles() {
      const formData = new FormData();
      this.fileList.forEach((file) => {
        formData.append('files', file);
      });

      const DaPicturesRecard = {}
      DaPicturesRecard.muId = this.dangAnNode.key;
      DaPicturesRecard.muPath = this.getAllLabels(this.dangAnNode);

      DaPicturesRecard.wlsjId = this.upload.wlsjNode.key;
      DaPicturesRecard.wlsjPath = this.getAllLabels(this.upload.wlsjNode);

      formData.append('picRecard', new Blob([JSON.stringify(DaPicturesRecard)],{ type: 'application/json', }));

       collectSaves(formData).then(response => {
         this.pictureRecard = response.data;
         this.upload.open = false;
       });
    },
    selectTree(data, Node) {
      this.upload.shelfId = data.shelfId;
      this.upload.wlsjNode = Node;
    },
    getAllLabels(obj) {
      let values = '';

      function getValues(obj) {
        if(values.length>0){
          values = obj.label+'/'+values
        }else {
          values = obj.label
        }

        if(obj.level>1){
          getValues(obj.parent);
        }
      }

      getValues(obj);
      return values;
    },
    handleCheckAllChange(val) {
      this.pictureRecard.forEach(item =>{
        item['checked']= val
      })
      this.pictureRecard = [...this.pictureRecard]
    },
    handleCheckChange(val) {
      let checkAll = true
      this.pictureRecard.forEach(item=>{
        if(!item['checked']){
          checkAll = false
        }
      })
      this.pictureRecard = [...this.pictureRecard]
      this.checkAll = checkAll
    },
    OCRRecognition(){
      let arr = [];
      this.pictureRecard.forEach(item => {
        if(item.checked){
          arr.push(item)
        }
      })

      if(arr.length>0){
        collectRecongnize(arr).then(response => {
          this.pictureRecard = [];
          this.$modal.msgSuccess("操作成功");
        });
      }else {
        this.$alert(`请先选择需要识别的档案！`, `提示`, {
          type: 'warning'
        });
      }
    },
    deleteFile(index){
      this.fileList.splice(index, 1);
    }
  }
};
</script>

<style lang="scss" scoped>

::v-deep .el-checkbox__inner{
  width: 20px;
  height: 20px;
}

::v-deep .el-checkbox__inner::after {
  height: 10px;
  left: 7px;
  top: 2px;
}
</style>
