<template>
  <div class="file-details">
    <customHeader>文件共享中心</customHeader>
    <div class="content">
      <div class="left-box">
        <!-- 左侧树菜单 -->
        <fileSystem
          :selected="selected"
          :list="listArr"
          :draggable="true"
          @delete-node="onDeltet"
          @on-click="onClick"
          @change-name="onChangeName"
          @addNode="onAddNode"
          @downloadNode="downloadNode"
        >
          <template #icon="{ item }">
            <template v-if="item.isFolder">
              <SvgIcon v-if="item.expanded" size="18" name="file-open" />
              <SvgIcon v-else size="18" name="file-close" />
            </template>
            <treeIcon class="iconfont" :title="item.title" v-else />
          </template>
          <template #operation="{ type }">
            <a-tooltip placement="top" :color="'rgba(28, 72, 105,.5)'">
              <template #title>
                <span>添加</span>
              </template>
              <i class="iconfont icon-xinzeng" v-if="type == 'addDocument'"></i>
            </a-tooltip>
            <a-tooltip placement="top" :color="'rgba(28, 72, 105,.5)'">
              <template #title>
                <span>编辑</span>
              </template>
              <i class="iconfont icon-bianji" v-if="type == 'Editable'"></i>
            </a-tooltip>

            <a-tooltip placement="top" :color="'rgba(28, 72, 105,.5)'">
              <template #title>
                <span>删除</span>
              </template>
              <a-popconfirm v-if="type == 'deleteNode'" title="是否确认删除!" ok-text="确定" cancel-text="取消" @confirm="confirmDel">
                <i class="iconfont icon-guanbi"></i>
              </a-popconfirm>
            </a-tooltip>
            <a-tooltip placement="top" :color="'rgba(28, 72, 105,.5)'">
              <template #title>
                <span>下载目录</span>
              </template>
              <i class="iconfont icon-shangchuan1" v-if="type == 'downloadNode'"></i>
            </a-tooltip>
          </template>
        </fileSystem>
      </div>
      <div class="right-box">
        <div class="search">
          <span style="color: #fff">文件名称：</span>
          <a-input v-model:value="searchForm.fileName" placeholder="请输入文件名称" :disabled="activeKey != '1'" />
          <span style="color: #fff">文件类型：</span>
          <a-select v-model:value="searchForm.fileType" placeholder="请选择..." style="width: 220px; margin-right: 20px" :disabled="activeKey != '1'">
            <a-select-option v-for="item in filetypeList" :value="item.value">{{ item.label }}</a-select-option>
          </a-select>
          <a-button type="primary" preIcon="ant-design:search-outlined" @click="onSearch" :disabled="activeKey != '1'">查询</a-button>
          <a-button type="primary" style="float: right" @click="reportSum" v-if="sysOrgCode == 'sdmtjtgsd'">汇总报表</a-button>
          <a-button type="primary" style="float: right; margin-right: 20px" @click="openModal(true)">文件上传</a-button>
        </div>
        <div class="list">
          <a-tabs class="tabs-box" v-model:activeKey="activeKey" @change="tabChange">
            <a-tab-pane key="1" tab="全部">
              <NormalTable
                :key="alive"
                :submitInfo="submitInfo"
                :selfParam="selfParam"
                :searchParam="searchForm"
                :nodeParam="nodeParam"
                :columns="columns"
                :list="getTree"
                :deleteById="deleteById"
                :downLoad="downLoad"
                designScope="file-detail"
                title="文件详情"
              />
            </a-tab-pane>
            <a-tab-pane key="2" tab="待审批">
              <approvalPend :key="alive2" :selected="selected" />
            </a-tab-pane>
            <a-tab-pane key="3" tab="已审批">
              <endEd :key="alive3" :selected="selected" />
            </a-tab-pane>
          </a-tabs>
        </div>
      </div>
    </div>
    <!-- 上传谈弹窗 -->
    <a-modal v-model:visible="visible" centered :width="600" title="上传文件" @ok="handleOk" @cancel="handleCancel">
      <a-form :model="formState" labelAlign="right" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="是否审批" :rules="[{ required: true, message: '请选择是否审批' }]">
          <a-radio-group v-model:value="formState.isApprove" @change="changeRadio">
            <a-radio :value="true">是</a-radio>
            <a-radio :value="false">否</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="文件类型">
          <JDictSelectTag v-model:value="formState.fileType" placeholder="请选择文件类型" dictCode="file_type" style="width: 260px" />
        </a-form-item>
        <a-form-item label="文件上传">
          <a-upload :before-upload="beforeUpload" @remove="handleRemove" :multiple="false" :file-list="fileList">
            <a-button type="primary" preIcon="ant-design:cloud-upload-outlined">选择文件</a-button>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 汇总报表弹窗 -->
    <a-modal v-model:visible="visiblehHz" centered :width="600" title="报表汇总" :footer="null" @cancel="handleCancelHz">
      <div style="height: 240px; overflow-y: auto; display: flex; flex-direction: column; align-items: center; padding: 10px; box-sizing: border-box">
        <vue3-seamless-scroll hover-stop="true" :list="reportHzList" :hover="true" :step="0.06" class="seamless-warp1">
          <div
            v-for="(item, index) in reportHzList"
            :key="index"
            style="width: 100%; height: 40px; display: flex; justify-content: space-between; align-items: center"
          >
            <span>{{ item.time }}</span>
            <span>{{ item.msg }}</span>
          </div>
        </vue3-seamless-scroll>
      </div>
    </a-modal>
  </div>
