<template>
  <div class="aos-files">
    <div class="aos-files__left">
      <div class="aos-files__tree-search">
        <el-input
          placeholder="输入搜索关键词"
          suffix-icon="el-icon-search"
          v-model="filterText">
        </el-input>
      </div>
      <el-tree
        class="aos-files__tree"
        ref="tree"
        default-expand-all
        :data="categorys"
        :props="defaultProps"
        :filter-node-method="filterNode"
        @node-click="handleNodeClick">
        <span class="aos-files__tree-item" slot-scope="{ node, data }">
          <span :class="{'aos-files__required': data.required}" :title="node.label">{{ node.label }}</span>
        </span>
      </el-tree>
    </div>
    <div class="aos-files__container">
      <div class="aos-files__operation">
        <el-checkbox v-model="checkedAll" @change="handleCheckedAll">全选</el-checkbox>
        <el-button class="aos-files__operation-button" type="text" @click="handleDownloadBatch"><i class="el-icon-download"></i>批量下载</el-button>
        <el-button class="aos-files__operation-button" v-if="showDelete" type="text" @click="handleDeleteBatch"><i class="el-icon-delete"></i>批量删除</el-button>
      </div>
      <div class="aos-files__main">
        <div class="aos-files__hint"><i class="el-icon-question"></i>{{currentFiles.fileCountMessage}}</div>
        <div class="aos-files__file">
          <div class="aos-files__file-item" v-if="currentFiles.detailChildren && currentFiles.detailChildren.length > 0" :id="'aos-files_' +currentFiles.id">
            <el-checkbox-group v-model="currentCheckedList" class="aos-files__file-item-group">
            <div class="aos-files__file-item-container" v-for="item in currentFiles.detailChildren" :key="item.id">
              <div class="aos-files__file-item-body">
                <div v-if="otherFileTypeList.indexOf(item.fileExt.toLowerCase()) > -1" class="aos-files__file-item-detail">
                  <i v-if="item.fileExt === 'docx' || item.fileExt === 'DOCX'" class="iconfont icon-doc" style="cursor:pointer;font-size:50px;" :title="item.fileName" :name="item.fileName"/>
                  <i v-else-if="item.fileExt === 'xlsx' || item.fileExt === 'XLSX'" class="iconfont icon-xls" style="cursor:pointer;font-size:50px;" :title="item.fileName" :name="item.fileName"/>
                  <i v-else-if="iconList.includes(item.fileExt)" class="iconfont" :class="'icon-'+item.fileExt" style="cursor:pointer;font-size:50px;" :title="item.fileName" :name="item.fileName"/>
                </div>
                <div v-else-if="item.fileExt === 'pdf' || item.fileExt === 'PDF'" class="aos-files__file-item-detail" @click="handleViewPdf(item)">
                  <i class="iconfont icon-pdf" style="cursor:pointer;font-size:50px;" :title="item.fileName" :name="item.fileName"/>
                </div>
                <div v-else-if="videoFileTypeList.indexOf(item.fileExt.toLowerCase()) > -1" class="aos-files__file-item-detail" @click="handleViewVideo(item)">
                  <i class="iconfont icon-mp4" style="cursor:pointer;font-size:50px;" :title="item.fileName" :name="item.fileName"/>
                </div>
                <div v-else-if="audioFileTypeList.indexOf(item.fileExt.toLowerCase()) > -1" class="aos-files__file-item-detail" @click="handleViewVideo(item)">
                  <i class="iconfont icon-mp3" style="cursor:pointer;font-size:50px;" :title="item.fileName" :name="item.fileName"/>
                </div>
                <div v-else-if="imgFileTypeList.includes(item.fileExt.toLowerCase())" class="aos-files__file-item-detail" @click="handleViewerImg('aos-files_'+currentFiles.id)">
                  <img style="cursor:pointer;" :src="item.thumbFileUrl" :alt="item.fileName" :name="item.fileName" :title="item.fileName"/>
                </div>
                <div v-else class="aos-files__file-item-detail">
                  <i class="el-icon-document"></i>
                </div>
                <div class="aos-files__file-item-operation">
                  <span class="aos-files__file-item-operation-delete" v-if="showDelete" @click="handleDelete(item)">删除</span>
                  <span class="aos-files__file-item-operation-download" @click="handleDownload(item)">下载</span>
                </div>
                <div class="aos-files__file-item-check">
                  <el-checkbox :label="item.id" :checked="item.checked" :showLabel="false"></el-checkbox>
                </div>
              </div>
              <div class="aos-files__file-item-name">{{ item.fileName + '.' + item.fileExt}}</div>
            </div>
            </el-checkbox-group>
            <div class="aos-files__file-item-container" v-if="currentFiles.showItemUpload && showUpload">
              <el-upload
                v-loading="loading"
                class="aos-files__file-item-body"
                drag
                multiple
                :accept="acceptFileExt"
                :show-file-list="false"
                :action="'/oss/api/fids/upload?ruFileId=' + currentFiles.id"
                :before-upload="handleBeforeUpload"
                :on-error="handleOnerror"
                :on-success="handleUploadSuccess">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<span class="aos-files__file-item-button">点击上传</span></div>
                <!-- <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div> -->
              </el-upload>
              <div class="aos-files__file-item-name">{{includeFileExt}}</div>
            </div>
          </div>
          <div v-else-if="currentFiles.showItemUpload && showUpload" class="aos-files__file-item-container">
            <el-upload
              v-loading="loading"
              class="aos-files__file-item-body"
              drag
              multiple
              :accept="acceptFileExt"
              :show-file-list="false"
              :action="'/oss/api/fids/upload?ruFileId=' + currentFiles.id"
              :before-upload="handleBeforeUpload"
              :on-error="handleOnerror"
              :on-success="handleUploadSuccess">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<span class="aos-files__file-item-button">点击上传</span></div>
              <!-- <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div> -->
            </el-upload>
            <div class="aos-files__file-item-name">{{includeFileExt}}</div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      title="播放器"
      :visible.sync="showVideDialog"
      append-to-body
      destroy-on-close
      width="30%"
      @close="handleVideoClose">
      <div class="aos-files__video">
        <aos-video ref="aos-files-video" :options="videoOptions"></aos-video>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Viewer from 'viewerjs-optimize';
