<template>
  <div>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px" @submit.native.prevent>
      <el-form-item label="文件名" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <uploadFiles :get-list="getList" :key="new Date().getTime()" :parent-id="queryParams.parentId.toString()" :fileUrl="fileUrl"/>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-folder-add"
          size="small"
          @click="handleAdd"
          v-hasPermi="['dataCenter:dataSetBasicFile:add']"
        >新建文件夹</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-download"
          size="small"
          :disabled="multiple"
          @click="downloadFile"
          v-hasPermi="['dataCenter:dataSetBasicFile:download']"
        >下载</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-share"
          size="small"
          @click="sharedFilesByIds"
          :disabled="multiple"
          v-hasPermi="['dataCenter:dataSetBasicFile:edit']"
        >共享</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-position"
          size="small"
          @click="handlePaste"
          :disabled="single"
          getFileTerr
          v-hasPermi="['dataCenter:dataSetBasicFile:edit']"
        >移动</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-document-copy"
          size="small"
          @click="handleCopy"
          :disabled="single"
          v-hasPermi="['dataCenter:dataSetBasicFile:add']"
        >复制</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="small"
          @click="handleDelete"
          :disabled="multiple"
          v-hasPermi="['dataCenter:dataSetBasicFile:remove']"
        >删除</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="small"
          @click="renameName"
          :disabled="single"
          v-hasPermi="['dataCenter:dataSetBasicFile:edit']"
        >重命名</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div style="display: flex;flex-direction: row;
      align-items: center;">
      <span><i @click="popFromStack" class="el-icon-arrow-left"></i></span>
      <el-breadcrumb  separator="/" class="app-container">
        <el-breadcrumb-item ><a @click="folderName = []"> 我的样本库</a></el-breadcrumb-item>
        <el-breadcrumb-item  v-for="item in folderName" :key="item.fileId"><a @click="removeAfter(item)">{{item.fileName}}</a></el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-table v-loading="loading" size="medium" :data="fileList" :height="tableHeight" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="名称" prop="fileName" min-width="200">
        <template slot-scope="scope">
          <!-- 根据条件生成点击事件 -->
          <span
            :class="{ 'link-type': scope.row.isDirectory === '1' }"
            @click="scope.row.isDirectory === '1' ? pushToStack(scope.row) : null"
          >
            {{ scope.row.fileName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" prop="fileUrl" min-width="120">
        <template slot-scope="scope">
          <span>
            {{scope.row.isDirectory === '1'?'文件夹':scope.row.fileName.split('.').pop()}}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="文件大小" align="center" prop="fileSize" min-width="120">
        <template slot-scope="scope">
          <span>{{scope.row.isDirectory === '1'?'-':scope.row.fileSize < 1024 * 1024?(scope.row.fileSize/1024).toFixed(2)+'KB':(scope.row.fileSize/1024/1024).toFixed(2)+'MB'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="标签类型" align="center" min-width="120" />
      <el-table-column label="共享状态" align="center" prop="isPublic" min-width="120">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isPublic" active-value="1" inactive-value="0"
                     @change="changeIsPublic(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" min-width="120" >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:file:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:file:remove']"
          >删除</el-button>
        </template>
      </el-table-column>-->
    </el-table>

    <pagination
      style="background-color: transparent"
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改标注人员和角色关联对话框 -->
    <el-dialog title="添加" :visible.sync="open" width="500px"  append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="位置" prop="fileUrl">
          <el-input v-model="this.url" :disabled="true" readonly />
        </el-form-item>
        <el-form-item label="名称" prop="fileName">
          <el-input v-model="form.fileName" maxlength="20" placeholder="请输入名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="copyOpen" width="500px"  append-to-body>
      <el-form ref="copyForm" :model="copyForm" :rules="copyRules" label-width="80px">
        <el-form-item label="位置" prop="parentId">
          <treeselect
            v-model="copyForm.parentId"
            :options="fileTree"
            :normalizer="normalizer"
            :show-count="true"
            :searchable="true"
            placeholder="选择上级菜单"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCopy">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="pasteOpen" width="500px"  append-to-body>
      <el-form ref="pasteForm" :model="pasteForm" :rules="pasteRules" label-width="80px">
        <el-form-item label="位置" prop="parentId">
          <treeselect
            v-model="pasteForm.parentId"
            :options="fileTree"
            :normalizer="normalizer"
            :show-count="true"
            :searchable="true"
            placeholder="选择上级菜单"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPaste">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="renameOpen" width="500px"  append-to-body>
      <el-form ref="renameForm" :model="renameForm" :rules="renameRules" label-width="80px">
        <el-form-item label="旧的名称" prop="oldName">
          <el-input v-model="renameForm.oldName"  :disabled="true" readonly />
        </el-form-item>
        <el-form-item label="新的名称" prop="newName">
          <el-input v-model="renameForm.newName" maxlength="20" placeholder="请输入名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitName">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listFile, getFile, delFile, addFile, updateFile,sharedFilesByIds,getFileTerr,changeIsPublic } from "@/api/dataCenter/basicFile";
import uploadFiles from '../child/uploadFiles.vue'
import {downloadFileInChunks} from '@/utils/download'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import Treeselect from '@riophae/vue-treeselect'
export default {
  name: "File",
  components:{ Treeselect, uploadFiles},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      tableHeight: 0,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文件基础表格数据
      fileList: [],
      //上传文件集合
      file:[],
      //父类id
      parentId:0,

      fileTree:undefined,
      //文件夹名称
      folderName:[],
      //文件路径
      fileUrl:"",
      url:"我的样本库",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      copyOpen:false,
      renameOpen:false,
      pasteOpen:false,
      open: false,
      // 新建文件夹弹出层
      addOpen:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileName: null,
      },
      // 表单参数
      form: {},
      copyForm:{},
      renameForm:{},
      pasteForm:{},
      renameRules:{
        newName: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
      },
      copyRules: {
        parentId: [
          { required: true, message: "位置不能为空", trigger: "blur" }
        ],
      },
      pasteRules:{
        parentId: [
          { required: true, message: "位置不能为空", trigger: "blur" }
        ],
      },
      // 表单校验
      rules: {
        fileName: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.updateTableHeight()

    // 监听窗口大小变化
    window.addEventListener("resize", this.updateTableHeight);
  },
  watch:{
      folderName(newVal, oldVal){
        this.parentId = newVal.length > 0 ? newVal[newVal.length - 1].fileId : 0;
        this.fileUrl = newVal.map(item => item.fileName).join("/");
        this.url = "我的样本库/" + this.fileUrl+(this.fileUrl?"/":"")
        this.getList();
      }
  },
  methods: {
    uploadFileId(res){
      console.log("file.vue",res)
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.fileId,
        label: node.fileName,
        children: node.children
      };
    },
    getFileTerr(fileId) {
      return getFileTerr(fileId).then(response => {
        this.fileTree = [];
        const menu = { fileId: 0, fileName: '主类目', children: [] };
        menu.children = this.handleTree(response.data, "fileId");
        this.fileTree.push(menu);
      })
    },
    updateTableHeight() {
      // 设置表格高度为窗口高度减去其他元素高度
      const headerHeight = 400; // 头部高度，可以调整
      const footerHeight = 90; // 底部高度，可以调整
      this.tableHeight = window.innerHeight - headerHeight - footerHeight;
    },
    // 入栈操作：添加元素到栈顶
    pushToStack(item) {
      if (item) {           // 确保输入框不为空
        this.folderName.push(item); // 入栈
      }
    },
    // 出栈操作：移除栈顶元素
    popFromStack() {
      if (this.folderName.length > 0) {
        this.folderName.pop();
      }
    },
    // 移除指定对象后面的所有元素
    removeAfter(item) {
      const index = this.folderName.findIndex(element => element.fileId === item.fileId);
      if (index !== -1) {
        // 使用 splice 方法移除索引之后的元素
        this.folderName.splice(index + 1);
      }
    },
    /** 查询文件基础列表 */
    getList() {
      this.loading = true;
      this.queryParams.parentId=this.parentId;
      console.log(this.queryParams)
      listFile(this.queryParams).then(response => {
        this.fileList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.pasteOpen = false;
      this.copyOpen =false;
      this.open = false;
      this.renameOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        fileId: null,
        parentId: null,
        ancestors: null,
        fileName: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fileId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    sharedFilesByIds(row){
      const fileId = row.fileId || this.ids
      sharedFilesByIds(fileId).then(response => {
        this.getList();
      });
    },
    // 用户状态修改
    changeIsPublic(row) {
      let text = row.isPublic === '0' ? '不共享' : '共享'
      this.$modal.confirm('确认要' + text + '吗？').then(function() {
        return changeIsPublic(row.fileId, row.isPublic)
      }).then(() => {
        this.$modal.msgSuccess('操作成功')
      }).catch(function() {
        row.isPublic = row.isPublic === '0' ? '1' : '0'
      })
    },
    renameName(row){
      const fileId = row.fileId || this.ids
      getFile(fileId).then(response => {
        this.renameForm = response.data;
        this.renameForm.oldName= this.renameForm.fileName.split('.')[0];
        this.renameOpen = true;
        this.title = "重命名";
      });
    },
    submitName(){
      this.$refs["renameForm"].validate(valid => {
        if (valid) {
          const { newName, fileName } = this.renameForm;
          // 检查是否存在后缀名
          const extension = fileName.includes('.') ? fileName.split('.').pop() : '';
          const fullFileName = `${newName}${extension ? '.' + extension : ''}`;
          let data = {
            fileId: this.renameForm.fileId,
            fileName : fullFileName,
          }
          updateFile(data).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.renameOpen = false;
            this.getList();
          });
        }
      })
    },
    handleCopy(row){
      const fileId = row.fileId || this.ids
      this.getFileTerr(fileId)
      getFile(fileId).then(response => {
        this.copyForm = response.data;
        this.copyOpen = true;
        this.title = "复制文件";
      });
    },
    submitCopy(){
      this.$refs["copyForm"].validate(valid => {
        if (valid) {
          let data = {
            fileId: this.copyForm.fileId,
            parentId : this.copyForm.parentId,
          }
          updateFile(data).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.copyOpen = false;
            this.getList();
          });
        }
      })
    },
    handlePaste(row){
      const fileId = row.fileId || this.ids
      this.getFileTerr(fileId)
      getFile(fileId).then(response => {
        this.pasteForm = response.data;
        this.pasteOpen = true;
        this.title = "移动文件";
      });
    },
    submitPaste(){
      this.$refs["pasteForm"].validate(valid => {
        if (valid) {
          let data = {
            fileId: this.pasteForm.fileId,
            parentId : this.pasteForm.parentId,
          }
          updateFile(data).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.pasteOpen = false;
            this.getList();
          });
        }
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加文件基础";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const fileId = row.fileId || this.ids
      getFile(fileId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改文件基础";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.fileUrl = this.fileUrl;
      this.form.parentId = this.parentId;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.fileId != null) {
            updateFile(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFile(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const fileIds = row.fileId || this.ids;
      this.$modal.confirm('是否确认删除数据项？').then(function() {
        return delFile(fileIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    downloadFile(row) {
      const fileIds = row.fileId || this.ids;
      if (Array.isArray(fileIds)) {
        if (fileIds.length > 1) {
          this.download('/ai/dataSetBasicFile/download/'+fileIds,{},`${new Date().getTime()}.zip`,{timeout: 600000})
        }else {
          const result = this.fileList.find(item => item.fileId === fileIds[0]);
          console.log(result);
          if (result.isDirectory==="1"){
            console.log(result);
            this.download('/ai/dataSetBasicFile/download/'+fileIds,{},result.fileName+'.zip',{timeout: 600000})
          }else {
            downloadFileInChunks('/ai/dataSetBasicFile/download/'+fileIds,result.fileName,result.fileSize)
          }
        }
      }else{
        this.download('/ai/dataSetBasicFile/download/'+fileIds,{},`${new Date().getTime()}.zip`,{timeout: 600000})
      }

    }
  }
};
</script>
