<template>
  <div>
    <el-dialog title="目录位置" :visible.sync="open" width="40%" append-to-body @close="cancel" :close-on-click-modal="false">
      <el-row :gutter="10" class="mb8">
        <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="20">
          <el-input placeholder="请输入内容" readonly :disabled="true" v-model="folder">
            <el-button slot="prepend" type="success" icon="el-icon-arrow-left"   @click="popFromStack"></el-button>
          </el-input>
        </el-col>
      </el-row>

      <el-table ref="table" v-loading="loading" size="small" :data="fileList" :height="tableHeight"  @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="名称" prop="fileName" min-width="100">
          <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="100">
          <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="100">
          <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" prop="createTime" min-width="100" >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </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="addOpen" 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="folder" :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="addSubmitForm">确 定</el-button>
          <el-button @click="addCancel">取 消</el-button>
        </div>
      </el-dialog>

      <template #footer>
        <el-button type="primary" :disabled="multiple" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listFile,addFile } from '@/api/dataCenter/basicFile'

export default {
  props: {
    open: {
      type: Boolean,
      default: false,
      required: true,
    },
    folderType:{
      type: Number,
      default: 0,
      required: true,
    }
  },
  computed: {
    isOpen: {
      get() {
        return this.open;
      },
      set(value) {
        this.$emit('update:open', value);
      },
    },
  },
  data() {
    return {
      folder:"我的样本库/",
      folderName:[],
      total:0,
      parentId:0,
      loading:true,
      fileList:[],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      tableHeight: 0,
      // 非多个禁用
      multiple: true,
      addOpen:false,
      queryParams:{
        pageNum: 1,
        pageSize: 10,
      },
      form:{},
      rules:{}
    };
  },
  created() {
    this.getList();
    this.updateTableHeight()
    // 监听窗口大小变化
    window.addEventListener("resize", this.updateTableHeight);
  },
  method(){
    this.getList();
  },
  watch:{
    folderName(newVal, oldVal){
      this.parentId = newVal.length > 0 ? newVal[newVal.length - 1].fileId : 0;
      this.fileUrl = newVal.map(item => item.fileName).join("/");
      this.folder = "我的样本库/" + this.fileUrl+(this.fileUrl?"/":"")
      this.getList();
    },
    open(newVal, oldVal){
      if (newVal){
        this.getList()
        this.updateTableHeight()
        // 监听窗口大小变化
        window.addEventListener("resize", this.updateTableHeight);
      }
    }
  },
  methods: {
    getList() {
      this.loading = true;
      this.queryParams.parentId=this.parentId;
      listFile(this.queryParams).then(response => {
        this.fileList = response.rows;
        this.total = response.total;
        this.loading = false;
        // 根据逻辑重新设置选中项
        const defaultSelection = []; // 自定义默认选中项
        this.handleSelectionChange(defaultSelection);
      });
    },
    // 入栈操作：添加元素到栈顶
    pushToStack(item) {
      if (item) {           // 确保输入框不为空
        this.folderName.push(item); // 入栈
      }
    },
    // 出栈操作：移除栈顶元素
    popFromStack() {
      if (this.folderName.length > 0) {
        this.folderName.pop();
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      if (selection.length > 1) {
        // 如果选中多个项，强制只保留第一个选中项
        this.$nextTick(() => {
          // 清空所有选中的项
          this.$refs.table.clearSelection();
          // 重新选中第一个项
          this.$refs.table.toggleRowSelection(selection[1], true);
        });
      }
      this.ids = selection.map(item => item.fileId)
      const isDirectory = selection.map(item => item.isDirectory)
      this.single = selection.length===1
      // multiple 的逻辑
      if (this.parentId === 0 && selection.length !== 1) {
        // parentId 为 0 且未单选时，multiple 强制为 true
        this.multiple = true;
      } else if (this.parentId !== 0 && selection.length !== 1) {
        // parentId 不为 0 且未单选时，multiple 强制为 false
        this.multiple = false;
      } else {
        // 单选情况下，根据 isDirectory 是否包含 '0' 判断
        this.multiple = isDirectory.includes('0');
      }
    },
    updateTableHeight() {
      // 设置表格高度为窗口高度减去其他元素高度
      const headerHeight = 400; // 头部高度，可以调整
      const footerHeight = 90; // 底部高度，可以调整
      this.tableHeight = window.innerHeight - headerHeight - footerHeight;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.addOpen = true;
      this.title = "创建文件夹";
    },
    addSubmitForm(){
      this.form.fileUrl = this.folder;
      this.form.parentId = this.parentId;
      this.$refs["form"].validate(valid => {
        if (valid) {
          addFile(this.form).then(response => {
            this.$modal.msgSuccess("创建成功成功");
            this.addOpen = false;
            this.getList();
          });
        }
      })
    },
    // 数据提交
    submitForm() {
      let result = null;
      // 判断是否有选中项
      if (this.ids && this.ids.length > 0) {
        result = this.fileList.find(item => item.fileId === this.ids[0]);
      }
      const data = {
        folder: result ? this.folder + result.fileName : this.folder,
        fileId: result ? result.fileId : this.parentId,
        folderType: this.folderType,
      };
      this.$emit('update-data', data); // 触发事件并传递数据
      this.cancel(); // 取消操作
    },
    addCancel(){
      this.addOpen = false;
    },
    // 取消按钮
    cancel() {
      this.addOpen=false;
      this.reset();
      this.$emit('dialog-cancel'); // 通知父组件
    },
    // 表单重置
    reset() {
      this.folder ="我的样本库/";
      this.folderName=[];
      this.total=0;
      this.parentId=0;
      this.loading=true;
      this.fileList=[];
      // 选中数组
      this.ids=[];
      // 非单个禁用
      this.single=true;
      // 非多个禁用
      this.multiple=true;
      this.queryParams={
        pageNum:1,
        pageSize:10,
      };
      this.form={};
      this.rules={}
    },
  },
};
</script>

<style scoped lang="scss">
/* 样式按需定义 */
/* 隐藏el-table的全选框 */
.el-table .el-checkbox__original {
  display: none;
}

.el-dialog {
  transition: opacity 0.3s ease;
}

</style>
