<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> -->
                          <el-tag size="small" type="info">版本：{{ file.file_version }}</el-tag>
                          <el-tag size="small" type="success">{{ file.push_policy }}</el-tag>
                          <!-- <p>
                                      <span style="font-size: 5px;color:brown">{{
                                        file.push_policy
                                      }}</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('info', file)"><el-icon>
                              <InfoFilled />
                            </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('updatePolicy', 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 v-if="showUpdatePolicy" label="更新策略" prop="type">
            <el-col :span="20">
              <el-radio-group v-model="uploadForm.pushPolicy" @change="pushPolicyChanged(uploadForm.pushPolicy)">
                <el-radio label="0" size="large">暂不更新</el-radio>
                <el-radio label="1" size="large">立即更新</el-radio>
                <el-radio label="2" size="large">延迟更新</el-radio>
              </el-radio-group>
            </el-col>
          </el-form-item>
          <el-form-item v-if="showUpdateTime" label="更新时间" prop="type">
            <el-col :span="20">
              <el-date-picker v-model="uploadForm.pushTime" type="datetime" placeholder="选择日期时间" />
            </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="MD5进度">
            <p style="color:brown">{{ processMD5 }}</p>
            <p style="color:rgb(255, 0, 0)">{{ keyWord }}</p>
          </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()">取消上传</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>
      <el-dialog title="修改策略" v-model="policyVisible" :center="true" :close-on-click-modal="false">
        <el-form :model="formPolicy">
          <el-form-item label="文件名称" prop="file_name">
            <el-col :span="20">
              <el-input v-model="formPolicy.file_name" disabled></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="更新策略" prop="type">
            <el-col :span="20">
              <el-radio-group v-model="formPolicy.pushPolicy" @change="formPolicyChanged(formPolicy.pushPolicy)">
                <el-radio label="0" size="large">暂不更新</el-radio>
                <el-radio label="1" size="large">立即更新</el-radio>
                <el-radio label="2" size="large">延迟更新</el-radio>
              </el-radio-group>
            </el-col>
          </el-form-item>
          <el-form-item v-if="showUpdateTime2" label="更新时间" prop="type">
            <el-col :span="20">
              <el-date-picker v-model="formPolicy.pushTime" type="datetime" placeholder="选择日期时间" />
            </el-col>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="policyVisible = false">取消</el-button>
            <el-button type="primary" @click="updatePolicy()">
              确定
            </el-button>
          </span>
        </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,
  updateMirrorPushPolicy,
} from "@/api/fileManager";
import { getDirectorList } from "@/api/responsiblePerson";
import { ref } from "vue";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import { ArrowRight } from "@element-plus/icons-vue";
import * as qiniu from "qiniu-js";
import defultThumUrlimage from '@/assets/defultThumUrl.svg'
import SparkMD5 from 'spark-md5'
import axios from 'axios'
import dayjs from "dayjs";

