<!--
 * @Description: Mongo文件列表面板组件
 * @Author: laoliu sunhuihong
 * @Date: 2022-07-31 16:43:52
 * @LastEditTime: 2024-06-11 12:53:05
-->
<template>
  <div class="body-mongo-file ">
    <!-- 过滤条件 -->
    <el-row class="head-line" :gutter="0" type="flex" justify="space-between" align="middle">
      <el-col :span="8" style="text-align: left;">
        <span class="search-title label-style">文件名：</span>
        <el-input v-model="filterParams.fileNameOrExtendsionName" clearable size="small" 
          placeholder="请输入文件名" style="width: 240px;" />
      </el-col>
      <el-col :span="8" style="text-align: left;">
        <span class="search-title">文件大小：</span>
        <el-input v-model="filterParams.startFileSize" clearable size="small" 
          placeholder="大于等于" style="width: 100px;" />
        <span class="search-title">&emsp;至&emsp;</span>
        <el-input v-model="filterParams.endFileSize" clearable size="small" 
          placeholder="小于等于" style="width: 100px;" />
      </el-col>
      <el-col :span="8" style="text-align: right;">
        <span class="search-title">表→字段：</span>
        <el-input v-model="curTableField" size="small" placeholder="从以下列表中选择" style="width: 240px;"
          clearable @change="changeCurTableField"/>&emsp;
        <el-button type="text" size="small" @click="handleShowTable">
          {{showTable ? '收起列表' : '展开列表'}}
        </el-button>
      </el-col>
    </el-row>
    <el-row v-if="showTable" class="head-line" :gutter="0" type="flex" justify="space-between" align="middle">
      <el-col :span="24" style="text-align: right;">
        <table-ref-list :tableList="mongoReferencesList"
          @handle-select="handleSelectReferencesItem"/>
      </el-col>
    </el-row>
    <el-row class="head-line" :gutter="0" type="flex" justify="space-between" align="middle">
      <el-col :span="8" style="text-align: left;">
        <span class="search-title label-style">原始文件名：</span>
        <el-input v-model="filterParams.originalName" clearable size="small" 
          placeholder="请输入原始文件名" style="width: 240px;" />
      </el-col>
      <el-col :span="16" style="text-align: right;">
        <el-button @click="handleQuery" size="small" type="primary" icon="el-icon-search">查 询</el-button>
      </el-col>
    </el-row>
    <div class="hr-line"></div>

    <!-- 文件列表 -->
    <el-table :data="fileList" :header-cell-style="{'background-color': '#EFF5FA'}"
      :row-style="{'cursor': 'pointer'}" @row-click="handleRowSelect" 
      style="margin-top: 20px; width: 100%; border: 1px solid #f0f0f0;">
      <el-table-column prop="mongo.filename" label="文件名" min-width="22%"></el-table-column>
      <el-table-column prop="mime" label="MIME类型" min-width="13%">
        <template slot-scope="scope">{{scope.row.mime ? scope.row.mime : '- -'}}</template>
      </el-table-column>
      <el-table-column prop="lengthStr" label="大小" min-width="12%">
        <template slot-scope="scope">
          <span v-if="scope.row.aboveLength" style="color: red;">{{scope.row.lengthStr}}</span>
          <span v-else>{{scope.row.lengthStr}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="mongo.uploadDate" label="创建时间" min-width="17%"></el-table-column>
      <el-table-column prop="refState" label="引用情况" min-width="23%"></el-table-column>
      <el-table-column label="操作" min-width="13%">
        <template slot-scope="scope">
          <el-button style="margin-left: 0;" v-for="(item, index) in scope.row.functionMeunList" 
            :key="index" type="text" size="small">
            <a class="dowload-button" v-if="item == '下载'" :href="calcImgUrl(scope.row.mongo.filename)" download>
              下载
            </a>
            <el-upload v-if="item == '替换'" multiple accept="image/jpeg,image/jpg,image/png" action="" 
              :show-file-list="false" :auto-upload="false" ref="replaceMongoFile" 
              :on-change="file => handleReplaceMongoFile(file, scope.row)">
              <el-button type="text" size="small" style="margin-left: 0;">替换</el-button>
              <el-divider direction="vertical"></el-divider>
            </el-upload>
            <el-button v-if="item !== '下载' && item !== '替换'" @click="handleClick(item, scope.row)" 
              type="text" size="small" style="margin-left: 0;">
              {{item}}
            </el-button>
            <span  v-show="index < (scope.row.functionMeunList.length-1) && item !== '替换'">
              <el-divider direction="vertical"></el-divider>
            </span>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-row class="foot-line">
      <el-pagination background @size-change="handlePageSize" @current-change="handleCurPage" 
        :current-page="filterParams.page" :page-sizes="pageSizes" :page-size="filterParams.pageSize" 
        layout="total, prev, pager, next, sizes, jumper" :total="totalNumber" />
    </el-row>
    
    <!-- Mongo文件详情 -->
    <file-details-dialog :visible="showFileDetailsDialog" :filename="filename" 
      @close-dialog="handleCloseDialog"/>
  </div>
</template>

<script>
import FileDetailsDialog from './FileDetailsDialog.vue'
import TableRefList from './TableRefList.vue'

export default {
  name: 'MongoFileMng',

  components: {
    'file-details-dialog': FileDetailsDialog,
    'table-ref-list': TableRefList
  },

  data() {
    return {
      // 过滤查询相关变量 
      filterParams: {
        page: 1,
        pageSize: 30
      },
      pageSizes: [10, 30, 50, 100],
      totalNumber: 0,
      
      fileList: [],//Mongo文件列表
      
      filename: '',//文件名
      showFileDetailsDialog: false,//是否显示Mongo文件详情Dialog

      curTableField: '',//表→字段绑定值
      mongoReferencesList: [],//过滤条件表/字段下拉选择列表
      showTable: false,//是否显示表→字段列表
    }
  },

  computed: {
     calcImgUrl() {
		  return function(filename) {
		  	return this.commonUtil.fillUrlArgments(this.commonUrl.URL_DOWNLOAD_MONGO_FILE, filename);
		  }	
		}
  },
  
  methods: {
    async initData() {
      this.mongoReferencesList = await this.getFilterDo();
      await this.listMongoFile();
    },

    //获取过滤条件（表引用信息列表）
    getFilterDo() {
      return new Promise((resolve) => {
        this.appAxios("GET", this.commonUrl.URL_GET_MONGO_FILE_FILTER_DO).then(result => {
          if (result != null) {
            resolve(result.data);
          }
        })
      })
    },

    //获取Mongo文件列表
    listMongoFile() {
      return new Promise((resolve) => {
        this.appAxios("GET", this.commonUrl.URL_PAGE_MONGO_FILES, this.filterParams).then(result => {
          if (result != null) {
            this.fileList = result.data || [];
            this.totalNumber = result.totalNumber;
            resolve();
          }
        })
      })
    },

    //操作按钮点击
    handleClick(item, row) {
      if (item == "删除") {
        this.handleDelete(row.mongo.filename);
      }
    },

    //更新替换指定文件
    handleReplaceMongoFile(file, row) {
      let isTypeOk = (file.raw.type == 'image/jpeg' || file.raw.type === 'image/png' || file.raw.type == 'image/jpg');
      let fileSize = file.size / 1024;
      let maxSize =  row.mongo.metadata.maxSize;
      let isOvermaxSize = parseInt(fileSize) < parseInt(maxSize);
      if (!isTypeOk) {
        this.$message.error('上传头像图片只能是JPG或PNG格式!');
        return;
      }
      if (!isOvermaxSize) {
        this.$message.error('上传的图片大小不能超过' + maxSize + '!');
        return;
      }
      this.uploadMongoFile(file, row.mongo.filename);
    },

    uploadMongoFile(file, filename) {
      let formData = new FormData();
      formData.append('file', file.raw);
      let url = this.commonUtil.fillUrlArgments(this.commonUrl.URL_REPLACE_MONGOFILE, filename);
      this.appAxios("PUT", url, formData, this.commonConst.CNTYPE_FORM_DATA).then(result => {
        if (result != null) {
          this.listMongoFile();
          this.$message.success('替换成功!');
        }
      })
    },

    //删除指定文件
    handleDelete(filename) {
      this.$confirm('删除后将无法恢复，确认删除?', '文件删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
				this.deleteMongoFile(filename);
			});
    },

    deleteMongoFile(filename) {
      let url = this.commonUtil.fillUrlArgments(this.commonUrl.URL_DELETE_MONGO_FILE, filename);
      this.appAxios("DELETE", url).then(result => {
        if (result != null) {
          this.listMongoFile();
        }
      })
    },

    handleRowSelect(row, col, _event) {
      if (col.label == '操作') return;
      this.filename = row.mongo.filename;
      this.showFileDetailsDialog = true;
    },

    //展开列表/收起列表
    handleShowTable() {
      this.showTable = !this.showTable;
    },

    //选择表字段数据
    handleSelectReferencesItem(item) {
      this.curTableField = item.tableName + '→' + item.fieldName;
      this.filterParams.refTable = item.tableName;
      this.filterParams.refField = item.fieldName;
    },

    //清空表/字段数据
    changeCurTableField(value) {
      if (value == '') {
        this.filterParams.refTable = null;
        this.filterParams.refField = null;
      }
    },

    //搜索
    handleQuery() {
      this.filterParams.page = 1;
      this.listMongoFile();
    },
    
    //关闭详情dialog
    handleCloseDialog() {
      this.showFileDetailsDialog = false;
      this.listMongoFile();
    },

    handlePageSize(val) {
      this.filterParams.pageSize = val;
      this.listMongoFile();
    },

    handleCurPage(curPage) {
      this.filterParams.page = curPage;
      this.listMongoFile();
    }
  },

  mounted() {
    this.initData();
  }
}
</script>

<style scoped>
.body-mongo-file {
  margin: 19px 40px;
  text-align: center;
  border: solid 0px;
}

.head-line {
  margin-bottom: 19px;
  text-align: right;
  border: solid 0px;
}

.search-title {
  color: #657180;
  font-size: 14px;
}

.label-style {
  display: inline-block;
  text-align: right;
  width: 90px;
}

.hr-line {
	height: 10px;
	background-color: #f0f0f0;
}

.foot-line {
  margin-top: 20px;
  text-align: right;
  border: solid 0px;
}

.dowload-button {
  text-decoration: none;
  color: #409EFF;
}
</style>