<template>
  <div>
    <div>
      <div class="gva-search-box">
        <div>
          <el-form ref="searchForm" :inline="true" :model="searchInfo">
            <el-form-item label="归属任务">
              <el-select v-model="searchInfo.name" size="small" filterable>
                <el-option
                  v-for="item in taskOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="负责人">
              <el-select v-model="searchInfo.director_name" size="small">
                <el-option
                  v-for="item in directorOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                size="small"
                type="primary"
                icon="search"
                @click="onSubmit"
                >查询</el-button
              >
              <el-button size="small" icon="refresh" @click="onReset"
                >重置</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="gva-search-box" style="padding-bottom: 25px">
        <div>
          <el-button
            size="small"
            type="primary"
            icon="upload"
            @click="navToScript()"
            >上传文件</el-button
          >
          <el-button
            v-if="createButtonVisible"
            class="excel-btn"
            size="small"
            type="success"
            icon="plus"
            @click="switchCreateFolder()"
            >新建文件夹</el-button
          >
        </div>
      </div>
      <div class="gva-btn-list">
        <div class="row center">
          <el-breadcrumb :separator-icon="ArrowRight">
            <el-breadcrumb-item
              v-for="(breadcrumb, index) in breadcrumbList"
              :key="index"
            >
              <a @click="clickBreadcrumb(breadcrumb, index)">{{
                breadcrumb.name
              }}</a>
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
      </div>
      <div class="gva-table-box">
        <div class="video-container">
          <el-card shadow="hover">
            <div class="video-main">
              <ul class="list">
                <li v-if="files.length == 0" class="list-none">
                  <el-empty :image-size="100" description="暂无文件" />
                </li>
                <li
                  v-else
                  v-for="(file, index) in files"
                  :key="index"
                  :class="{ active: file.active }"
                  class="list-item"
                  @dblclick="dbClickOpenFile(file)"
                >
                  <el-dropdown
                    trigger="contextmenu"
                    :id="String(file.id)"
                    placement="bottom"
                    @command="handleCommand"
                    @visible-change="handleChange($event, String(file.id))"
                    ref="dropdownRef"
                  >
                    <div class="inner">
                      <img
                        :src="file.thumUrl ? file.thumUrl : defultThumUrl"
                        class="icon-thumb"
                      />
                      <div class="inner-info" v-if="file.isFile">
                        <p>
                          版本:<span style="font-size: 14px">{{
                            file.file_version
                          }}</span>
                        </p>
                      </div>

                      <!-- <i v-else class="icon-folder"></i> -->
                      <!-- <div v-show="file.resType > 0" class="hover-cover">
                      <span style="color: #fff">{{
                        file.size | sizeFilter
                      }}</span>
                    </div> -->
                    </div>

                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item
                          v-if="file.isFile == false"
                          :command="beforeHandleCommand('open', file)"
                          ><el-icon><Position /></el-icon>打开</el-dropdown-item
                        >
                        <el-dropdown-item
                          v-if="file.isFile"
                          :command="beforeHandleCommand('rename', file)"
                          ><el-icon><InfoFilled /></el-icon
                          >重命名</el-dropdown-item
                        >
                        <el-dropdown-item
                          v-if="file.isFile"
                          :command="beforeHandleCommand('getUrl', file)"
                          ><el-icon><Share /></el-icon
                          >获取链接</el-dropdown-item
                        >
                        <el-dropdown-item
                          v-if="file.isFile"
                          :command="beforeHandleCommand('download', file)"
                          ><el-icon><Download /></el-icon>下载</el-dropdown-item
                        >
                        <el-dropdown-item
                          v-if="file.isFile"
                          :command="beforeHandleCommand('delete', file)"
                          ><el-icon><DeleteFilled /></el-icon
                          >删除</el-dropdown-item
                        >
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                  <!-- <i
                    class="icon-file-selected"
                    @click="toggleSelect(file, file.id)"
                  ></i> -->
                  <div class="file-name">
                    <span :title="file.name">{{ file.name }}</span>
                  </div>
                </li>
              </ul>
            </div>
          </el-card>
        </div>
      </div>
    </div>
    <el-dialog
      title="文件上传界面"
      v-model="uploadVisible"
      :center="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="elForm2"
        :model="uploadForm"
        size="default"
        label-width="100px"
      >
        <el-form-item label="上传目录" prop="way">
          <el-col :span="20">
            <el-input
              v-model="uploadForm.way"
              placeholder="根目录"
              disabled
            ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="关联任务" prop="id">
          <el-col :span="20">
            <el-input
              v-model="uploadForm.task_id"
              placeholder="关联任务"
              disabled
            ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="任务名称" prop="name">
          <el-col :span="20">
            <el-input
              v-model="uploadForm.task_name"
              placeholder="任务名称"
              disabled
            ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="文件类型" prop="type">
          <el-col :span="20">
            <el-select
              v-model="uploadForm.type"
              placeholder="文件类型"
              :style="{ width: '100%' }"
              @change="selectChanged(uploadForm)"
            >
              <el-option
                v-for="item in fileTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="文件名称" prop="qiniuVersion">
          <el-col :span="20">
            <el-input
              v-model="uploadForm.fileName"
              placeholder="文件名称,选择文件后自动生成"
              disabled
              :style="{ width: '100%' }"
            ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item v-if="showVersion" label="更新版本" prop="qiniuVersion">
          <el-col :span="20">
            <el-input
              v-model="uploadForm.qiniuVersion"
              placeholder="版本号"
              disabled
              :style="{ width: '100%' }"
            ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item v-if="showUpload" label="选择文件" prop="qiniuAddress">
          <el-col :span="20">
            <el-upload
              :limit="1"
              action="http://upload-z2.qiniup.com"
              :data="qiniuData"
              drag
              :disabled="disabledUpload"
              :show-file-list="false"
              :http-request="uploadHttpRequest"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :on-progress="onProgress"
            >
              <div class="el-default" v-if="!progressFlag">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                  将文件拖到此处，或<em> 点击上传 </em>
                </div>
              </div>
              <el-progress
                type="circle"
                :percentage="progress"
                :stroke-width="15"
                style="margin-top: 20px"
                v-if="progressFlag"
              >
              </el-progress>
            </el-upload>
            <!-- 进度条 -->
            <!-- <el-progress
							v-if="progressFlag"
							:text-inside="true"
							:percentage="progress"
							:stroke-width="15"
							:status="status"
						></el-progress> -->
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button size="small" @click="cancelUp(uploadForm)"
            >取消上传</el-button
          >
          <!-- <el-button type="primary" size="small" @click="recordFile(uploadForm)"
						>确定上传</el-button
					> -->
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      v-model="fileFolderVisible"
      title="新建文件夹"
      width="50%"
      :close-on-press-escape="false"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <el-form
        v-if="fileFolderVisible"
        :inline="true"
        :model="formFolder"
        :rules="rules"
        label-position="left"
        label-width="100px"
      >
        <el-row :gutter="2">
          <el-col :span="24">
            <el-form-item label="文件夹类型" prop="folder_type">
              <!-- <el-select
              v-model="formFolder.folder_type"
              size="small"
              @change="changeFolderType"
            >
              <el-option label="游戏任务" value="0" />
              <el-option label="其他文件" value="1" />
            </el-select> -->
              <el-select
                v-model="formFolder.folder_type"
                placeholder="文件夹类型"
                :style="{ width: '100%' }"
                size="small"
                @change="changeFolderType"
              >
                <el-option
                  v-for="item in folderTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="2" v-if="taskFolderVisible">
          <el-col :span="24">
            <el-form-item label="任务名称" prop="task">
              <el-select
                v-model="formFolder.task"
                size="small"
                filterable
                @change="changeTask"
              >
                <el-option
                  v-for="item in taskOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="2">
          <el-col :span="24">
            <el-form-item label="文件夹名" prop="folder_name">
              <el-input
                v-model="formFolder.folder_name"
                :disabled="disabledFolderName"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="fileFolderVisible = false"
            >取 消</el-button
          >
          <el-button size="small" type="primary" @click="createFolder()"
            >确 定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "qiniuTransfer",
};
</script>