//===================
const fileFolderVisible = ref(false);
const taskFolderVisible = ref(false);
const createButtonVisible = ref(true);
const disabledFolderName = ref(false);
const policyVisible = ref(false);
const formFolder = ref({
  folder_type: "0",
  folder_name: "",
  task: "",
  parentId: 0,
});
const formPolicy = ref({
  id: 0,
  file_name: "",
  pushPolicy: '0',
  pushTime: new Date("2099-01-01 15:04:05"),
})
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 processMD5 = ref('未选择文件');
const afterMD5 = ref('0'); // 上传后七牛返回的MD5
const beforeMD5 = ref('0'); // 上传前本地计算的MD5
const keyWord = ref(''); //关键信息展示
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: "",
  pushPolicy: '0',
  pushTime: new Date("2099-01-01 15:04:05"),
  md5: '',
});
const folderTypeOptions = ref([]);
const dropdownRef = ref();
const activeItems = ref([]); // 选中激活的文件列表
const qiniuData = ref({
  key: "",
  token: "",
  cName: "",
}); //七牛上传时获取的服务器信息
const showVersion = ref(false);
const showUpdatePolicy = ref(false);
const showUpdateTime = ref(false);
const showUpdateTime2 = 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;
  processMD5.value = '';
  await getToken();
  afterMD5.value = '';
  beforeMD5.value = '';
  keyWord.value = '';
  uploadForm.value.pushTime = new Date("2099-01-01 15:04:05");
}
// 查询所有文件类型
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;
    case "info":
      getFileInfo(val.command);
      break;
    case "updatePolicy":
      switchPolicy(val.command);
      break;
    default:
      break;
  }
};
function switchPolicy(file) {
  formPolicy.value.id = file.id
  formPolicy.value.file_name = file.name
  formPolicy.value.pushTime = file.push_time
  if (file.push_policy == "延迟更新") {
    formPolicy.value.pushPolicy = '2'
    showUpdateTime2.value = true;
  } else if (file.push_policy == "立即更新") {
    formPolicy.value.pushPolicy = '1'
    showUpdateTime2.value = false;
  } else {
    formPolicy.value.pushPolicy = '0'
    showUpdateTime2.value = false;
  }
  policyVisible.value = true
}
function formPolicyChanged(pushPolicy) {
  if (pushPolicy == 2) {
    showUpdateTime2.value = true;
  } else if (pushPolicy == 1) {
    formPolicy.value.pushTime = new Date();
    showUpdateTime2.value = false;
  } else {
    showUpdateTime2.value = false;
    formPolicy.value.pushTime = new Date("2099-01-01 15:04:05");
  }
}
async function updatePolicy() {
  const res = await updateMirrorPushPolicy({
    id: formPolicy.value.id,
    push_policy: Number(formPolicy.value.pushPolicy),
    push_time: dayjs(new Date(formPolicy.value.pushTime)).format("YYYY-MM-DD HH:mm:ss"),
  });
  // console.log(res);
  if (res.code == 0) {
    ElMessage.success(res.msg);
    policyVisible.value = false
    initMaterialPage(currentParentId.value);
  }
}
//文件重命名
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,
  //   }
  // );
  ElMessageBox.confirm(
    "<strong>" + file.qiniu_address + "</strong>",
    '下载链接',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '复制到剪切板',
      type: '',
    }
  )
    .then(() => {
      // console.log(file.qiniu_address)
      clickCopy(file.qiniu_address)
    })
    .catch(() => {
      // ElMessage({
      //   type: 'info',
      //   message: 'Delete canceled',
      // })
    })
}
//获取文件信息
async function getFileInfo(file) {
  ElMessageBox.alert(
    "<p><strong>文件名:" + file.name + "</strong></p>" +
    "<p><strong>文件版本:" + file.file_version + "</strong></p>" +
    "<p><strong><span>下载链接：</span>" + file.qiniu_address + "</strong></p>" +
    "<p><strong>七牛HASH:" + file.qiniu_hash + "</strong></p>" +
    "<p><strong>MD5值:" + file.md5 + "</strong></p>" +
    "<p><strong>更新策略:" + file.push_policy + "</strong></p>" +
    "<p><strong>更新时间:" + file.push_time + "</strong></p>",
    "文件信息",
    {
      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;
  // console.log(fileTypeOptions.value[uploadForm.value.type].name)
  if (fileTypeOptions.value[uploadForm.value.type].name == "雷电镜像" || fileTypeOptions.value[uploadForm.value.type].name == "夜神镜像") {
    showUpdatePolicy.value = true;
  } else {
    showUpdatePolicy.value = false;
  }
}
async function pushPolicyChanged(pushPolicy) {
  if (pushPolicy == 2) {
    showUpdateTime.value = true;
  } else if (pushPolicy == 1) {
    uploadForm.value.pushTime = new Date();
    showUpdateTime.value = false;
  } else {
    showUpdateTime.value = false;
    uploadForm.value.pushTime = new Date("2099-01-01 15:04:05");
  }
}
// 取消上传文件
async function cancelUp() {
  //中断文件传输
  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);
  }
  if (window.location.href.indexOf("#reloaded") == -1) {
    console.log("刷新页面")
    window.location.href = window.location.href + "#reloaded";
    window.location.reload();
  }

}

async function ComputerFileMd5(files) {
  const file = files;
  // const hash = sha1(file);
  // async function test(file) {
  // 	//计算SHA1
  // 	const hash = await sha1(file);
  // 	//hash即得到的sha1值
  // 	// console.log(hash);
  // }
  // test(file);
  //计算MD5
  // const sliceLength = 10;
  // const chunkSize = Math.ceil(file.size / sliceLength);
  // const fileReader = new FileReader();
  // const md5 = new SparkMD5();
  // let index = 0;
  // const loadFile = () => {
  //   const slice = file.slice(index, index + chunkSize);
  //   fileReader.readAsBinaryString(slice);
  // };
  // loadFile();
  // fileReader.onload = async (e) => {
  //   await md5.appendBinary(e.target.result);
  //   if (index < file.size) {
  //     index += chunkSize;
  //     loadFile();
  //   } else {
  //     // md5.end() 就是文件md5码
  //     console.log(md5.end());
  //     console.log('计算完毕')
  //     return md5.end()
  //   }
  // };
  //方法二：
  //=============================================
  // const loading = ElLoading.service({
  //   lock: true,
  //   text: "正在计算文件MD5,请勿关闭此页面...",
  //   spinner: "el-icon-loading",
  //   background: "rgba(0, 0, 0, 0.9)"
  // });

  return new Promise((resolve, reject) => {
    // console.log(file.name)
    let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
      chunkSize = 4 * 1024 * 1024, //4MB
      chunks = Math.ceil(file.size / chunkSize),
      currentChunk = 0,
      spark = new SparkMD5.ArrayBuffer(),
      fileReader = new FileReader();
    let time = new Date().getTime();
    fileReader.onload = async (e) => {
      await spark.append(e.target.result);   // Append array buffer
      currentChunk++;
      if (currentChunk < chunks) {
        // console.log(`开始第${currentChunk + 1}  /  ${chunks}分片解析计算`);
        processMD5.value = `开始第  ${currentChunk + 1}  /  ${chunks}  分片解析计算`
        loadNext();
      } else {
        // console.log('finished loading');
        let md5 = spark.end(); //得到md5
        processMD5.value = `MD5：${md5} 用时：${new Date().getTime() - time} ms`
        // console.log(`MD5计算完成：${file.name} \nMD5：${md5} \n分片：${chunks} 大小:${file.size} 用时：${new Date().getTime() - time} ms`);
        await spark.destroy(); //释放缓存
        resolve(md5)
        // loading.close();
      }
    };

    fileReader.onerror = () => {
      console.warn('oops, something went wrong.');
      file.cancel();
      reject('oops, something went wrong.');
    };
    function loadNext() {
      let start = currentChunk * chunkSize,
        end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
      let chunk = blobSlice.call(file, start, end);
      fileReader.readAsArrayBuffer(chunk);
    }
    loadNext();
  })




}