</template>
<script lang="ts" setup name="system-user">
  import { Vue3SeamlessScroll } from 'vue3-seamless-scroll';
  import customHeader from '/@/components/vent/customHeader.vue';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import fileSystem from './commen/fileSystem.vue';
  import treeIcon from './commen/Icon/treeIcon.vue';
  import NormalTable from '../comment/NormalTable.vue';
  import approvalPend from '../approvalPend/index.vue';
  import endEd from '../endEd/index.vue';
  import { useRouter } from 'vue-router';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { SvgIcon } from '/@/components/Icon';
  import { ref, onMounted, reactive, nextTick, watch, onUnmounted } from 'vue';
  import { columns } from './fileDetail.data';
  import {
    getTree,
    createFile,
    editMenu,
    delMenu,
    uploadApi,
    downLoad,
    deleteById,
    listData,
    getNowUserAgencyData,
    sumVentReport,
    queryVentMonReportJd,
    zipdownload,
  } from './fileDetail.api';
  import { useGlobSetting } from '/@/hooks/setting';

  const { sysOrgCode } = useGlobSetting();
  let visiblehHz = ref(false);
  let reportHzList = ref<any[]>([]);
  let timer: null | NodeJS.Timeout = null;
  let activeKey = ref('1');
  let selfParam = reactive({
    //各矿参数
    sysOrgCode: '',
    bpmStatus: null,
    flag: false,
  });
  let router = useRouter(); //路由
  const { createMessage } = useMessage();
  let searchForm = reactive({
    fileName: '',
    fileType: '',
  });
  let filetypeList = reactive<any[]>([
    { label: 'txt', value: 'txt' },
    { label: 'doc', value: 'doc' },
    { label: 'docx', value: 'docx' },
    { label: 'xls', value: 'xls' },
    { label: 'xlsx', value: 'xlsx' },
    { label: 'ppt', value: 'ppt' },
    { label: 'pptx', value: 'pptx' },
    { label: 'jpg', value: 'jpg' },
    { label: 'png', value: 'png' },
    { label: 'pdf', value: 'pdf' },
  ]);
  let fileList = reactive<any[]>([]); //上传文件列表
  // let uploadParam = reactive({}); //上传文件参数
  let nodeParam = reactive({}); //点击树节点时传递的参数
  let alive = ref(0); //点击树节点刷新表格数据
  let alive2 = ref(0);
  let alive3 = ref(0);
  let visible = ref(false); //控制上传弹窗的显示
  let formState = reactive({
    //上传文件类型，是否审批
    isApprove: null,
    fileType: '',
  });
  //文件审批-提交信息
  let submitInfo = ref<any[]>([]);

  //lxh 当前选中树节点
  let selected = reactive<any>({
    id: null,
    pid: null,
    title: '',
    isFolder: false,
  });
  let flag = ref('');
  //左侧菜单列表
  let listArr = reactive<any[]>([]);
  //获取要删除的节点数据
  let delNode = reactive({});

  //下载目录
  function downloadNode(data) {
    console.log(data, '999000=============================================');
    zipdownload({ id: data.id, ifMine: false }).then((res) => {
      let filename = `${data.fileName}`;
      downFilePublic(res, filename);
    });
  }
  // 下载公用方法
  function downFilePublic(content, fileName) {
    const blob = new Blob([content], { type: 'application/zip;charset=UTF-8' }); // 构造一个blob对象来处理数据
    // 对于<a>标签，只有 Firefox 和 Chrome（内核） 支持 download 属性
    // IE10以上支持blob但是依然不支持download
    if ('download' in document.createElement('a')) {
      // 支持a标签download的浏览器
      const link = document.createElement('a'); // 创建a标签
      link.download = fileName; // a标签添加属性
      link.style.display = 'none';
      link.href = URL.createObjectURL(blob);
      document.body.appendChild(link);
      link.click(); // 执行下载
      URL.revokeObjectURL(link.href); // 释放url
      document.body.removeChild(link); // 释放标签
    } else {
      // 其他浏览器
      navigator.msSaveBlob(blob, fileName);
    }
  }
  //汇总报表
  function reportSum() {
    visiblehHz.value = true;
    sumVentReport();
    timer = setInterval(async () => {
      let res = await queryVentMonReportJd();
      reportHzList.value = res.jdList;
      if (res.flag) {
        visiblehHz.value = false;
        clearTimeout(timer);
        reportHzList.value.length = 0;
        alive.value = new Date().getTime();
      } else {
        visiblehHz.value = true;
      }
    }, 3000);
  }
  //关闭汇总弹窗
  function handleCancelHz() {
    reportHzList.value.length = 0;
    visiblehHz.value = false;
    clearTimeout(timer);
    alive.value = new Date().getTime();
  }
  //上传文件
  let openModal = (val) => {
    formState.isApprove = null;
    formState.fileType = '';
    fileList.length = 0;
    visible.value = val;
  };

  //tabs选项切换
  let tabChange = (activeKeyVal) => {
    activeKey.value = activeKeyVal;
    switch (activeKeyVal) {
      case '1':
        alive.value = new Date().getTime();
        break;
      case '2':
        alive2.value = new Date().getTime();
        break;
      case '3':
        alive3.value = new Date().getTime();
        break;
    }
  };
  //文件审批状态切换
  let changeRadio = (val) => {
    formState.isApprove = val.target.value;
  };
  //开始上传
  let handleOk = () => {
    if (formState.isApprove === null) {
      createMessage.warning('请选择文件审批状态！');
    } else {
      const formData = new FormData();
      formData.append('file', fileList[0]);
      formData.append('parentId', selected.id);
      formData.append('isApprove', formState.isApprove);
      formData.append('fileType', formState.fileType);
      uploadApi(formData).then((res) => {
        console.log(res, '上传返回');
        alive.value = new Date().getTime();
        visible.value = false;
      });
    }
  };
  //取消上传
  let handleCancel = () => {
    visible.value = false;
  };
  let list2trees = (data) => {
    // 删除 所有 children,以防止多次调用
    data.forEach(function (item) {
      delete item.children;
    });
    // 将数据存储为 以 id 为 KEY 的 map 索引数据列
    let map = {};
    data.forEach(function (item) {
      map[item.id] = item;
    });
    var val = [];
    data.forEach(function (item) {
      item.isFolder = true;
      item.title = item.fileName;
      item.pid = item.parentId;
      // 以当前遍历项，的pid,去map对象中找到索引的id
      var parent = map[item.pid];
      // 好绕啊，如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
      if (parent) {
        (parent.children || (parent.children = [])).push(item);
      } else {
        //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
        val.push(item);
      }
    });
    return val;
  };

  let getTypeTableList = async () => {
    let parentId = nodeParam.id || '';
    let selectFlag = nodeParam.id ? false : true;
    let likeFileName = searchForm.fileName || '';
    let fileSuffix = searchForm.fileType || '';
    let bpmStatus = selfParam.bpmStatus || '';
    let sysOrgCode = selfParam.sysOrgCode || '';
    let res = await getTree({
      parentId: parentId,
      selectFlag: selectFlag,
      likeFileName: likeFileName,
      fileSuffix: '.' + fileSuffix,
      bpmStatus: bpmStatus,
      sysOrgCode: sysOrgCode,
    });
    console.log(res, 'tableList--------------------');
  };

  //获取左侧菜单树数据
  let getTreeList = async () => {
    listArr.length = 0;
    let data = await getTree({ parentId: '' });
    let datas = data.records.filter((v) => v.fileType == null);
    let list = list2trees(datas);
    listArr.push(...list);
    console.log(listArr, '树节点数据');
    selected.id = listArr[0].id;
    selected.pid = listArr[0].pid;
    selected.title = listArr[0].title;
    selected.isFolder = listArr[0].isFolder;
  };

  //点击目录
  const onClick = (node) => {
    selected.id = node.id;
    selected.pid = node.pid;
    selected.title = node.title;
    selected.isFolder = node.isFolder;
    console.log(selected, 'selec----------');
    if (flag.value != node.title) {
      alive.value = new Date().getTime();
      nodeParam = node;
      flag.value = node.title;
    }
  };
  //添加文件
  const onAddNode = async (node) => {
    let data = await createFile({ fileName: node.newName, type: 'FOL', parentId: node.id });
    console.log(data, '新增文件返回');
    getTreeList();
  };

  //  修改名字
  const onChangeName = (node) => {
    editMenu({
      id: node.id,
      fileName: node.newName,
      parentId: node.pid,
    }).then((res) => {
      getTreeList();
    });
  };
  // 删除
  let onDeltet = (node) => {
    delNode = { ...node };
  };
  //确定删除
  let confirmDel = () => {
    if (delNode.pid == 'root') {
      createMessage.warning('根节点不能被删除!');
    } else if (delNode.children) {
      createMessage.warning('该节点无法被删除,请先删除该节点下的子节点!');
    } else {
      delMenu({ id: delNode.id }).then((res) => {
        console.log(res, '删除文件');
        getTreeList();
      });
    }
  };

  //查询列表
  let onSearch = () => {
    alive.value = new Date().getTime();
  };
  //上传文件
  let beforeUpload = (file) => {
    console.log(file, '选中文件');
    fileList.length = 0;
    let index = file.name.indexOf('.');
    let name = file.name.substring(index + 1);
    if (name == 'png' || name == 'jpg' || name == 'gif' || name == 'psd' || name == 'webp') {
      createMessage.warning('禁止上传图片类型的文件!');
    } else {
      fileList.push(file);
    }
  };
  // 文件移除
  let handleRemove = (file) => {
    const index = fileList.indexOf(file);
    const newFileList = fileList.slice();
    newFileList.splice(index, 1);
    fileList.length = 0;
  };
  //文件-提交
  async function getListData() {
    let res = await listData({ zx: true, column: 'createTime', order: 'desc', status: 1 });
    console.log(res, '审批提交-----------');
    submitInfo.value = res;
  }
  watch(
    () => router.currentRoute.value,
    (val) => {
      console.log('各矿传参', val);
      selfParam.bpmStatus = val.query.bpmStatus;
      selfParam.sysOrgCode = val.query.sysOrgCode;
      selfParam.flag = val.query.flag;
    },
    { immediate: true }
  );
  onMounted(() => {
    getTreeList();
    getListData();
    getTypeTableList();
  });
  onUnmounted(() => {
    if (timer) {
      clearTimeout(timer);
      timer = undefined;
    }
  });
