<template>
  <el-tabs v-model="activeName" class="demo-tabs p5" @tab-click="handleCheckMian">
    <el-tab-pane label="资料" name="first">
      <div class="profile_engin">
        <div class="box_info">
          <div class="tree_left1" id="tree_left1">
            <div class="file_upload check_select">
              <div class="box_btn">
                <file-upload
                  v-model="state.paramsQuery.file"
                  :limit="100"
                  :uploadUrl="uploadUrl"
                  :params="uploadParams"
                  :on-upload-success="uploadFile"
                  :fileType="[]"
                >
                  <el-button type="primary" style="float: left" :disabled="!state.parentPid">
                    <el-icon size="small"><Plus /></el-icon>上传文件
                  </el-button>
                </file-upload>
              </div>
              <el-button type="primary" :disabled="!state.parentPid" @click="onExport"
                ><el-icon><Download /></el-icon>下载</el-button
              >
              <el-button type="primary" @click="onBook"
                ><el-icon><View /></el-icon>查看全项目文件</el-button
              >
            </div>
            <div class="file_upload check_select">
              <el-input class="input_left" v-model="filterText" size="small" placeholder="请输入文件名称" />
            </div>
            <el-tree
              ref="treeRef"
              highlight-current
              :default-expand-all="state.checked"
              :filter-node-method="filterFolder"
              :data="state.treeList"
              node-key="id"
              accordion
              :expand-on-click-node="false"
              @node-click="handleNodeClick"
              :current-node-key="state.selectedNodeId"
            >
              <template #default="{ node, data }">
                <span class="custom-tree-node">
                  <el-icon color="#f1a81a"><FolderOpened /></el-icon>
                  <span>{{ node.label }}</span>
                </span>
              </template>
            </el-tree>
            <div class="resize-handle resize-handle-right right"></div>
          </div>
          <div class="list_right" id="list_right1">
            <div>
              <el-form :model="state.paramsQuery" ref="queryRef" :inline="true" label-width="100px">
                <el-row>
                  <el-col :span="7" class="colBlock">
                    <el-form-item label="文件名称" prop="fileName">
                      <el-input
                        v-model="state.paramsQuery.fileName"
                        placeholder="请输入文件名称"
                        clearable
                        @keyup.enter.native="getdocumentDataList"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6" class="m-l10">
                    <el-form-item>
                      <el-button type="primary" @click="searchInfo"
                        ><el-icon><Search /></el-icon>搜索</el-button
                      >
                      <el-button @click="resetQuery"
                        ><el-icon><Refresh /></el-icon>重置</el-button
                      >
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <el-table v-loading="state.loading" :data="state.infoList" height="67vh" border>
              <el-table-column label="序号" align="center" type="index" min-width="50px" />
              <el-table-column label="文件名称" align="center" prop="fileName"></el-table-column>
              <el-table-column label="文件类型" align="center" prop="fileSuffix" width="100px" />

              <el-table-column label="上传时间" align="center" prop="createTime"> </el-table-column>
              <el-table-column label="操作" align="center" width="300">
                <template #default="scope">
                  <el-button type="primary" link @click="handleView(scope.row)" v-if="acceptType.includes(scope.row.fileSuffix)"
                    ><el-icon><View /></el-icon>查看</el-button
                  >
                  <el-button type="primary" v-if="state.wordType.includes(scope.row.fileSuffix)" link @click="updataView(scope.row)"
                    ><el-icon><EditPen /></el-icon>修改文件</el-button
                  >
                  <el-button type="primary" link @click="onExportView(scope.row)"
                    ><el-icon><Download /></el-icon>下载</el-button
                  >
                  <el-button type="success" link @click="updateName(scope.row)"
                    ><el-icon><EditPen /></el-icon>修改名称</el-button
                  >
                  <el-button type="danger" link @click="handleDelete(scope.row)"
                    ><el-icon><DeleteFilled /></el-icon>删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <pagination
              :total="state.total"
              v-model:page="state.paramsQuery.pageNum"
              v-model:limit="state.paramsQuery.pageSize"
              @pagination="getdocumentDataList"
            />
          </div>
        </div>
        <documentsDeailsVue ref="documentDetailRef" v-if="state.showDocumentDetail" @onClose="onClose"></documentsDeailsVue>
        <documentsEdit ref="documentDataEditRef" v-if="state.showdocumentDataEdit" @onClose="onCloseEdit"></documentsEdit>
        <bookFile ref="bookFileRef" @onExportView="onExportView" @onBook="handleView" @onExport="onExport"></bookFile>
        <el-dialog draggable title="上传文件" v-model="uploadFileder" width="30%">
          <file-upload v-model="state.paramsQuery.file"></file-upload>
          <template #footer>
            <span>
              <el-button @click="uploadFileder = false">取消</el-button>
              <el-button type="primary" @click="subMitUpload">确定</el-button>
            </span>
          </template>
        </el-dialog>
      </div>
      <el-image-viewer
        ref="imageRef"
        style="width: 100%; height: 100%"
        :url-list="[imgUrl]"
        v-if="imgUrl"
        show-progress
        fit="cover"
        @close="imgUrl = ''"
      />
    </el-tab-pane>
    <el-tab-pane label="回收站" name="second">
      <RecyclingStation ref="recylingRef"></RecyclingStation>
    </el-tab-pane>
  </el-tabs>
