<template>
  <div :id="filesId" class="aos-files">
    <div v-for="item in categorys" :key="item.id">
      <h2 class="aos-files-first-name">{{item.name}}<el-button v-if="showApprove" class="aos-file-approval-all" type="text" @click="handleApprovalAll">批量通过</el-button></h2>
      <div class="aos-files-fileItem" v-for="children in item.children" :key="children.id">
        <h3>
          <i class="el-icon-star-on aos-file-required" v-if="children.required"></i>{{children.name}}<span class="aos-file-count">{{children.fileCountMessage}}</span>
          <el-popover
            placement="bottom"
            :title="children.name + '示例图片'"
            width="200"
            trigger="click">
            <div>
              <div title="点击预览大图" style="cursor:pointer;background-size:200px 200px;height:200px;width:200px" @click="handleViewExample(children.exampleImgUrl)" v-show="children.exampleImgUrl" :style="{'background-image': 'url(' + children.exampleImgUrl +')'}"></div>  
              <span v-show="!children.exampleImgUrl">暂无示例图片</span>
            </div>
            <span v-show="children.exampleImgUrl" slot="reference" class="aos-file-example">示例图片</span>
          </el-popover>
        </h3>
        <div>
          <div :id="'aos-files-img-box-' + children.id" class="aos-files-container" v-if="children.children.length > 0">
            <div class="aos-files-img" v-for="fileItem in children.children" :key="fileItem.id">
              <div v-if="fileItem.fileExt !== 'pdf'" class="aos-files-img-box" @click="handleViewerImg(children)">
                <img style="cursor:pointer;" :src="fileItem.thumbFileUrl" :alt="fileItem.fileName" :name="fileItem.fileName" :title="fileItem.fileName"/>
              </div>
              <div v-if="fileItem.fileExt === 'pdf'" class="aos-files-img-box" @click="handleViewerPdf(fileItem)">
                <i class="el-icon-pdf" style="cursor:pointer;font-size:50px;" :title="fileItem.fileName" :name="fileItem.fileName"/>
              </div>
              <!-- showThumb ? fileItem.thumbFileUrl : fileItem.realFileUrl -->
              <div class="aos-files-img-delete" v-if="showOperate">
                <span v-if="showApprove" class="aos-files-img-disAgree clearfix" @click="handleDisAgree(fileItem)">不通过</span>
                <i v-if="showDelete && fileItem.showItemDelete" class="el-icon-delete" title="删除" @click="handleDeleteImg(fileItem)"></i>
                <a style="width:12px;margin-left: 8px;" title="下载" :href="fileItem.realFileUrl" :download="fileItem.fileName +'.'+ fileItem.fileExt" @click="handleDownload(fileItem)">
                  <i class="el-icon-download"></i>
                </a>
                <span v-if="showApprove" class="aos-files-img-agree clearfix" @click="handleAgree(fileItem)">通过</span>
              </div>
              <div class="aos-files-img-state" :class="{'is-agree': fileItem.stateAgree,'is-disAgree': fileItem.stateDisAgree }">
                <span>{{fileItem.stateMessage}}</span>
                <el-tooltip class="aos-files-img-tooltip" v-if="fileItem.stateDisAgree" effect="light" :content="fileItem.auditExplain ? fileItem.auditExplain : ''" placement="right">
                  <i class="el-icon-warning"></i>
                </el-tooltip>
              </div>
              <div class="aos-files-img-remark" v-if="showApprove && fileItem.remark" :title="fileItem.remark">
                {{fileItem.remark}}
              </div>
            </div>
            <el-upload
              v-if="children.showItemUpload && showUpload"
              class="aos-files-upload"
              drag
              multiple
              :show-file-list="false"
              :action="'/oss/api/fids/upload?ruFileId=' + children.id"
              :on-success="handleUploadSuccess">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<span class="aos-files-upload-button">点击上传</span></div>
              <!-- <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div> -->
            </el-upload>
          </div>
          <el-upload
            v-else-if="children.showItemUpload && showUpload"
            class="aos-files-upload"
            drag
            multiple
            :show-file-list="false"
            :action="'/oss/api/fids/upload?ruFileId=' + children.id"
            :on-success="handleUploadSuccess">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<span class="aos-files-upload-button">点击上传</span></div>
            <!-- <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div> -->
          </el-upload>
        </div>
      </div>
    </div>
    <el-dialog
      :title="messageTitle"
      :visible.sync="showMessage"
      :append-to-body="true"
      width="30%">
      <div>
        <el-form ref="message" label-width="80px">
          <el-form-item label="意见">
            <el-input v-model="message"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer">
        <el-button @click="handleMeaageCancel">取 消</el-button>
        <el-button type="primary" @click="handleMeaageConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible" :append-to-body="true" title="示例图片预览">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
    <transition>
      <div v-if="showImgViewer" class="aos-img-viewer"></div>
    </transition>
  </div>