</script>

<style lang="less" scoped>
  @import '/@/design/theme.less';
  @ventSpace: zxm;

  @{theme-deepblue} {
    .file-details {
      --input-border: #0863c3;
      --image-btn: url(/@/assets/images/themify/deepblue/files/details/btn.png);
    }
  }

  .file-details {
    --input-border: #31bccc;
    --image-btn: url(/@/assets/images/files/details/btn.png);
    width: calc(100% - 10px);
    height: calc(100% - 100px);
    padding: 0px 15px 15px 15px;
    position: relative;
    margin-top: 100px;
    // background: url(../../../../assets/images/files/homes/bd.png) no-repeat center;
    // background-size: contain;

    &::after {
      display: block;
      content: '';
      height: 200px;
      width: 100%;
      position: absolute;
      background-image: linear-gradient(#2eb2ff05, #2ea2ff00);
      border-top: 1px solid #2eb2ff20;
      top: 0px;
      left: 0px;
    }

    .content {
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: flex-start;
      position: relative;
      z-index: 999;

      .left-box {
        width: 18%;
        height: 100%;
        padding: 10px;
        border: 1px solid #99e8ff66;
        background: #27546e1a;
        overflow-y:auto;
        box-shadow: 0px 0px 20px 7px rgba(145, 233, 254, 0.7) inset;
        -moz-box-shadow: 0px 0px 20px 7px rgba(145, 233, 254, 0.7) inset;
        -webkit-box-shadow: 0px 0px 50px 1px rgb(149 235 255 / 5%) inset;
        // lxh
        .iconfont {
          color: #fff;
          font-size: 12px;
          margin-left: 5px;
        }
      }

      .right-box {
        width: 82%;
        height: 100%;
        padding: 0px 0px 0px 10px;
        box-sizing: border-box;

        .search {
          height: 34px;
          line-height: 34px;
          margin-bottom: 15px;
        }
      }

      .list {
        height: calc(100% - 49px);
        position: relative;
      }
    }

    .zxm-form {
      padding: 10px !important;
    }
  }

  .seamless-warp1 {
    width: 100%;
    height: 100%;
    overflow: hidden;
  }

  ::v-deep .jeecg-svg-icon {
    margin-right: 5px;
  }

  ::v-deep .jeecg-basic-table-form-container {
    padding: 0px 0px;
  }

  ::v-deep .zxm-btn-primary {
    background-color: transparent;
    border: none;
    background: var(--image-btn) no-repeat !important;
    background-size: 100% 100% !important;
  }

  ::v-deep .zxm-tree-switcher {
    background: transparent;
  }

  ::v-deep .zxm-input {
    width: 220px;
    height: 30px;
    background: transparent;
    border: 1px solid var(--input-border);
    color: #fff;
    margin-right: 20px;
    border-radius: 5px;
  }

  ::v-deep .zxm-select:not(.zxm-select-customize-input) .zxm-select-selector {
    height: 30px !important;
    background: transparent !important;
    border: 1px solid var(--input-border) !important;
    border-radius: 5px !important;
    color: #fff !important;
  }

  ::v-deep .zxm-select-single.zxm-select-show-arrow .zxm-select-selection-item {
    color: #fff !important;
  }

  ::v-deep .zxm-btn-group {
    margin-right: 25px;
  }

  ::v-deep .zxm-upload-list-item-name {
    color: #fff;
  }

  ::v-deep .zxm-upload-list-item:hover .zxm-upload-list-item-info {
    background-color: transparent;
  }

  :deep(.@{ventSpace}-table-cell-row-hover) {
    background: #264d8833 !important;
  }

  :deep(.@{ventSpace}-table-row-selected) {
    background: #268bc522 !important;
  }

  :deep(.@{ventSpace}-select-dropdown) {
    border: 1px solid #ececec66;

    .@{ventSpace}-select-item-option-selected,
    .@{ventSpace}-select-item-option-active {
      background-color: #ffffff33 !important;
    }

    .@{ventSpace}-select-item:hover {
      background-color: #ffffff33 !important;
    }
  }

  ::v-deep .zxm-form-item-control-input {
    width: 90%;
  }
</style>
