<template>
  <div class="app-uploader" v-loading="loading" elemeur-loading-text="服务器受理中...">
    <Panel title="资源检索" class="flex-1" v-if="allowSearch">
      <template slot="buttons">
        <el-button class="blue" @click="queryFiles" icon="el-icon-fa-search">查询</el-button>
        <el-button class="yellow" @click="resetQuery" icon="el-icon-fa-reply-all">重置</el-button>
      </template>
      <el-form :model="pageTable.param" ref="queryForm">
        <el-row>
          <el-col :lg='4' :sm='12'>
            <el-form-item label="文件名称" prop="fileName">
              <el-input v-model="pageTable.param.fileName"/>
            </el-form-item>
          </el-col>
          <el-col :lg='4' :sm='12'>
            <el-form-item label="文件类别" prop="fileType">
              <el-select placeholder="请选择" v-sys-code="'fileType'" v-model="pageTable.param.fileType" clearable>
                <el-option v-for="item in sysCode.fileType" :key="item.key" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg='4' :sm='12'>
            <el-form-item label="开始时间(上传)" prop="starTime">
              <el-date-picker v-model="pageTable.param.starTime" type="datetime" placeholder="选择开始时间"/>
            </el-form-item>
          </el-col>
          <el-col :lg='4' :sm='12'>
            <el-form-item label="结束时间(上传)" prop="endTime">
              <el-date-picker v-model="pageTable.param.endTime" type="datetime" placeholder="选择结束时间"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </Panel>

    <Panel title="资源列表" class="flex-1">

      <template slot="buttons">
        <el-button class="blue" @click="saveUpload" icon="el-icon-fa-save" v-if="allowUpload">全部保存</el-button>
        <el-button class="blue" @click="queryFiles" icon="el-icon-fa-refresh" >刷新</el-button>
      </template>

      <el-alert style='margin-bottom:10px;' title="文件名带有红色的(*),说明此时文件处于临时状态并没有生效，请点击“全部保存”按钮！" type="warning"/>

      <el-table border :data="pageTable.data"
                element-loading-spinner="el-icon-loading"
                v-loading="pageTable.isLoading"
                element-loading-text="数据加载中"
                height="300px"
                max-height="300px"
                ref="table">
        <el-table-column label="操作"  width="140" align="center">
          <template slot-scope="scope">
            <el-button v-if="allowTrash " icon="el-icon-fa-trash" class="red" @click="deleteUpload(scope.$index,scope.row)">删除</el-button>
            <el-button v-if="allowUpload" :disabled="scope.row.state==='1'" icon="el-icon-fa-check" class="blue" @click="saveFile(scope.$index,scope.row)">保存</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="filename" label="文件名" show-overflow-tooltip sortable>
          <template slot-scope="scope">
            <span class="font-red" v-if="scope.row.state!=='1'">&nbsp;*&nbsp;</span>
            <span @click="downloadOrViewFile(scope.row)" class="file-title">
              <i :class="icon(scope.row)"></i>
              {{ scope.row.filename }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="filesize" label="文件大小" width="100" align="right" :formatter="fileSizeFormat"/>
        <el-table-column prop="crtime" label="上传时间" :formatter="formatterDate" width='100'/>
        <el-table-column prop="filetype" label="文件类型" width='80'/>
        <el-table-column prop="mediatype" label="MediaType" width='120' show-overflow-tooltip/>

      </el-table>
      <el-pagination background :page-size.sync="pageTable.size" :current-page.sync="pageTable.curr" :total="pageTable.total"/>
    </Panel>


    <Panel title="待上传列表" class="flex-1" v-if="allowUpload">
      <template slot="buttons">
        <div style="float: right;">
          <el-upload style='display: inline-block;margin-right: 3px;' :on-error="fileUploadError" :on-change="fileUploadChange"
                     :show-file-list="false" :accept="accept" multiple :data="data" ref="upload"
                     :action="uploadPath" :auto-upload="false" :on-success='uploadSuccess'>
            <el-button class="blue" icon="el-icon-tickets">选择文件</el-button>
          </el-upload>
          <el-button class="blue" icon="el-icon-fa-cloud-upload" @click="submitUpload">全部上传</el-button>
          <el-button class="yellow" icon="el-icon-fa-trash" @click="clear">清空列表</el-button>
        </div>
      </template>
      <el-table hideTitle style="min-height:100px;" :data="fileList" border row-key="uid" stripe highlight-current-row>
        <el-table-column label="操作"   width="200" align="center">
          <template slot-scope="scope">
            <el-button class="blue" icon="el-icon-fa-cloud-upload" :disabled="scope.row.status==='fail'" @click="handleUpload(scope.$index,scope.row)">上传</el-button>
            <el-button class="red" icon="el-icon-fa-trash" @click="handleRemove(scope.$index,scope.row)">删除</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="文件名" width="180" show-overflow-tooltip/>
        <el-table-column prop="size" label="文件大小" width="80" align="right" :formatter="fileSizeFormat"/>
        <el-table-column label="进度">
          <template slot-scope="scope">
            <el-progress style="line-height:unset;" :text-inside="true" :stroke-width="14"
                         :percentage="parseInt(scope.row.percentage)"
                         :status="(scope.row && scope.row.status==='fail')? 'exception' : ''"/>
          </template>
        </el-table-column>
      </el-table>
    </Panel>
  </div>
</template>
<script>
import FilesAPI from "@/api/base/sysm/FilesAPI";
import config from "@/config";
import PageTable from "@/libs/PageTable";

export default {
  name:'Uploader',
  props: {
    uuid: {type: String, required: true},
    module: String,
    accept: String,
    allowSearch: {type: Boolean, default: false},
    allowTrash: {type: Boolean, default: false},
    allowUpload: {type: Boolean, default: false}
  },
  data() {
    return {
      pageTable: new PageTable({
        autoLoad: false,
        doLoad: FilesAPI.list,
        param: {uuid:this.uuid},
        log: false
      }),
      loading: false,
      uploadPath: config.ajaxUrl + "/sys/file/upload",
      successFiles: [],
      fileList: [],
      queryForm: {
        starTime: null,
        endTime: null,
        fileType: null,
        fileName: null
      }
    };
  },
  computed: {
    data() {
      return {
        module: this.module,
        uuid: this.uuid
      };
    }
  },
  mounted() {
    this.queryFiles();
  },
  watch: {
    uuid() {
      if (!this.readonly) {
        this.$refs.upload.clearFiles();
      }
      this.queryFiles();
    }
  },
  methods: {
    icon(row) {
      const ext = row.filetype;
      if (["jpg", "png", "bmp"].indexOf(ext) !== -1) {
        return 'font-blue el-icon-fa-file-image-o'
      }
      if (["pdf"].indexOf(ext) !== -1) {
        return 'font-red el-icon-fa-file-pdf-o'
      }
      if (["doc", "docx"].indexOf(ext) !== -1) {
        return 'font-blue el-icon-fa-file-word-o'
      }
      if (["xls", "xlsx"].indexOf(ext) !== -1) {
        return 'font-green el-icon-fa-file-excel-o'
      }
      if (["ppt", "pptx"].indexOf(ext) !== -1) {
        return 'font-red el-icon-fa-file-powerpoint-o'
      }
      if (["zip", "rar", "tar", "gz"].indexOf(ext) !== -1) {
        return 'font-green el-icon-fa-file-zip-o'
      }
      return 'font-dark el-icon-fa-file-o'
    },
    queryFiles() {
      this.pageTable.handleLoad();
    },
    fileSizeFormat(row, column, cellValue) {
      if (cellValue === 0) return "0 B";
      let k = 1000;
      let sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
      let i = Math.floor(Math.log(cellValue) / Math.log(k));
      return (cellValue / Math.pow(k, i)).toPrecision(3) + " " + sizes[i];
    },
    // 手动触发文件上传
    submitUpload() {
      this.$refs.upload.submit();
    },
    //  清空上传
    clear() {
      this.$refs.upload.clearFiles();
    },
    // 文件上传成功回调函数
    uploadSuccess(response, file, fileList) {
      if (response.respCode === "000000" && response.fileInfo) {
        let keys = Object.keys(response.fileInfo);
        let tem = {};
        keys.forEach((value, index) => {
          let t = value.toLowerCase();
          tem[t] = response.fileInfo[value];
        });
        this.successFiles.splice(0, 0, tem);
        this.$refs.upload.handleRemove(file);
        this.pageTable.handleLoad();
      } else {
        this.$message.error("上传失败!");
      }
    },
    handleUpload(index, file) {
      this.$refs.upload.$refs["upload-inner"].upload(file.raw);
    },
    handleRemove(index, file) {
      this.$refs.upload.handleRemove(file);
    },
    fileUploadError(e, file, fileList) {
      fileList.push(file);
      this.$message.error("有文件上传失败!");
    },
    // 添加文件
    fileUploadChange(file, fileList) {
      this.fileList = fileList;
    },
    async downloadOrViewFile(data) {
      const ext = data.filetype;
      if (["jpg", "png", "bmp", "pdf"].indexOf(ext) !== -1) {
        window.open(config.ajaxUrl + '/sys/file/view?uuid=' + data.uuid);
      } else {
        await FilesAPI.download(data.uuid)
      }
    },
    // 下载文件
    async downloadFile(data) {
      await FilesAPI.download(data.uuid)
    },
    // 删除上传的企业附件
    async deleteUpload(index, data) {
      try {
        await this.$confirm('您确定要删除该文件么?', '重要提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        this.loading = true;
        await FilesAPI.delete(data.uuid);
        this.queryFiles();
      } finally {
        this.loading = false;
      }
    },
    async saveUpload() {
      this.loading = true;
      try {
        await FilesAPI.saveAll(this.uuid)
        this.$emit("save", this.successFiles);
        this.queryFiles();
      } finally {
        this.loading = false;
      }
    },
    async saveFile(index, data) {
      this.loading = true;
      try {
        FilesAPI.save(data.uuid);
        this.loading = false;
        data.state = "1";
      } finally {
        this.loading = false;
      }
    },
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.queryForm.starTime = null;
      this.queryForm.endTime = null;
      this.picker = [];
    }
  }
};
</script>

<style>
.app-uploader .file-title:hover {
  cursor: pointer;
  color: #1ba39c;
}
</style>