<template>
  <div class="aos-files-tree">
    <el-tree
      default-expand-all
      :data="categorys"
      :props="defaultProps"
      @node-click="handleNodeClick">
      <span class="aos-files-tree__tree-item" slot-scope="{ node, data }">
          <span :class="{'aos-files-tree__required': data.required}" :title="node.label">{{ node.label }}</span>
        </span>
    </el-tree>
  </div>
</template>

<script>
import Viewer from 'viewerjs-optimize';
import { PopupManager } from 'aos-element/src/utils/popup';
export default {
  name: 'AosFilesTree',
  props: {
    // 业务类型
    businessModel: {
      type: String,
      required: true
    },
    // 业务主键
    businessPk: {
      type: String,
      required: true
    },
    // 业务场景
    businessScene: {
      type: String,
      default: ''
    },
  },
  data () {
    return {
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      viewer: '',
      categorys: [],
      files: '',
      fileItems: '',
      currentContainerId: '',
      currentContainer: '',
      imgFileTypeList: ['png','jpg','jpeg','gif','tif','bmp', 'svg', 'webp']
    }
  },
  created () {
    this.getFileDetail()
  },
  beforeDestroy () {
    if (this.viewer) {
      this.viewer = null
    }
    this.removeContainer()
  },
  methods: {
    // 获取附件详细
    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();
      }).catch((res) => {
        this.$message({
          type: 'error',
          message: '请求附件详情出错'
        });
      });
    },
    // 格式化当前模板需要使用到的数据格式
    formatArray(){
      // 构建对应小类别的文件详细
      this.files.forEach((item) => {
        // let showDisagreeUpload = false;
        // let realShowDisagreeUpload = false;
        let agree = 0;
        let disAgree = 0;
        item.detailChildren = [];
        item.icon = 'document'
        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.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)) {
            item.isAready = true;
          } else {
            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) {
      const dom = document.getElementById('aos-files-tree-' + this.currentContainerId)
      if (!id) {
        if (dom) {
          document.body.removeChild(dom)
        }
      } else if (this.currentContainerId && this.currentContainerId !== id) {
        if (dom) {
          document.body.removeChild(dom)
        }
      }
    },
    createImgList (list, id) {
      const container = document.createElement('div')
      container.id = 'aos-files-tree-' + 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)) {
            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) {
      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-tree-' + data.id), {
        className: 'aos-img-viewer-container ' + ('aos-files-tree-' + data.id),
        zIndex: PopupManager.nextZIndex() + 101
      });
      container.children[0].click()
    }
  }
}
</script>

<style>

</style>