</template>

<script setup name="KnowledgeDocument" lang="ts">
import {
  listKnowledgeDocument,
  delKnowledgeDocument,
  addKnowledgeDocument,
  getUniFolderDownloadList,
  treeStructureData,
  documentDataEdit
} from '@/api/design/technicalStandard';

import documentsEdit from './component/documentsEdit.vue';
import documentsDeailsVue from './component/documentsDeails.vue';
import RecyclingStation from './component/recyclingStation.vue';

import { useUserStoreHook } from '@/store/modules/user';
import bookFile from './component/bookFile.vue';
const activeName = ref('first');
const { proxy } = getCurrentInstance() as any;
// 获取用户 store
const userStore = useUserStoreHook();
// 从 store 中获取项目列表和当前选中的项目
const currentProject = computed(() => userStore.selectedProject);
const uploadUrl = computed(() => {
  return `/design/technicalStandard/file`;
});
const uploadParams = computed(() => {
  return {
    pid: state.paramsQuery.folderId,
    projectId: state.projectId
  };
});

const imgUrl = ref<string>('');
const filterText = ref('');
const treeRef = ref();
const documentDetailRef = ref();
const documentDataEditRef = ref();
const uploadFileder = ref(false);
const imageRef = ref();
const recylingRef = ref();
const bookFileRef = ref();
const state = reactive({
  treeList: [] as any,
  arrayList: [] as any,
  infoMap: new Map(),
  infoList: [] as any,
  total: 0,
  paramsQuery: {
    folderId: '',
    fileName: '',
    pageNum: 1,
    pageSize: 20,
    projectId: currentProject.value?.id,
    file: null,
    pid: null
  },
  loading: false,
  checked: true,
  showDocumentDetail: false,
  showdocumentDataEdit: false,
  showUploadFileder: false,
  parentRow: null,
  parentPid: null,
  parentName: '',
  selectedNodeId: null,
  projectId: currentProject.value?.id || '',
  imgType: ['jpg', 'png', 'jpeg', 'gif', 'svg'],
  wordType: ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'],
  browserViewableType: ['html', 'htm', 'txt', 'log', 'md', 'json', 'xml', 'css', 'js'],

  draggableCheck: true
});

const acceptType = computed(() => [...state.imgType, ...state.wordType, ...state.browserViewableType]);

watch(filterText, (val: any) => {
  treeRef.value!.filter(val);
});

// 上传文件
const uploadFile = (files: any[]) => {
  proxy.$modal.success('上传成功');
  state.paramsQuery.file = null;
  getdocumentDataList();
  // uploadFileder.value = true;
};

