<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="6" :sm="8">
            <a-form-item label="文件名称">
              <j-input placeholder="请输入文件名称" v-model="queryParam.fileName"></j-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item label="文件类型">
              <a-select placeholder="请选择文件类型" default-value="" v-model="queryParam.searchFileType">
                <a-select-option :value="item.id" v-for="(item, index) in fileTypes" :key="index">
                  {{item.name}}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item label="上传时间">
              <a-range-picker v-model="queryParam.createTimeRange"
                              format="YYYY-MM-DD"
                              :placeholder="['开始时间', '结束时间']"
                              @change="onCreateTimeChange" />
            </a-form-item>
          </a-col>

          <a-col :md="6" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">

      <a-upload
        name="file"
        :multiple="false"
        :action="minioUploadAction"
        :headers="tokenHeader"
        :showUploadList="false"
        :beforeUpload="beforeUpload"
        @change="handleChange">
        <a-button>
          <a-icon type="upload"/>
          文件上传
        </a-button>
      </a-upload>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay" @click="handleMenuClick">
          <a-menu-item key="1">
            <a-icon type="delete" @click="batchDel"/>
            删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作
          <a-icon type="down"/>
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a
          style="font-weight: 600">{{selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
          @change="handleTableChange">

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical"/>
          <a @click="ossDelete(record.id)">删除</a>
        </span>

        <template v-slot:fileNameSlot="text, record, index">
          <a :href="handlePreview(record)" target="_blank">{{record.fileName}}</a>
        </template>

        <template v-slot:thumbnailSlot="text, record, index">
          <div class="anty-img-wrap">
            <a-avatar shape="square" :src="record.url" icon="file"/>
          </div>
        </template>

      </a-table>
    </div>
    <!-- table区域-end -->

    <oss-file-model ref="modalForm" @ok="modalFormOk"></oss-file-model>

  </a-card>
</template>

<script>
  import {JeecgListMixin} from '@/mixins/JeecgListMixin'
  let Base64 = require('js-base64').Base64
  import {putAction,getFileAccessHttpUrl} from '@/api/manage';
  import ossFileModel from './modules/OSSFileModal'
  import {filterObj} from "@/utils/util";

  export default {
    name: "OSSFileList",
    mixins: [JeecgListMixin],
    components: {
      ossFileModel
    },
    data() {
      return {
        description: '文件列表',
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: "center",
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '文件名称',
            dataIndex: 'fileName',
            scopedSlots: { customRender: 'fileNameSlot' }
          },
          {
            title: '预览图',
            align: "center",
            dataIndex: 'thumbnail',
            scopedSlots: { customRender: 'thumbnailSlot' }
          },
          {
            title: '文件类型',
            dataIndex: 'searchFileType'
          },
          {
            title: '文件大小',
            dataIndex: 'fileSize',
            customRender: (text, record) => {
              let fileSize = text
              if (fileSize) {
                if (fileSize < 1024) {
                  return fileSize + "B"
                } else if (fileSize < 1048576) {
                  return (fileSize / 1024).toFixed(1) + "K"
                } else if (fileSize < 1073741824) {
                  return (fileSize / 1048576).toFixed(1)+ "M"
                } else {
                  return (fileSize / 1073741824).toFixed(1) + "G"
                }
              }
              return "0"
            }
          },
          {
            title: '上传时间',
            dataIndex: 'createTime'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: "center",
            scopedSlots: {customRender: 'action'},
          }
        ],
        url: {
          upload: "/sys/oss/file/upload",
          list: "/sys/oss/file/list",
          delete: "/sys/oss/file/delete",
          deleteBatch: "/sys/oss/file/deleteBatch",
          minioUpload: "/sys/upload/uploadMinio"
        },
        queryParam: {
          searchFileType: ""
        },
        fileTypes: [
          {"id":"","name":"所有"},
          {"id":"pdf","name":"pdf"},
          {"id":"image","name":"图片"},
          {"id":"word","name":"word"},
          {"id":"excel","name":"excel"},
          {"id":"ppt","name":"ppt"},
          {"id":"video","name":"视频"},
        ]
      }
    },
    computed: {
      uploadAction() {
        return window._CONFIG['domianURL'] + this.url.upload;
      },
      minioUploadAction() {
        return window._CONFIG['domianURL'] + this.url.minioUpload;
      },
    },
    methods: {
      getQueryParams(){
        // 高级查询器
        let sqp = {}
        let param = Object.assign(sqp, this.queryParam, this.isorter ,this.filters);

        param.field = this.getQueryField();
        param.pageNo = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize;
        delete param.createTimeRange; //范围参数不传递后台
        return filterObj(param);
      },
      onCreateTimeChange: function (value, dateString) {
        console.log(dateString[0],dateString[1]);
        this.queryParam.createTime_begin=dateString[0];
        this.queryParam.createTime_end=dateString[1];
      },
      beforeUpload(file) {
        var fileType = file.type;
        if (fileType === 'image') {
          if (fileType.indexOf('image') < 0) {
            this.$message.warning('请上传图片');
            return false;
          }
        } else if (fileType === 'file') {
          if (fileType.indexOf('image') >= 0) {
            this.$message.warning('请上传文件');
            return false;
          }
        }
        return true
      },
      handleChange(info) {
        if (info.file.status === 'done') {
          if (info.file.response.success) {
            this.loadData()
            this.$message.success(`${info.file.name} 上传成功!`);
          } else {
            this.$message.error(`${info.file.response.message}`);
          }
        } else if (info.file.status === 'error') {
          this.$message.error(`${info.file.response.message}`);
        }
      },
      ossDelete(id) {
        var that = this;
        that.$confirm({
          title: "确认删除",
          content: "是否删除选中文件?",
          onOk: function () {
            that.handleDelete(id)
          }
        });
      },
      handlePreview(record) {
        if (record && record.url) {
          let url = window._CONFIG['onlinePreviewDomainURL'] + '?url=' + encodeURIComponent(Base64.encode((record.url)))
          // window.open(url, '_blank')
          return url;
        }
      },
      handleMenuClick(e) {
        if (e.key == 1) {
          this.batchDel();
        }
      },
      getAvatarView(avatar) {
        return getFileAccessHttpUrl(avatar)
      },
    }
  }
</script>

<style scoped>
  @import '~@assets/less/common.less';
</style>