<script setup>
import {
  getAllTaskSimple,
  addFileFolder,
  getFolderFileList,
  getQiniuToken,
  getAllFileType,
  selectFolderMsg,
  queryVersionByType,
  addQiniuFile,
  deleteQiniuFile,
  deleteQiniuFileAndRecord,
  renameQiniuFileAndRecord,
  queryFolder,
} from "@/api/fileManager";
import { getDirectorList } from "@/api/responsiblePerson";
import { ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { ArrowRight } from "@element-plus/icons-vue";
// import { number } from "echarts";
import * as qiniu from "qiniu-js";
import defultThumUrlimage from '@/assets/defultThumUrl.svg'
// import { switchCase } from "@babel/types";

//===================
const fileFolderVisible = ref(false);
const taskFolderVisible = ref(false);
const createButtonVisible = ref(true);
const disabledFolderName = ref(false);
const formFolder = ref({
  folder_type: "0",
  folder_name: "",
  task: "",
  parentId: 0,
});
const taskOptions = ref();
const fileTypeOptions = ref([]);
const directorOptions = ref();
const currentParentId = ref(0);
const uploadVisible = ref(false);
const progressFlag = ref(false);
const progress = ref(0);
const cance = ref(false);
const disabledUpload = ref(false);
const uploadForm = ref({
  way: "",
  parentId: 0,
  parentName: "",
  task_id: 0,
  task_name: "",
  fileName: "",
  type: null,
  type_name: "",
  qiniuVersion: "",
  key: "",
  qiniuAddress: "",
  qiniuHash: "",
});
const folderTypeOptions = ref([]);
const dropdownRef = ref();
const activeItems = ref([]); // 选中激活的文件列表
const qiniuData = ref({
  key: "",
  token: "",
  cName: "",
}); //七牛上传时获取的服务器信息
const showVersion = ref(false);
const showUpload = ref(false);
const status = ref("exception");
//
async function switchCreateFolder() {
  if (breadcrumbList.value.length == 1) {
    folderTypeOptions.value = [
      { value: "0", label: "游戏任务" },
      // { value: "1", label: "其他文件" },
    ];
    formFolder.value.folder_type = "0";
    taskFolderVisible.value = true;
    disabledFolderName.value = true;
    formFolder.value.folder_name = "";
    formFolder.value.task = "";
  } else {
    folderTypeOptions.value = [
      // { value: "0", label: "游戏任务" },
      { value: "1", label: "其他文件" },
    ];
    formFolder.value.folder_type = "1";
    taskFolderVisible.value = false;
    disabledFolderName.value = false;
    formFolder.value.folder_name = "";
    formFolder.value.task = "";
  }
  formFolder.value.parentId =
    breadcrumbList.value[breadcrumbList.value.length - 1].id;
  if (fileFolderVisible.value == false) {
    fileFolderVisible.value = true;
  }
  if (formFolder.value.folder_type === "0") {
    taskFolderVisible.value = true;
    disabledFolderName.value = true;
  }
  const taskListRes = await getAllTaskSimple({
    page: 1,
    pageSize: 999,
  });
  let taskList = [];
  const data = taskListRes.data.list;
  data.forEach((e) => {
    taskList.push({
      value: e.task_id + "|" + e.task_name,
      label: e.task_id + "_" + e.task_name,
    });
  });
  taskOptions.value = taskList;
}
function changeFolderType(e) {
  if (e === "0") {
    taskFolderVisible.value = true;
    disabledFolderName.value = true;
    formFolder.value.folder_name = "";
    formFolder.value.task = "";
  } else {
    taskFolderVisible.value = false;
    disabledFolderName.value = false;
    formFolder.value.folder_name = "";
    formFolder.value.task = "";
  }
}
function changeTask(e) {
  formFolder.value.folder_name = e;
}
const createFolder = async () => {
  var task = formFolder.value.task;
  var taskArr = task.split("|");

  const addFormFolder = {
    name: formFolder.value.folder_name,
    task_id: Number(taskArr[0]),
    parent_id: Number(formFolder.value.parentId),
  };

  let res = await addFileFolder(addFormFolder);
  // console.log(res);
  if (res.code === 0) {
    ElMessage({
      type: "success",
      message: "文件夹创建成功!",
    });
    fileFolderVisible.value = false;
    currentParentId.value = res.data.id;
    breadcrumbList.value.push({ id: res.data.id, name: res.data.name });
    initMaterialPage(currentParentId.value);
  } else {
    ElMessage({
      type: "error",
      message: res.message,
    });
  }
};
//
// 跳转上传界面
async function navToScript() {
  if (breadcrumbList.value.length == 1) {
    ElMessage.warning("根目录不允许直接上传文件,请先选择进入文件夹!!");
    return;
  }
  uploadForm.value.parentId =
    breadcrumbList.value[breadcrumbList.value.length - 1].id;
  uploadForm.value.parentName =
    breadcrumbList.value[breadcrumbList.value.length - 1].name;
  uploadForm.value.way = "";
  breadcrumbList.value.forEach((e) => {
    uploadForm.value.way += e.name + ">";
  });
  // console.log(uploadForm.value.parentId);
  const folderInfo = await getParentTaskMsg(uploadForm.value.parentId);
  // console.log(folderInfo);
  if (folderInfo == "") {
    uploadForm.value.task_id = "";
    uploadForm.value.task_name = "";
  } else {
    uploadForm.value.task_id = folderInfo.task_id;
    uploadForm.value.task_name = folderInfo.task_name;
  }
  uploadVisible.value = true;
  cance.value = false;
  showVersion.value = false;
  showUpload.value = false;
  uploadForm.value.fileName = "";
  uploadForm.value.type = null;
  uploadForm.value.qiniuVersion = "";
  uploadForm.value.qiniuAddress = "";
  progressFlag.value = false;
  await getFileTypeOptions();
  disabledUpload.value = false;
  await getToken();
}
// 查询所有文件类型
async function getFileTypeOptions() {
  fileTypeOptions.value = [];
  const res = await getAllFileType();
  if (res.code === 0) {
    for (let i = 0; i < res.data.list.length; i++) {
      var temp = {
        typeId: res.data.list[i].id,
        value: i,
        label: res.data.list[i].name + res.data.list[i].describe,
        name: res.data.list[i].name,
        type: res.data.list[i].describe,
      };
      fileTypeOptions.value.push(temp);
    }
  }
}
//查询上传目录是否关联任务id并返回
async function getParentTaskMsg(id) {
  const res = await selectFolderMsg({ id: Number(id) });
  // console.log(res);
  if (res.msg == "获取成功") {
    return res.data.data;
  }
  return "";
}
const handleChange = (visible, id) => {
  if (!visible) return;

  dropdownRef.value.forEach((item) => {
    if (item.id == id) return;
    item.handleClose();
  });
};
/**
 * 动态设置Dropdown的command
 */
function beforeHandleCommand(flag, command) {
  // flag为传递的参数
  return {
    flag: flag,
    command: command,
  };
}
const handleCommand = (val) => {
  switch (val.flag) {
    case "open":
      dbClickOpenFile(val.command);
      break;
    case "download":
      downloadFile(val.command);
      break;
    case "delete":
      deleteFile(val.command);
      break;
    case "getUrl":
      getUrl(val.command);
      break;
    case "rename":
      rename(val.command);
      break;
    default:
      break;
  }
};
//文件重命名
async function rename(file) {
  ElMessageBox.prompt("请输入新的文件名", "重命名", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    inputPattern:
      /(?!((^(con)$)|^(con)\..*|(^(prn)$)|^(prn)\..*|(^(aux)$)|^(aux)\..*|(^(nul)$)|^(nul)\..*|(^(com)[1-9]$)|^(com)[1-9]\..*|(^(lpt)[1-9]$)|^(lpt)[1-9]\..*)|^\s+|.*\s$)(^[^\\\/\:\*\?\"\<\>\|]{1,255}$)/,
    inputErrorMessage: "不允许这样命名",
    inputValue: file.name,
  })
    .then(async ({ value }) => {
      const res = await renameQiniuFileAndRecord({
        id: file.id,
        file_name: file.name,
        file_name_new: value,
        qiniu_key: file.qiniu_key,
      });
      // console.log(res);
      if (res.code == 0) {
        ElMessage.success(res.msg);
        initMaterialPage(currentParentId.value);
      }
    })
    .catch(() => {
      // ElMessage({
      //   type: "info",
      //   message: "Input canceled",
      // });
    });
}
//获取下载链接
async function getUrl(file) {
  ElMessageBox.alert(
    "<strong>" + file.qiniu_address + "</strong>",
    "下载链接",
    {
      dangerouslyUseHTMLString: true,
      showClose: false,
    }
  );
}
//从七牛云删除文件并且清除数据库记录
async function deleteFile(file) {
  // console.log(file);
  ElMessageBox.confirm("确定删除此文件？", "警告", {
    type: "warning",
  })
    .then(async () => {
      const res = await deleteQiniuFileAndRecord({
        id: file.id,
        qiniu_key: file.qiniu_key,
      });
      if (res.code == 0) {
        ElMessage.success(res.msg);
        initMaterialPage(currentParentId.value);
      }
    })
    .catch(() => null);
}
//下载文件
async function downloadFile(file) {
  // console.log(file);
  // console.log(file.qiniu_address);
  // let url = window.URL.createObjectURL(new Blob([file.qiniu_address]));
  // let link = document.createElement("a");
  // link.style.display = "none";
  // link.href = url;
  // link.setAttribute("download", file.name); //指定下载后的文件名，防跳转
  // document.body.appendChild(link);
  // link.click();
  // // 释放内存
  // window.URL.revokeObjectURL(link.href);
  // 创建 a 标签
  const a = document.createElement("a");
  // 创建一个点击事件
  const event = new MouseEvent("click");
  // 将 a 的 download 属性设置为想要下载的名称
  a.download = file.name || "文件名称";
  // 将生成的 url 设置为 a.href 属性
  a.href = file.qiniu_address;
  // 打开新的窗口（如果是一个图片类型的文件，在浏览器打开新的标签页打开）
  // a.target = "_blank";
  // 实现触发生成的 a 标签
  a.dispatchEvent(event);
}
//获取七牛token
async function getToken() {
  const res = await getQiniuToken();
  if (res.code === 0) {
    qiniuData.value.token = res.data.token;
    qiniuData.value.cName = res.data.cName;
    // console.log(qiniuData);
  } else {
    ElMessageBox.alert(err, "提示", {
      confirmButtonText: "关闭",
    });
  }
}
async function selectChanged(aaa) {
  // 查询该类型对应最新版本号并+1
  const res = await queryVersionByType({
    task_id: aaa.task_id,
    file_type: fileTypeOptions.value[uploadForm.value.type].typeId,
  });
  // console.log(res);
  if (res.code == 0) {
    uploadForm.value.qiniuVersion = parseInt(res.data.fileVersion) + 1;
  } else {
  }
  showVersion.value = true;
  showUpload.value = true;
}
// 取消上传文件
async function cancelUp(aaa) {
  //中断文件传输
  cance.value = true;
  uploadVisible.value = false;
  // console.log(qiniuData.value.key);
  var qiniu_key = qiniuData.value.key;
  if (qiniu_key == "") {
    return;
  }
  //取消上传时从七牛云删除已上传的文件
  const res = await deleteQiniuFile({
    qiniu_key: qiniu_key,
  });
  // console.log(res);
  if (res.code == 0) {
    ElMessage.success(res.msg);
  }
}
//上传前处理
function beforeAvatarUpload(file) {
  progressFlag.value = false;
  const fileFirst = file.name.substring(0, file.name.lastIndexOf("."));
  const fileLast = file.name.substring(file.name.lastIndexOf(".") + 1);
  //
  const limitType = fileTypeOptions.value[uploadForm.value.type].type;
  let isALL = limitType.substring(limitType.lastIndexOf(".") + 1);
  if (isALL == "*") {
  } else if (fileLast == "" || isALL != fileLast) {
    ElMessageBox.alert("只能上传" + isALL + "格式的文件", "提示", {
      confirmButtonText: "关闭",
    });
    return false;
  }
  let folder =
    "shuyou/" +
    uploadForm.value.task_id +
    "|" +
    uploadForm.value.task_name +
    "/" +
    fileTypeOptions.value[uploadForm.value.type].name +
    "/" +
    fileFirst +
    "_" +
    new Date().getTime() +
    "." +
    fileLast;
  uploadForm.value.fileName =
    fileFirst + "_" + new Date().getTime() + "." + fileLast;
  qiniuData.value.key = folder;
  // console.log(folder);
  disabledUpload.value = true;
}
//确定上传,记录文件信息在数据库中
async function recordFile(aaa) {
  console.log(aaa);
  const params = {
    parent_id: aaa.parentId,
    task_id: aaa.task_id,
    file_version: aaa.qiniuVersion,
    qiniu_address: aaa.qiniuAddress,
    file_name: aaa.fileName,
    file_type: aaa.type,
    file_type_name: aaa.type_name,
    qiniu_hash: aaa.qiniuHash,
    qiniu_key: aaa.key,
  };
  let res = await addQiniuFile(params);
  if (res.code === 0) {
    uploadVisible.value = false;
    ElMessage.success("文件记录成功!!!");
  }
  cance.value = false;
  initMaterialPage(currentParentId.value);
}
//上传成功
function handleAvatarSuccess(res) {
  // console.log(res);
  // 七牛云对外域名qiniuData.value.cName
  const fileUrl = qiniuData.value.cName + res.key;
  const fileHash = res.hash;
  // console.log(fileUrl);
  uploadForm.value.key = res.key;
  uploadForm.value.qiniuAddress = fileUrl;
  uploadForm.value.qiniuHash = fileHash;
  uploadForm.value.type_name =
    fileTypeOptions.value[uploadForm.value.type].name;
  uploadForm.value.type = fileTypeOptions.value[uploadForm.value.type].typeId;
  setTimeout(() => {
    recordFile(uploadForm.value);
  }, 1000); // 一秒后执行保存
}
//进度条显示
function onProgress(event, file, fileList) {
  progressFlag.value = true; // 显示进度条
  progress.value = parseInt(event.percent); // 动态获取文件上传进度
  status.value = "exception";
  if (progress.value >= 100) {
    status.value = "success";
    // setTimeout(() => {
    // 	progressFlag.value = false;
    // }, 1000); // 一秒后关闭进度条
  } else if (progress.value >= 50) {
    status.value = "warning";
  }
}
//自定义上传操作
function uploadHttpRequest(option) {
  // 开始上传，token从后端获取， key自定义也可从后端获取（key可以说是文件名）
  const putExtra = {};
  const config = {
    checkByServer: false,
    checkByMD5: false,
    forceDirect: false,
    useCdnDomain: true,
    disableStatisticsReport: false,
    concurrentRequestLimit: 10,
    retryCount: 4,
    chunkSize: 100, //分片时每片大小
    // region: qiniu.region.z2,
    debugLogLevel: "OFF",
  };
  const observable = qiniu.upload(
    option.file,
    qiniuData.value.key,
    qiniuData.value.token,
    putExtra,
    config
  );
  let subscription = observable.subscribe({
    // 以下相关代码就是将七牛云的回调函数给el-upload
    //让el-upload能够展示进度条
    next(res) {
      option.onProgress({ percent: res.total.percent });
      if (cance.value == true) {
        console.log("上传取消");
        ElMessage.error("上传取消");
        subscription.unsubscribe(); // 上传取消
      }
    },
    error(err) {
      option.onError(err);
    },
    complete(res) {
      option.onSuccess(res);
    },
  });

  return subscription;
}

function toggleSelect(item, id) {
  // 切换选择文件或文件夹的激活样式
  // this.id = id;
  // if (item.active) {
  //   Vue.set(item, "active", false); // 为item添加不存在的属性，需要使用vue提供的Vue.set( object, key, value )方法
  //   const index = this.activeItems.indexOf(id);
  //   if (index > -1) {
  //     this.activeItems.splice(index, 1);
  //   }
  // } else {
  //   Vue.set(item, "active", true);
  //   this.activeItems.push(id);
  // }
  // if (this.activeItems.length > 0) {
  //   // 当有文件被激活时，显示重命名，删除，移动操作按钮
  //   this.activeFlag = true;
  // } else {
  //   this.activeFlag = false;
  // }
  // if (this.activeItems.length > 1) {
  //   // 当有两个以上的文件被选中的时候，重命名，移动操作按钮不可用
  //   this.activeFlagNotReame = true;
  // } else {
  //   this.activeFlagNotReame = false;
  // }
  // this.activeFlagMoveble = true;
  // this.files.forEach((item) => {
  //   if (item.active) {
  //     if (item.resType !== 0) {
  //       // 只要有一个不是文件夹的被选中，就可以移动
  //       this.activeFlagMoveble = false;
  //     }
  //   }
  // });
}
//===================
const rules = ref({
  folder_type: [
    { required: true, message: "请选择文件夹类型", trigger: "blur" },
  ],
  folder_name: [{ required: true, message: "请输入文件夹名", trigger: "blur" }],
});

const page = ref(1);
const pageSize = ref(20);
const searchInfo = ref({});

let breadcrumbList = ref([
  {
    id: 0,
    name: "根目录",
  },
]); // 面包屑
let files = ref([]); // 文件数据列表

const defultThumUrl = ref(defultThumUrlimage); // 默认文件夹的样式图片

function clickBreadcrumb(breadcrumb, index) {
  breadcrumbList.value = breadcrumbList.value.slice(0, index + 1);
  currentParentId.value = breadcrumb.id;
  initMaterialPage(currentParentId.value);
  if (breadcrumbList.value.length == 1) {
    createButtonVisible.value = true;
  } else {
    createButtonVisible.value = false;
  }
}
function dbClickOpenFile(file) {
  // 双击文件操作
  if (file.isFile) {
    return;
  }
  // 打开的是文件夹
  breadcrumbList.value.push({ id: file.id, name: file.name });
  currentParentId.value = file.id;
  // console.log(file);
  // console.log(currentParentId.value);
  initMaterialPage(currentParentId.value);
  if (breadcrumbList.value.length == 1) {
    createButtonVisible.value = true;
  } else {
    createButtonVisible.value = false;
  }
}

import fileTypeDll from '@/assets/file_type_dll.svg'
import fileTypeId from '@/assets/file_type_ld.png'
import fileTypeApk from '@/assets/file_type_apk.svg'
import fileTypeYeshen from '@/assets/file_type_yeshen.webp'
import fileTypeOther from '@/assets/file_type_other.svg'

async function initMaterialPage(id = 0) {
  searchInfo.value.parent_id = id;
  files.value = [];
  // 初始化获取
  const table = await getFolderFileList({
    // page: page.value,
    // pageSize: pageSize.value,
    ...searchInfo.value,
  });
  if (table.code === 0) {
    // console.log(table);
    const folderList = table.data.folderList;
    const fileList = table.data.fileList;
    if (folderList != null) {
      for (let i = 0; i < table.data.folderList.length; i++) {
        var temp = {
          id: table.data.folderList[i].id,
          name: table.data.folderList[i].name,
          isFile: false,
        };
        files.value.push(temp);
      }
    }
    if (fileList != null) {
      for (let i = 0; i < table.data.fileList.length; i++) {
        var temp = {
          id: table.data.fileList[i].id,
          name: table.data.fileList[i].file_name,
          isFile: true,
          update_time: table.data.fileList[i].update_time,
          file_version: table.data.fileList[i].file_version,
          qiniu_address: table.data.fileList[i].qiniu_address,
          qiniu_key: table.data.fileList[i].qiniu_key,
          qiniu_hash: table.data.fileList[i].qiniu_hash,
          thumUrl: "",
        };
        switch (table.data.fileList[i].file_type) {
          case 1:
            temp.thumUrl = fileTypeDll;
            break;
          case 2:
            temp.thumUrl = fileTypeId;
            break;
          case 3:
            temp.thumUrl = fileTypeApk;
            break;
          case 4:
            temp.thumUrl = fileTypeYeshen;
            break;
          default:
            temp.thumUrl = fileTypeOther;
            break;
        }
        files.value.push(temp);
      }
    }
  }
}
//获取下拉框list
const getSelectList = async () => {
  const taskListRes = await getAllTaskSimple({
    page: 1,
    pageSize: 999,
  });
  let taskList = [];
  const data = taskListRes.data.list;
  data.forEach((e) => {
    taskList.push({
      value: e.task_id + "|" + e.task_name,
      label: e.task_id + "_" + e.task_name,
    });
  });
  taskOptions.value = taskList;
  //游戏负责人列表===============================
  const directorRes = await getDirectorList();
  let directorList = [];
  const data3 = directorRes.data.list;
  data3.forEach((e) => {
    if (e.name != "备用") {
      directorList.push({ value: e.name, label: e.name });
    }
  });
  directorOptions.value = directorList;
};
const onReset = () => {
  searchInfo.value = {};
};
const onSubmit = async () => {
  // console.log(searchInfo.value)
  files.value = [];
  const table = await queryFolder({
    ...searchInfo.value,
  });
  if (table.code === 0) {
    // // console.log(table);
    const folderList = table.data.folderList;
    if (folderList != null) {
      for (let i = 0; i < table.data.folderList.length; i++) {
        var temp = {
          id: table.data.folderList[i].id,
          name: table.data.folderList[i].name,
          isFile: false,
        };
        files.value.push(temp);
      }
    }
  }
};
getSelectList();
initMaterialPage();
</script>

<style scoped lang="scss">
.button-box {
  padding: 10px 20px;
  .el-button {
    float: right;
  }
}
.warning {
  color: #dc143c;
}

.clearfix:after {
  content: "";
  display: block;
  clear: both;
}
.video-container {
  min-width: 630px;
  margin: 10px;
  .video-header {
    padding: 0 0 5px 0;
    border-bottom: 1px solid #dbdbdb;
    .breadcrumb {
      // float: left;
      height: 20px;
      margin-top: 10px;
      .breadcrumb-link {
        cursor: pointer;
        //font-size: 16px;
      }
      .breadcrumb-link:hover {
        color: #409eff;
        text-decoration: underline;
      }
      .breadcrumb-link-active {
        // 面包屑当前激活文件夹的样式
        font-weight: 700;
      }
    }
    .header-top {
      // float: right;
      height: 40px;
      line-height: 40px;
      position: relative;
    }
  }
  .video-main {
    .list-none {
      box-sizing: border-box;
      position: relative;
      height: 300px;
      width: 100%;
      margin: 5px;
      display: inline-block;
    }
    .list-item {
      border: 1px solid rgb(241, 241, 241);
      border-radius: 5%;
      box-sizing: border-box;
      position: relative;
      height: 125px;
      width: 160px;
      background-color: rgb(241, 241, 241);
      margin: 5px;
      display: inline-block;
      cursor: pointer;
      .inner {
        height: 85px;
        width: 140px;
        // background-color: red;
        margin: 5px 10px;
        // padding: 10px 15px 10px 15px;
        .icon-folder {
          // 文件夹的样式
          display: inline-block;
          width: 80px;
          height: 80px;
          background-image: url("@/assets/defultThumUrl.svg");
          background-size: 100% 100%;
        }
        .icon-thumb {
          // 文件的样式
          width: 80px;
          height: 80px;
        }
        .inner-info {
          float: right;
          // border: 1px solid #409eff;
          width: 45px;
          height: 20px;
          margin-top: 30px;
        }
      }
      .file-name {
        // 文件夹name样式
        padding-left: 10px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: #424e67;
        font-size: 12px;
      }
      .file-name:hover {
        color: rgb(0, 123, 255);
      }
    }
    .hover-cover {
      width: 100px;
      height: 100px;
      position: absolute;
      left: 10px;
      top: 5px;
      background-color: rgb(0, 0, 0);
      opacity: 0;
      text-align: center;
      line-height: 100px;
      font-size: 12px;
    }
    .list-item:hover {
      background-color: rgb(212, 212, 212);
      .icon-file-selected {
        opacity: 0.5;
      }
      .hover-cover {
        opacity: 0.6;
      }
    }
    .icon-file-selected {
      // 小圆点默认样式
      position: absolute;
      right: 5px;
      top: 5px;
      display: inline-block;
      width: 20px;
      height: 20px;
      background-size: 100% 100%;
      background-image: url(@/assets/selected.svg);
      opacity: 0;
    }
    .icon-file-selected:hover {
      // 小圆点hover
      opacity: 1 !important;
    }
    .active {
      // 选择文件触发激活样式
      border: 1px solid #409eff;
      border-radius: 8px;
      .icon-file-selected {
        position: absolute;
        right: 5px;
        top: 5px;
        display: inline-block;
        width: 20px;
        height: 20px;
        background-size: 100% 100%;
        background-image: url(@/assets/selected.svg);
        opacity: 1;
      }
    }
    .active:hover {
      // 激活状态小圆点透明度1
      .icon-file-selected {
        opacity: 1 !important;
      }
    }
    // .loadding-message {
    //   // 加载loading的文字样式
    //   color: #424e67;
    //   font-size: 12px;
    //   text-align: center;
    // }
  }
}
</style>
