<template>
  <basic-container>
    <avue-crud :option="option" :table-loading="loading" :data="data" :page.sync="page" ref="crud" v-model="form"
      :permission="permissionList" :before-open="beforeOpen" @search-change="searchChange" @search-reset="searchReset"
      @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange"
      @refresh-change="refreshChange" @on-load="onLoad" :upload-after="uploadAfter">
      <template slot-scope="{row}" slot="menu">
        <el-button size="small" v-show="permission.knowledgeView" @click="$refs.crud.rowView(row, index)">查看</el-button>
        <el-button size="small" v-show="permission.knowledgeEdit"  @click="$refs.crud.rowEdit(row, index)">编辑</el-button>
        <el-button size="small" v-show="permission.knowledgeDelete"  @click="rowDel(row)">删除</el-button>
        <el-button size="small" v-show="row.attach.length != 0 && permission.knowledgeDownload" @click="handlePreview(row)">下载</el-button>
      </template>
      <template slot-scope="{row}" slot="fileName">
        {{ row.attach.length > 0 ? row.attach.map(item => item.attachName).join(',') : '' }}
      </template>
      <template slot-scope="{row}" slot="imgUrlForm">
        <el-upload class="upload-demo" action="/api/blade-resource/oss/endpoint/put-file" :on-remove="handleRemove"
          :on-success="handleSuccess" multiple :limit="3" :on-exceed="handleExceed" :file-list="imgList"
          :headers="headers">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">最多只能上传3个文件</div>
        </el-upload>
      </template>
      <!-- <template slot-scope="{row}" slot="searchValueSearch">
        <el-input style="margin-left: -80px;width: 305px;" placeholder="请输入故障等关键词"
          v-model="form.searchValue"></el-input>
      </template> -->
      <template slot-scope="{row}" slot="publishSta">
        <el-tag size="small" :type="row.publishSta == 1 ? '' : row.publishSta == 2 ? 'danger' : 'info'">{{
          row.publishSta == 1 ? '已发布' : row.publishSta == 2 ? '已取消'
            : '已保存'
        }}</el-tag>
      </template>
      <!-- 自定义弹窗按钮 -->
      <template slot-scope="{row,index,type}" slot="menuForm">
        <el-button @click="handleCancel"> 取消</el-button>
        <el-button v-show="type == 'add'" type="primary" size="small" @click="addPublish()">提交</el-button>
        <el-button v-show="type == 'edit'" type="primary" size="small" @click="updatePublish()">提交</el-button>
      </template>
    </avue-crud>
    <el-dialog width="70%" :visible.sync="dialogVisible" :append-to-body="true" :close-on-click-modal="false"></el-dialog>
  </basic-container>