//上传前处理
async 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;

  // console.log(file)
  await ComputerFileMd5(file).then(function (res) {
    beforeMD5.value = res
    // console.log(res)
  }, function (error) {
    uploadVisible.value = false;
    ElMessage.error("计算MD5出错,上传取消");
    return false;
  });
}
//确定上传,记录文件信息在数据库中
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,
    push_policy: Number(aaa.pushPolicy),
    push_time: dayjs(new Date(aaa.pushTime)).format("YYYY-MM-DD HH:mm:ss"),
    md5: aaa.md5,
  };
  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;
  //此处获取七牛云返回的MD5值，并和本地计算的进行对比，如不一致，则删除文件并结束
  //因七牛返回MD5很慢，因此此处先不对比
  // console.warn(fileUrl)
  // axios.get(fileUrl + '?qhash/md5', {
  // })
  //   .then(response => {
  //     console.log(response.data.hash)
  //     if (response.data.hash) {
  //       afterMD5.value = response.data.hash
  //       if (afterMD5.value == beforeMD5.value) {
  //         keyWord.value = `文件校验完成,即将保存`
  //         setTimeout(() => {
  //           uploadForm.value.md5 = afterMD5.value
  //           recordFile(uploadForm.value);
  //         }, 1000); // 一秒后执行保存
  //       } else {
  //         keyWord.value = `文件校验失败,与云端MD5不一致(${afterMD5.value})`
  //         cancelUp()
  //       }
  //     } else {
  //       keyWord.value = `文件校验失败,七牛云未返回MD5(${response.data})`
  //       cancelUp()

  //     }
  //   })
  //   .catch(error => {
  //     console.error(error)
  //     keyWord.value = `文件校验失败,七牛云未返回MD5(${error})`
  //     cancelUp()
  //   })
  if (beforeMD5.value) {
    keyWord.value = `文件校验完成,即将保存`
    setTimeout(() => {
      uploadForm.value.md5 = beforeMD5.value
      recordFile(uploadForm.value);
    }, 1000); // 一秒后执行保存
  } else {
    keyWord.value = `MD5有误(${afterMD5.value})`
    cancelUp()
  }
}
//进度条显示
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: 10, //分片时每片大小
    // 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++) {
        let policy = '暂不更新'
        if (table.data.fileList[i].push_policy == 1) {
          policy = '立即更新'
        } else if (table.data.fileList[i].push_policy == 2) {
          policy = '延迟更新'
        }
        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: "",
          md5: table.data.fileList[i].md5,
          push_policy: policy,
          push_time: table.data.fileList[i].push_time,
        };
        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);
      }
    }
  }
}
// 点击复制到剪切板
function clickCopy(msg) {
  const save = function (e) {
    e.clipboardData.setData('text/plain', msg)
    e.preventDefault() // 阻止默认行为
  }
  const once = {
    once: true
  }
  document.addEventListener('copy', save, once) // 添加一个copy事件,当触发时执行一次,执行完删除
  document.execCommand('copy') // 执行copy方法
  ElMessage({
    type: 'success',
    message: '复制成功',
  })
}

//获取下拉框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: 170px;
      background-color: rgb(241, 241, 241);
      margin: 5px;
      display: inline-block;
      cursor: pointer;

      .inner {
        height: 85px;
        width: 150px;
        // background-color: red;
        margin: 5px 5px 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: 65px;
          height: 50px;
          margin-top: 20px;
        }
      }

      .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>