// 提交上传文件
const subMitUpload = () => {
  if (!state.paramsQuery.file) {
    ElMessage.warning('请选择文件！');
    return;
  }
  addKnowledgeDocument(state.paramsQuery, { projectId: state.projectId, pid: state.parentPid }).then((res: any) => {
    if (res.code == 200) {
      ElMessage.success('上传成功');
      uploadFileder.value = false;
      state.paramsQuery.file = null; //清空文件
      getdocumentDataList();
    } else {
      ElMessage.error(res.message);
    }
  });
};

const searchInfo = () => {
  // 搜索
  getdocumentDataList();
};
const resetQuery = () => {
  // 重置
  state.paramsQuery.fileName = '';
  getdocumentDataList();
};
// 获取树形结构文件夹目录
const gettreeStructureData = () => {
  state.parentPid = null;
  activeName.value = 'first';
  const loading = ElLoading.service({
    lock: true,
    text: '正在加载中……',
    background: 'rgba(0, 0, 0, 0.7)',
    target: '.tree_left1'
  });
  treeStructureData(state.projectId).then((res: any) => {
    loading.close();
    if (res.code == 200 && res.data && res.data.length) {
      state.selectedNodeId = '';
      state.treeList = res.data;
      state.paramsQuery.folderId = res.data[0].id;
      getdocumentDataList();
      // setInfo(res.data);
    }
  });
};
// 处理数据
const setInfo = (arr) => {
  arr.forEach((element) => {
    state.arrayList.push(element);
    state.infoMap.set(element.folderId, element.id);
    if (element.treeStructureDataRes && element.treeStructureDataRes.length) {
      setInfo(element.treeStructureDataRes);
    }
  });
};
// 选择目录文件
const handleNodeClick = (row) => {
  state.parentRow = row;
  state.parentPid = row.parentId;
  console.log('🚀 ~ handleNodeClick ~ state.parentPid:', state.parentPid);
  state.parentName = row.label;
  state.paramsQuery.folderId = row.id;
  getdocumentDataList();
  if (row.id === state.selectedNodeId) {
    // 如果当前节点已经选中，则取消选中
    state.selectedNodeId = null;
    state.parentPid = null; //关闭父级选择的id
    state.parentRow = null; //获取父级对象
    state.parentName = ''; //获取父级对应的名称
    state.paramsQuery.folderId = ''; //
  } else {
    // 否则选中当前节点 重新赋值
    state.selectedNodeId = row.id;
  }
};
// 获取文档列表数据
const getdocumentDataList = () => {
  if (!state.paramsQuery.folderId) {
    return;
  }
  state.loading = true;
  listKnowledgeDocument(state.paramsQuery).then((res: any) => {
    state.loading = false;
    if (res.code == 200) {
      state.infoList = res.rows;
      state.total = res.total;
    }
  });
};
// 查询tree树形结构数据
const filterFolder = (value: string, data: any) => {
  if (!value) return true;
  return data.name.includes(value);
};
const handleDelete = (row) => {
  // 删除文档
  let msg = '你确定要删除所选文件？';
  delFile(msg, row, () => {
    getdocumentDataList();
  });
};

//切换tab
const handleCheckMian = (tab, event) => {
  activeName.value = tab.name;
  if (activeName.value === 'first') {
    gettreeStructureData();
  } else {
    // 回收站
    recylingRef.value.getDocumentDataList();
  }
};