</template>
<script>
import 'viewerjs-optimize/dist/viewer-optimize.css';
import Viewer from 'viewerjs-optimize';
export default {
  name: 'AosFiles',
  data(){
    return {
      categorys: '', // 文件大类
      files: '', // 文件大类所属的小类别
      fileItems: '', // 文件小类别对应的详细
      messageTitle: '审批意见', // 对应的意见审批意见框的名称
      agree: false, // 判断当前是同意还是不同意,true为同意
      currentFileItem: '', // 当前点击的图片的信息
      showMessage: false, // 是否显示意见框
      message: '', // 意见字段
      viewer: '',
      showImgViewer: false, // 是否显示可拖拽框
      showThumb: true, // 是否显示缩略图
      dialogVisible: false,
      dialogImageUrl: ''
    }
  },
  props: {
    filesId: {
      type: [String,Number],
      default: 'aos-files'
    },
    // 业务类型
    businessModel: {
      type: String,
      required: true
    },
    // 业务主键
    businessPk: {
      type: String,
      required: true
    },
    // 业务场景
    businessScene: {
      type: String,
      default: ''
    },
    // 是否显示操作按钮,
    showOperate: {
      type: Boolean,
      default: true
    },
    // 是否显示上传
    showUpload: {
      type: Boolean,
      default: true
    },
    // 是否显示审批按钮
    showApprove: {
      type: Boolean,
      default: true
    },
    // 是否显示删除按钮
    showDelete: {
      type: Boolean,
      default: true
    },
    // 审批不通过是否显示上传,默认不显示
    showDisagreeUpload: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    handleViewExample(url){
      this.dialogVisible = true;
      this.dialogImageUrl = url;
    },
    /**
     * 批量审批
     */
    handleApprovalAll(){
      let params = {
        businessKey: this.businessPk,
        businessModel: this.businessModel,
        businessScene: this.businessScene
      };
      this.$http({
        url: '/oss/api/fids/qualifiedBat',
        method: 'post',
        params: params
      }).then(() => {
        this.$message({
          type: 'success',
          message: '批量审批成功'
        });
        this.getFileDetail();
      }).catch(() => {
        this.$message({
          type: 'error',
          message:'批量审批出错'
        });
      });
    },
    // 获取附件详细
    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: '请求附件详情出错'
        });
      });
    },
    // 获取附件详细
    getFileDetailSync(callback) {
      const that = this;
      if (typeof callback !== 'function' && window.Promise) {
        window.Promise((resolve, reject) => {
          callback = function(valid) {
            valid ? resolve(valid) : reject(valid);
          };
        });
      }
      if(this.viewer){
        this.viewer.destroy();
      }
      window.Promise.all([that.getFileDetail()]).then(() => {
        callback(true);
      });
    },
    // 格式化当前模板需要使用到的数据格式
    formatArray(){
      // 构建对应小类别的文件详细
      this.files.forEach((item) => {
        // let showDisagreeUpload = false;
        // let realShowDisagreeUpload = false;
        let agree = 0;
        let disAgree = 0;
        item.children = [];
        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.children.push(childItem);
            childItem.filesTypeName = item.name;
            if(childItem.auditStatus === 'unqualified'){
              disAgree++;
            } else {
              agree++
            }
            // realShowDisagreeUpload = childItem.showDisagreeUpload || showDisagreeUpload;
          }
        });
        item.agree = agree;
        item.disAgree = disAgree;
        // 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 = [];
        this.files.forEach((childItem) => {
          if(item.id === childItem.ruCategoryId){
            item.children.push(childItem);
          }
        });
      });
    },
    // 删除图片
    handleDeleteImg(fileItems){
      if(fileItems.auditStatus !== 'new'){
        this.$message({
          type: 'error',
          message: '当前图片已经审批过,不允许删除'
        });
        return;
      }
      this.$confirm('是否删除此图片?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
      }).then(() => {
        this.$http({
          url: '/oss/api/fids/deleteFile/' + fileItems.id,
          method: 'delete'
        }).then((res) => {
          this.getFileDetail();
        }).catch(() => {
          this.$message({
            type: 'error',
            message: '删除图片出错'
          });
        });
      });
    },
    handleDownload(fileItem){
      let a = document.createElement('a');
      if(typeof a.download === 'undefined'){
        let newUrl = window.location.protocol + "//" + window.location.host + fileItem.realFileUrl;
        window.open(newUrl);
      }
    },
    //审批通过
    handleAgree(fileItems){
      this.messageTitle = '通过';
      this.agree = true;
      // this.showMessage = true;
      this.currentFileItem = JSON.parse(JSON.stringify(fileItems));
      this.handleMeaageConfirm();
    },
    // 审批不通过
    handleDisAgree(fileItems){
      this.messageTitle = '不通过';
      this.agree = false;
      this.showMessage = true;
      this.currentFileItem = JSON.parse(JSON.stringify(fileItems));
    },
    // 审批意见取消
    handleMeaageCancel(fileItems){
      this.showMessage = false;
    },
    // 审批意见提交
    handleMeaageConfirm(fileItems){
      let url;
      let submitData = '';
      if(this.agree){
        url = '/oss/api/fids/audit/'+ this.currentFileItem.id + '/qualified'
      } else {
        url = '/oss/api/fids/audit/' + this.currentFileItem.id + '/unqualified';
        submitData = {
          auditExplain: this.message
        }
      }
      this.$http({
        url: url,
        method: 'post',
        params: submitData
      }).then((res) => {
        if(this.agree){
          this.$message({
            type: 'success',
            message: '同意操作成功'
          });
        } else {
          this.$message({
            type: 'success',
            message: '不同意操作成功'
          });
          this.showMessage = false;
        }
        this.getFileDetail();
      }).catch((res) => {
        if(this.agree){
          this.$message({
            type: 'error',
            message: '同意操作出错'
          });
        } else {
          this.$message({
            type: 'error',
            message: '不同意操作出错'
          })
        }
      });
    },
    // 图片上传成功之后重新请求数据
    handleUploadSuccess(response, file, fileLis){
      this.getFileDetail();
    },
    // 大图预览
    handleViewerImg(children){
      this.showImgViewer = true;
      // this.showThumb = false; //启用新的viewerjs
      // this.showThumb = true;
      // let itemId = 'aos-files-img-box-' + children.id;
      if (this.viewer) {
        this.viewer.destroy();
        this.viewer = null;
      }
      // document.getElementById('aos-files').addEventListener('hidden',function(){
      //   this.showThumb = true;
      // });
      this.viewer = new Viewer(document.getElementById(this.filesId), {
        // inline: true,
        // viewed() {
        //   viewer.zoomTo(1);
        // },
        // container: '#aos-img-viewer',
        className: 'aos-img-viewer-container ' + this.filesId
      });
    },
    // PDF 预览
    handleViewerPdf(fileItem){
      let newUrl = window.location.protocol + "//" + window.location.host + "/trd/pdfViewer/web/viewer.html?file="+fileItem.realFileUrl;
      window.open(newUrl);
    },
    // 校验必传的图片
    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);
    },
    // 检查是否审批
    checkApproveAll(callback) {
      if (typeof callback !== 'function' && window.Promise) {
        window.Promise((res, rej) =>{
          callback = function(valid, message) {
            valid ? res(valid, message) : rej(valid, message);
          };
        });
      }
      let length = this.fileItems.length;
      let valid = true;
      let message = '';
      for(let i = 0;i< length;i++){
        if(!this.fileItems[i].approveDone){
          // this.$message({
          //   type:'error',
          //   message: this.fileItems[i].filesTypeName + '资料未审批'
          // });
          valid = false;
          message = message + this.fileItems[i].filesTypeName + ',';
        }
      }
      callback(valid,message);
    },
    // 检查是否所以必填项都审批通过
    checkApproveAgree(callback) {
      if (typeof callback !== 'function' && window.Promise) {
        window.Promise((res, rej) =>{
          callback = function(valid, message) {
            valid ? res(valid, message) : rej(valid, message);
          };
        });
      }
      // let length = this.fileItems.length;
      let valid = true;
      for(let i = 0;i< this.files.length;i++){
        if(this.files[i].approveAgreeNumber > 0){
          let doneNumber = 0;
          this.files[i].children.forEach((item) => {
            if(item.auditStatus === 'qualified'){
              doneNumber += 1;
            }
          });
          if(doneNumber < this.files[i].approveAgreeNumber){
            valid = false;
            break;
          }
        }
      }
      callback(valid);
    },
    // 校验驳回后是否重新上传了图片
    checkRejectApproveUpload(callback) {
      // let promise;
      if (typeof callback !== 'function' && window.Promise) {
        window.Promise((res, rej) => {
          callback = function(valid) {
            valid ? res(valid) : rej(valid);
          };
        });
      }
      // let length = this.fileItems.length;P
      let valid = true;
      for(let i = 0;i< this.files.length;i++){
        if(this.files[i].approveAgreeNumber > 0){
          let doneNumber = 0;
          this.files[i].children.forEach((item) => {
            if(item.auditStatus !== 'unqualified'){
              doneNumber += 1;
            }
          });
          if(doneNumber < this.files[i].approveAgreeNumber){
            valid = false;
            break;
          }
        }
      }
      callback(valid);
    }
  },
  created() {
    this.getFileDetail();
  },
  destroyed() {
    if(this.viewer){
      this.viewer.destroy();
      this.viewer = null;
      document.getElementById(this.filesId).removeEventListener('hidden');
    }
  },
  watch: {
    showDisagreeUpload: function(){
      this.getFileDetail();
    },
    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()
      }
    }
  }
}
</script>