</template>
<script>
// import { getKnowledgeList, remove, add, getDetail, doPublish, addPublish, queryArticleDetail } from "@/api/articlelist/article";
import website from '@/config/website';
import { getKnowledgeList, addKnowledge, getDetail, editKnowledge, insertKnowledgeContent, updateKnowledge, deleteKnowledge } from '@/api/knowledge/knowledge'
import {getToken, removeToken, removeRefreshToken} from '@/util/auth';
import { mapGetters } from "vuex";
import JSZip from 'jszip';
import { saveAs } from 'file-saver';
export default {
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      dialogVisible: false,
      selectionList: [],
      option: {
        searchShowBtn: false,
        refreshBtn: false,
        columnBtn: false,
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        addBtn:true,
        viewBtn: false,
        saveBtn: false,
        delBtn: false,
        editBtn: false,
        updateBtn: false,
        cancelBtn: false,
        dialogType: 'dialog',
        dialogClickModal: false,
        column: [
          {
            label: "知识类别",
            labelWidth: 120,
            span: 24,
            prop: "dictKey",
            type: "select",
            formslot: true,
            dicUrl: '/api/blade-system/dict-biz/child-list?current=1&size=100&parentId=1854791470553329666',
            dicFormatter: (res) => {
              return res.data[0].children
            },
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            search: true
          },
          {
            label: '附件',
            labelWidth: 120,
            prop: 'fileName',
            slot: true,
            editDisplay: false,
            addDisplay: false,
            viewDisplay:false
          },
          {
            label: "知识库内容",
            labelWidth: 120,
            prop: "content",
            component: 'AvueUeditor',
            overHidden: true,
            options: {
              customConfig: {
                menus: ['head', 'bold', 'fontSize', 'fontName', 'italic', 'underline', 'strikeThrough', 'foreColor', 'backColor', 'link', 'list', 'justify', 'quote', 'emoticon', 'table', 'code', 'undo', 'redo']
              },
              action: '/api/blade-resource/oss/endpoint/put-file',
              props: {
                home: this.website.filePrex,
                res: "data",
                url: "link",
              }
            },
            minRows: 12,
            span: 24,
            html: true,
            formatter: (val) => {
              if (val.content) {
                return '<div style="max-height:80px;overflow:hidden;">' + decodeURIComponent(val.content) + '</div>';
              } else {
                return '<div style="max-height:80px;overflow:hidden;">' + '' + '</div>';
              }
            }
          },
          {
            label: '附件',
            prop: 'imgUrl',
            type: 'upload',
            labelWidth: 120,
            hide: true,
            span: 24,
            multiple: true,
            propsHttp: {
              url: 'link',
              name: 'originalName',
              res: 'data'
            },
            action: '/api/blade-resource/oss/endpoint/put-file',
            formslot: true
          },
        ]
      },
      data: [],
      fileList: [],
      imgList: [],
      previewList: [],
      headers:{},
    };
  },
  computed: {
    ...mapGetters(["userInfo","permission"]),
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  mounted() {
    this.headers = {
      "Authorization":`Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`,
      'Blade-Auth':'bearer ' + getToken(),
      'Blade-Requested-With':'BladeHttpRequest'
    }
    console.log('permission----------->',this.permission.knowledgeView)
    this.option.addBtn = this.permission.knowledgeAdd ? true :false
    console.log('optipon===============>',this.option)
  },
  methods: {
    // 存在附件的知识库可进行预览操作
    handlePreview(row) {
      getDetail({ id: row.id }).then(res => {
        this.previewList = res.data.data.attach
        if (this.previewList.length > 1) {
          const zip = new JSZip();
          // 下载后压缩包的名称
          const blogTitle = 'file.zip'
          const cache = {};
          const promises = [];
          this.previewList.forEach(item => {
            if (item.attachUrl) {
              const promise = this.getFile(item.attachUrl).then(data => {
                // *下载文件, 并存成ArrayBuffer对象
                const arr_name = item.attachName.split("/");
                const file_name = arr_name[arr_name.length - 1]; // *获取文件名
                zip.file(file_name, data, { binary: true }); // *逐个添加文件
                cache[file_name] = data;
              });
              promises.push(promise);
            }
          });
          Promise.all(promises).then(() => {
            zip.generateAsync({
              type: "blob", compression: 'DEFLATE',  // *STORE: 默认不压缩; DEFLATE：需要压缩
              compressionOptions: {
                level: 9 // *压缩等级 1~9。1: 压缩速度最快，9: 最优压缩方式
              }
            }).then(content => {
              saveAs(content, blogTitle); // *生成二进制流，利用file-saver保存文件，文件名自定义
            });
          });
        } else if (this.previewList.length == 1) {
          // var a = document.createElement("a");
          // console.log(a, this.previewList);


          // var event = new MouseEvent("click");

          // a.target = "_blank";
          // a.download = this.previewList[0].attachName;
          // a.href = this.previewList[0].attachUrl;//路径前拼上前缀，完整路径
          // a.dispatchEvent(event);
          fetch(this.previewList[0].attachUrl, {
                method: 'get',
                heanders: {
                    'Content-Type': 'application/json;charset=UTF-8'
                }
            })
                .then(res => res.blob())
                .then(blob => {
                    const link = document.createElement('a')
                    link.style.display = 'none'
                    link.download = this.previewList[0].attachName// 设置下载属性 以及文件名
                    link.href = URL.createObjectURL(blob)

                    document.body.appendChild(link)
                    link.click()
                    // 释放的 URL 对象以及移除 a 标签
                    URL.revokeObjectURL(link.href)
                    document.body.removeChild(link)
                })

        }
      })
    },
    getFile(url) {
      return new Promise((resolve, reject) => {
        //通过请求获取文件blob格式
        let xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", url, true);
        xmlhttp.responseType = "blob";
        xmlhttp.onload = function () {
          if (xmlhttp.status == 200) {
            resolve(xmlhttp.response);
          } else {
            reject(xmlhttp.response);
          }
        };
        xmlhttp.send();
      });
    },
    // 文件上传成功钩子
    handleSuccess(response, file, fileList) {
      this.fileList.push({
        attachName: response.data.originalName,
        attachUrl: response.data.link
      })
    },
    // 文件删除钩子
    handleRemove(file, fileList) {
      this.imgList = this.imgList.filter(item => item.link != file.link)
      this.fileList = this.fileList.filter(item => item.attachUrl != file.link)
    },
    //富文本编辑器上传
    uploadAfter(res, done) {
      this.fileList.push({
        attachUrl: res.link,
        // 附件名称
        attachName: res.originalName,
      })
      done();
    },
    //发布
    rowPublish(row) {
      this.$confirm("确定" + (row.publishSta == 1 ? "取消发布该条数据吗" : "发布该条数据吗") + "?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          if (row.publishSta != 1) {
            //发布之前判断是否已有发布
            queryArticleDetail(this.userInfo.dept_id).then(res => {
              if (JSON.stringify(res.data.data) != '{}') {
                //一个医院只可以发布一条
                this.$confirm("只可以发布一条须知，确认发布将会把已发布须知取消发布！", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning"
                })
                  .then(() => {
                    this.doSurePublish(row);
                  });
              } else {
                this.doSurePublish(row);
              }
            })
          } else {
            //取消发布不需要限制
            this.doSurePublish(row);
          }
        });
    },
    //二次确认发布-取消发布
    doSurePublish(row) {
      doPublish(row.id, row.publishSta == 1 ? 0 : 1).then(res => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      })
    },
    rowUpdate(row, index, done, loading) {
      row.content = encodeURIComponent(row.content);
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    // 取消
    handleCancel() {
      this.$refs.crud.closeDialog()
      this.fileList = []
    },
    //知识库弹窗提交按钮
    addPublish() {
      let param = this.form;
      param.createDept = this.userInfo.dept_id;
      param.content = encodeURIComponent(param.content);
      let query = {
        dictKey: param.dictKey,
        content: param.content,
        userId: this.userInfo.user_id,
        attach: this.fileList
      }
      insertKnowledgeContent(query).then(res => {
        if (res.data.code == 200) {
          this.$message.success('知识库新增成功')
          this.$refs.crud.closeDialog()
          this.fileList = []
          this.imgList = []
          this.onLoad(this.page)
        }
      })
    },
    updatePublish() {
      let params = JSON.parse(JSON.stringify(this.form))
      params.content = encodeURIComponent(params.content);
      let query = {
        id: params.id,
        dictKey: params.dictKey,
        content: params.content,
        userId: this.userInfo.user_id,
        attach: this.fileList
      }
      updateKnowledge(query).then(res => {
        if (res.data.code == 200) {
          this.$message.success('知识库编辑成功')
          this.$refs.crud.closeDialog()
          this.fileList = []
          this.imgList = []
          this.onLoad(this.page)
        }
      })
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return deleteKnowledge(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      console.log('type', type)
      if (["edit", "view"].includes(type)) {
        getDetail({ id: this.form.id }).then(res => {
          res.data.data.content = decodeURIComponent(res.data.data.content);
          this.form = res.data.data;
          let imgData = []
          this.fileList = []
          res.data.data.attach.length > 0 && res.data.data.attach.map(item => {
            imgData.push({
              link: item.attachUrl,
              name: item.attachName
            })
            this.fileList = res.data.data.attach
          })
          this.form = {
            ...this.form,
            imgUrl: imgData
          }
          this.imgList = imgData
          done();
        });
      } else if (['add'].includes(type)) {
        this.imgList = []
        this.fileList = []
        done();
      }
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      // console.log(this.userInfo)
      console.log('query--------->', this.query)
      this.loading = true;
      getKnowledgeList({ current: page.currentPage, size: page.pageSize, dictKey: this.query.dictKey ? this.query.dictKey : '' }).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style></style>