const onExportView = (row) => {
  console.log(row);
  proxy.$download.direct(row.fileUrl, row.originalName);
};
const updateName = (row) => {
  // 修改名称
  editName(row, '请输入文件名称', 1);
};
const handleView = (row) => {
  if (state.imgType.includes(row.fileSuffix)) {
    imgUrl.value = row.fileUrl;
    return;
  } else if (state.wordType.includes(row.fileSuffix)) {
    state.showDocumentDetail = true;
    nextTick(() => {
      documentDetailRef.value.openDialog(row);
    });
  } else {
    window.open(row.fileUrl);
  }
};
// 关闭在线编辑弹框
const onClose = () => {
  state.showDocumentDetail = false;
};
// 关闭修改的在线文档弹框
const onCloseEdit = () => {
  state.showdocumentDataEdit = false;
};
const updataView = (row) => {
  // 修改文档
  state.showdocumentDataEdit = true;
  nextTick(() => {
    documentDataEditRef.value.openDialog(row, '/design/technicalStandard/changxie/callback/');
  });
};
// 删除文件及文件夹
const delFile = (msg, data, cb) => {
  ElMessageBox.confirm(msg, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      delKnowledgeDocument([data.id]).then((res: any) => {
        if (res.code == 200) {
          ElMessage.success('删除成功');
          cb();
        }
      });
    })
    .catch(() => {});
};
const editName = (data, title, type) => {
  ElMessageBox.prompt(title, '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputErrorMessage: title,
    inputValue: data.fileName
  })
    .then(({ value }) => {
      documentDataEdit({ id: data.id, fileName: value }).then((res: any) => {
        if (res.code == 200) {
          ElMessage({
            type: 'success',
            message: '修改成功'
          });
          // 数据重新刷新
          if (type == 2) {
            gettreeStructureData();
          } else {
            getdocumentDataList();
          }
        } else {
          ElMessage({
            type: 'error',
            message: res.message
          });
        }
      });
    })
    .catch(() => {});
};
const onExport = () => {
  getUniFolderDownloadList(state.paramsQuery.folderId).then((res: any) => {
    if (res.code == 200) {
      console.log(state.paramsQuery.fileName);
      proxy.$download.downloadFilesAsZip(res.data, { urlKey: 'fileUrl', nameKey: 'originalName', zipName: state.parentName + '.zip' });
    }
  });
};

// 查看所有资料
const onBook = () => {
  bookFileRef.value.openDialog();
};

onMounted(() => {
  gettreeStructureData();
});
</script>

<style lang="scss" scoped>
.profile_engin {
  height: 80vh;
  .set-tool {
    display: none;
  }
  .el-tree-node__content:hover,
  .el-tree-node__content:active {
    .set-tool {
      display: inline-block;
    }
  }
  .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
    background-color: #354e67 !important;
    color: #fff;
  }
  .box_info {
    display: flex;
    justify-content: space-between;
  }
  .pagination-container {
    padding: 10px 0 !important;
  }
  > div {
    height: 100%;
    width: 100%;
  }
  .tree_left1 {
    width: 30%;
    background-color: #fff;
    border: 1px solid #dddddd;
    border-radius: 6px;
    padding: 6px 0px;
    position: relative;
    min-width: 26%;
    border-right: 6px solid;
    border-right-color: rgba(204, 230, 255, 0);
    .resize-handle-right {
      top: 0;
      width: 6px;
      height: 100%;
      right: -10px;
      cursor: ew-resize;
      position: absolute;
      z-index: 999;
    }
    .check_select {
      display: flex;
      align-items: center;
      width: 100%;
      // justify-content: space-between;
      padding: 4px;
      border-bottom: 1px solid #f1f1f1;
      .box_btn {
        margin: 0 10px 0 20px;
        position: relative;
        > span {
          padding: 4px 10px;
          background: #67c23a;
          color: #fff;
          border-radius: 2px;
        }
        .btn {
          position: absolute;
          left: 20%;
          display: none;
          top: -2px;
          width: 220px;
          .el-button {
            float: left;
          }
        }
      }
      .box_btn:hover,
      .box_btn:active {
        cursor: pointer;
        .btn {
          display: block;
        }
      }
    }
    .file_upload {
      margin: 2px 0;
    }
    .input_left {
      padding: 6px;
      box-sizing: border-box;
      // border-bottom: 1px solid #cbcbcb;
    }
  }
  .list_right {
    width: 69.5%;
    background: white;
    border: 1px solid #ededed;
    padding: 10px;
    box-sizing: border-box;
  }
  .el-tree {
    height: calc(80vh - 160px);
    width: 100%;
    overflow: auto !important;
  }
  // .el-tree-node__children {
  // 	overflow: visible !important;
  // }
}
</style>