import { PopupManager } from 'aos-element/src/utils/popup';
export default {
  name: 'AosFiles',
  props: {
    // 业务类型
    businessModel: {
      type: String,
      required: true
    },
    // 业务主键
    businessPk: {
      type: String,
      required: true
    },
    // 业务场景
    businessScene: {
      type: String,
      default: ''
    },
    // 是否显示上传
    showUpload: {
      type: Boolean,
      default: true
    },
    // 是否显示删除按钮
    showDelete: {
      type: Boolean,
      default: true
    },
    beforeUpload: {
      type: Function
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    businessPk: function(val,oldVal){
      if(val !== oldVal){
        this.getFileDetail();
      }
    },
    businessModel: function(val, oldVal) {
      if (val !== oldVal) {
        this.getFileDetail();
      }
    },
    businessScene: function(val,oldVal){
      if(val !== oldVal){
        this.getFileDetail()
      }
    }
  },
  data () {
    return {
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      viewer: '',
      categorys: [],
      files: '',
      fileItems: '',
      currentContainerId: '',
      currentContainer: '',
      currentFiles: '',
      checkedAll: false,
      otherFileTypeList: ['docx','doc', 'xls', 'zip', 'xlsx', 'rar', 'txt'],
      iconList: ['bmp','doc','gif','mp3','pdf', 'ppt', 'txt', 'rar', 'xls', 'zip', 'wps', 'avi', 'mp4'],
      videoFileTypeList: ['mp4','webm','mov','flv'],
      audioFileTypeList: ['mp3', 'wav', 'ogg'],
      imgFileTypeList: ['png','jpg','jpeg','gif','tif','tiff','bmp', 'svg', 'webp', 'ico'],
      currentCheckedList: [],
      filterText: '',
      showVideDialog: false,
      videoOptions: {},
      includeFileExt: '支持rar、zip、doc、docx、xls、xlsx、wps、ppt、txt、mp3、ogg、avi、mp4、jpg、jpeg、png、gif、svg, pdf格式',
      acceptFileExt: 'rar,zip,doc,docx,xls,xlsx,wps,ppt,txt,pdf,mp3,ogg,avi,mp4,jpg,jpeg,png,gif,svg,PNG,JPG,JPEG,PNG,GIF,SVG,RAR,ZIP,DOC,DOCX,XLS,XLSX,WPS,PPT,TXT,PDF,MP3,MP4,AVI',
      loading: false
    }
  },
  created () {
    this.getFileDetail()
  },
  beforeDestroy () {
    if (this.viewer) {
      this.viewer = null
    }
    this.removeContainer()
  },
  methods: {
    handleVideoClose () {
      this.$refs['aos-files-video'].destory()
    },
     // 校验必传的图片
    checkAready(callback) {
      if (typeof callback !== 'function' && window.Promise) {
        window.Promise((resolve, reject) => {
          callback = function(valid) {
            valid ? resolve(valid) : reject(valid);
          };
        });
      }
      let valid = true;
      let length = this.files.length;
      for(let i = 0;i<length;i++){
        if(!this.files[i].isAready){
          valid = false;
          break;
        }
      }
      callback(valid);
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    handleViewPdf (item) {
      this.$openPdfViewer(item.realFileUrl)
    },
    handleViewVideo (item) {
      this.showVideDialog = true
      this.videoOptions = {
        width: 400,
        sources: [
          {
            src: item.realFileUrl,
            type: `video/${item.fileExt}`
          }
        ]
      }
    },
    handleViewerImg(id){
      this.showImgViewer = true;
      if (this.viewer) {
        this.viewer.destroy();
        this.viewer = null;
      }
      this.viewer = new Viewer(document.getElementById(id), {
        className: 'aos-img-viewer-container ' + id,
        zIndex: PopupManager.nextZIndex() + 100
      });
    },
    handleViewImg () {
      const data = this.currentFiles
      if (!data.detailChildren || (data.detailChildren && data.detailChildren.length <= 0)) return
      this.removeContainer(data.id)
      let container = this.currentContainer
      if (this.viewer) {
        this.viewer.destroy();
        this.viewer = null;
      }
      const children = data.detailChildren
      if (!this.currentContainerId || (this.currentContainerId && this.currentContainerId !== data.id)) {
        container = this.createImgList(children, data.id)
      }
      this.currentContainerId = data.id
      this.currentContainer = container
      this.viewer = new Viewer(document.getElementById('aos-files-' + data.id), {
        className: 'aos-img-viewer-container ' + ('aos-files-' + data.id)
      });
      container.children[0].click()
    },
    handleFileItemCheckedChange (value, item) {
      item.checked = value
      const id = item.id
      if (value) {
        this.currentCheckedList.push(id)
      } else {
        if (this.currentCheckedList.length > 0) {
          for (let index = 0; index < this.currentCheckedList.length; index++) {
            const element = this.currentCheckedList[index];
            if (element === id) {
              this.currentCheckedList.splice(index, 1)
              break
            }
          }
        }
      }
    },
    handleCheckedAll (value) {
      const detailChildren = this.currentFiles.detailChildren
      this.currentCheckedList = []
      if (detailChildren && detailChildren.length > 0) {
        this.currentCheckedList = []
        detailChildren.forEach(item => {
          item.checked = value
          if (value) {
            this.currentCheckedList.push(item.id)
          }
        })
      }
    },
    handleBeforeUpload() {
      const self = this
      this.loading = true
      if (this.beforeUpload) {
        if (this.beforeUpload()) {
          return true
        } else {
          this.loading = false
          return false
        }
      } else {
        this.loading = true
        return true
      }
    },
    handleOnerror () {
      this.loading = false
      this.getFileDetail();
    },
     // 图片上传成功之后重新请求数据
    handleUploadSuccess(response, file, fileLis){
      this.loading = false
      this.getFileDetail();
    },
    handleDownload(fileItem){
      const fileName = fileItem.fileName + '.' + fileItem.fileExt
      this.$http({
        url: fileItem.realFileUrl,
        responseType: 'blob',
      }).then((res) => {
      this.download(res.data, fileName)
      })
    },
    handleDelete(item) {
      this.$confirm('是否删除此文件?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.$http({
          url: '/oss/api/fids/deleteFile/' + item.id,
          method: 'post'
        }).then((res) => {
          if (this.currentCheckedList.length > 0) {
            for (let index = 0; index < this.currentCheckedList.length; index++) {
              const element = this.currentCheckedList[index];
              if (element === item.id) {
                this.currentCheckedList.splice(index, 1)
                break
              }
            }
          }
          this.getFileDetail();
        })
      });
    },
    handleDeleteBatch () {
      if (this.currentCheckedList.length > 0) {
        this.$confirm('是否删除选中文件?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          this.$http({
            url: '/oss/api/fids/deleteFileByIds',
            method: 'post',
            data: this.currentCheckedList
          }).then((res) => {
            this.currentCheckedList = []
            this.getFileDetail();
          })
        });
      } else {
        this.$message({
          type: 'warning',
          message: '当前无选中数据'
        })
      }
      
    },
    download (blob, name) {
      const a = document.createElement('a');
      const url = window.URL.createObjectURL(blob);
      a.href = url;
      a.download = name
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a)
    },
    handleDownloadBatch () {
      if (this.currentCheckedList.length > 0) {
        if (this.currentCheckedList.length === this.currentFiles.detailChildren.length) {
          this.downloadFullZip()
        } else {
          this.downloadBatch()
        }
      } else {
        this.$message({
          type: 'warning',
          message: '当前无选中数据'
        })
      }
    },
    downloadBatch() {
      const length = this.currentCheckedList.length
      const zipName = this.currentFiles.sourceName + `(${length}).zip`
      this.$http({
        url: '/oss/api/fids/download-zip',
        method: 'post',
        data: this.currentCheckedList,
        responseType: 'blob',
      }).then((res) => {
        this.download(res.data, zipName)
      })
    },
    downloadFullZip() {
      const fileName = this.currentFiles.name + '.zip'
      this.$http({
        url: '/oss/api/fids/download-zip/' + this.currentFiles.id,
        responseType: 'blob',
      }).then((res) => {
        this.download(res.data, fileName)
      })
    },
    // 获取附件详细
    getFileDetail(){
      if(this.viewer){
        this.viewer.destroy();
      }
      let params = {
        businessModel: this.businessModel,
        businessKey: this.businessPk,
        businessScene:this.businessScene
      };
      return this.$http({
        url: '/oss/api/fids/file-detail-by-business',
        method: 'get',
        params: params
      }).then((res) => {
        //categorys 一级标题,
        // files 二级标题
        // fileItems 文件明细
        this.categorys = res.data.categorys;
        this.files = res.data.files;
        this.fileItems = res.data.fileItems;
        this.formatArray();
        this.getCurrentFiles(this.files)
      }).catch((res) => {
        this.$message({
          type: 'error',
          message: '请求附件详情出错'
        });
      });
    },
    getCurrentFiles (files) {
      if (files && files.length > 0 && this.currentFiles && this.currentFiles.id) {
        for (let index = 0; index < files.length; index++) {
          const element = files[index];
          if (element.id === this.currentFiles.id) {
            this.currentFiles = element
            break
          }
        }
      }
    },
    // 格式化当前模板需要使用到的数据格式
    formatArray(){
      // 构建对应小类别的文件详细
      this.files.forEach((item) => {
        // let showDisagreeUpload = false;
        // let realShowDisagreeUpload = false;
        let agree = 0;
        let disAgree = 0;
        item.detailChildren = [];
        item.icon = 'document'
        item.checked = false
        if(item.sampleId){
          item.exampleImgUrl = '/oss/api/fids/sample/'+item.sampleId;
        } else {
          item.exampleImgUrl = null;
        }

        this.fileItems.forEach((childItem) => {
          childItem.thumbFileUrl = '/oss/api/fids/download-thumb/'+childItem.id;
          childItem.realFileUrl = '/oss/api/fids/download/'+childItem.id;
          childItem.approveDone = true;
          childItem.approveAgree = false;
          // childItem.showDisagreeUpload = false;
          if(childItem.auditStatus === 'new'){
            childItem.showItemDelete = true;
            childItem.stateMessage = "未审批";
            childItem.stateDisAgree = false;
            childItem.stateAgree = false;
            childItem.approveDone = false;
          } else if(childItem.auditStatus === 'qualified'){
            childItem.showItemDelete = false;
            childItem.stateMessage = "审批通过";
            childItem.stateAgree = true; // 控制是否显示审批通过颜色
            childItem.stateDisAgree = false; // 控制是否显示审批未通过颜色
            childItem.approveAgree = true;
          } else if(childItem.auditStatus === 'unqualified'){
            childItem.showItemDelete = false;
            childItem.stateMessage = "审批未通过";
            childItem.stateDisAgree = true;
            childItem.stateAgree = false;
            // if(this.showDisagreeUpload){
            //   childItem.showDisagreeUpload = true;
            // }
          } else {
            childItem.showItemDelete = true;
            childItem.stateMessage = "未审批";
            childItem.stateDisAgree = false;
            childItem.stateAgree = false;
            childItem.approveDone = false;
          }
          if(childItem.ruFileId === item.id){
           
            item.detailChildren.push(childItem);
            childItem.filesTypeName = item.name;
            if(childItem.auditStatus === 'unqualified'){
              disAgree++;
            } else {
              agree++
            }
            // realShowDisagreeUpload = childItem.showDisagreeUpload || showDisagreeUpload;
          }
        });
        item.agree = agree;
        item.disAgree = disAgree;
        item.sourceName = item.name
        item.name = item.name + `(${item.detailChildren.length})`
        if (item.detailChildren <= 0) {
          delete item.detailChildren
        }
        // if(agree < item.children.length){
        //   realShowDisagreeUpload = true;
        // } else {
        //   realShowDisagreeUpload = false;
        // }
        // item.showDisagreeUpload = realShowDisagreeUpload;
      });
      // 判断当前已上传的图片是否已超出显示
      this.files.forEach((item) => {
        let fileItemsLenegth = item.agree;
        if (item.quantity.indexOf('+') > -1) {
          item.fileCountMessage = '需要上传最少' + parseInt(item.quantity, 0) + '份资料';
          item.approveAgreeNumber = parseInt(item.quantity, 0);
          item.showItemUpload = true;
          if (fileItemsLenegth >= parseInt(item.quantity.substring(0, 1), 0)) {
            this.$set(item, 'isAready', true);
          } else {
            this.$set(item, 'isAready', false);
          }
          if (parseInt(item.quantity.substring(0, 1), 0) !== 0) {
            item.required = true;
          } else {
            item.required = false;
          }
        } else if (item.quantity.indexOf('-') > -1) {
          let maxLength = parseInt(item.quantity.substring(0, 1), 0);
          item.approveAgreeNumber = 0;
          item.fileCountMessage = '需要上传最多' + parseInt(item.quantity, 0) + '份资料';
          if (fileItemsLenegth < maxLength) {
            item.showItemUpload = true;
          } else {
            item.showItemUpload = false;
          }
          item.isAready = true;
          item.required = false;
        } else if (item.quantity.indexOf('~') > -1) {
          let minLength = parseInt(item.quantity.substring(0, 1), 0);
          let maxLength = parseInt(item.quantity.substring(2), 0);
          item.approveAgreeNumber = minLength;
          item.fileCountMessage = "需要上传最少"+ minLength +"份资料"+",最多"+ maxLength +"份资料";
          if(fileItemsLenegth < maxLength){
            item.showItemUpload = true;
          } else {
            item.showItemUpload =false;
          }
          if(fileItemsLenegth >= minLength){
            item.isAready = true;
          } else {
            item.isAready = false;
          }
          item.required = true;
        } else {
          let length = parseInt(item.quantity, 0);
          item.approveAgreeNumber = length;
          item.fileCountMessage = "需要上传"+ length +"份资料";
          if(fileItemsLenegth < length){
            item.showItemUpload = true;
            item.isAready = false;
          } else {
            item.isAready = true;
            item.showItemUpload = false;
          }
          item.required = true;
        }
      });
      this.categorys.forEach((item) => {
        item.children = [];
        item.icon = 'folder-opened'
        this.files.forEach((childItem) => {
          if(item.id === childItem.ruCategoryId){
            item.children.push(childItem);
          }
        });
        if (item.children.length <= 0) {
          delete item.children
        }
      });
    },
    removeContainer (id) {
      if (!id) {
        document.body.removeChild(document.getElementById('aos-files-' + this.currentContainerId))
      } else if (this.currentContainerId && this.currentContainerId !== id) {
        document.body.removeChild(document.getElementById('aos-files-' + this.currentContainerId))
      }
    },
    createImgList (list, id) {
      const container = document.createElement('div')
      container.id = 'aos-files-' + id
      container.style.position = 'absolute'
      container.style.top = '-10000px'
      container.style.left = '-10000px'
      if (list && list.length > 0) {
        list.forEach(item =>{
          if (this.imgFileTypeList.includes(item.fileExt.toLowerCase())) {
            const imgItem = document.createElement('img')
            imgItem.src = item.thumbFileUrl
            imgItem.alt = item.fileName
            imgItem.title = item.fileName
            container.appendChild(imgItem)
          }
        })
      }
      document.body.append(container)
      return container
    },
    handleNodeClick (data) {
      this.currentFiles = data
      this.currentCheckedList = []
      this.checkedAll = false
    }
  }
}
</script>

<style>

</style>