<template>
  <header>
    <div class="top-placeholder">
      <a-row type="flex">
        <a-col :span="23">
          <div style="display: flex">
            <a-button style="margin-bottom: 10px; margin-right: 20px" type="primary" @click="handleMutiAdd" preIcon="ant-design:cloud-upload-outlined"
              >上传</a-button
            >
            <a-input class="search-input" v-model:value="fileName" placeholder="查询名称" allow-clear />
            <a-input class="search-input" v-model:value="labelNames" placeholder="查询标签" allow-clear />
            <a-button style="margin-bottom: 10px; margin-right: 10px" type="primary" @click="handleSearch" preIcon="ant-design:search-outlined"
              >查询</a-button
            >
            <a-button style="margin-bottom: 10px; margin-right: 30px" type="primary" @click="searchReset" preIcon="ant-design:reload-outlined"
              >重置</a-button
            >
          </div>
        </a-col>
        <a-col :span="1">
          <a-button size="small" style="margin-top: 5px" @click="changeShowMode">
            <MenuOutlined v-if="isShowFolder" />
            <AppstoreOutlined v-else />
          </a-button>
        </a-col>
      </a-row>
    </div>
  </header>
  <main>
    <div v-show="isShowFolder">
      <a-row gutter="24">
        <a-col span="4" v-for="(item, index) in mergedData" :key="index">
          <div v-if="item.isFolder" class="folder" @dblclick.stop="handleSelect(item)">
            <FolderFilled style="font-size: 60px; color: #ffe486" />
            <div class="draggable ellipsis" draggable="true"> {{ item.fileName }}</div>
          </div>
          <a-dropdown v-else :trigger="['contextmenu']">
            <div class="folder" @dblclick="showFileContent(item)">
              <span style="font-size: 50px">
                <FileWordTwoTone v-if="item.fileTp == 'doc' || item.fileTp == 'docx'" />
                <FilePdfTwoTone v-else-if="item.fileTp == 'pdf'" />
                <FileTextTwoTone v-else />
              </span>
              <div @dragstart="dragStart" class="draggable ellipsis" draggable="true" style="margin-top: 10px"> {{ item.fileName }}</div>
            </div>
            <template #overlay>
              <a-menu @click="({ key: menuKey }) => onContextFileClick(item, menuKey)">
                <a-menu-item key="addCom"><Icon icon="ant-design:plus-outlined" />&nbsp;新增合规条目</a-menu-item>
                <!-- <a-menu-item key="addStr"><Icon icon="ant-design:plus-outlined" />&nbsp;新增内控策略</a-menu-item> -->
                <a-menu-item key="addCtrl"><Icon icon="ant-design:plus-outlined" />&nbsp;新增内控制度</a-menu-item>
                <a-menu-item key="addProblem"><Icon icon="ant-design:plus-outlined" />&nbsp;新增问题项</a-menu-item>
                <a-menu-item key="addPra"><Icon icon="ant-design:plus-outlined" />&nbsp;新增行业实践</a-menu-item>
                <a-menu-item key="addRisk"><Icon icon="ant-design:plus-outlined" />&nbsp;新增风险事件</a-menu-item>
                <a-menu-item style="background: #d9d9d9; height: 1px; padding: 1px" />
                <a-menu-item key="dowload">
                  <span><Icon icon="ant-design:download-outlined" />&nbsp;下载</span>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </a-col>
      </a-row>
    </div>
    <div v-show="!isShowFolder">
      <BasicTable @register="registerTable">
        <!--插槽:table标题-->
        <template #action="{ record }">
          <template v-if="!record.isFolder">
            <TableAction :actions="getTableAction(record)" />
          </template>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key == 'fileName'">
            <template v-if="record.isFolder">
              <FolderFilled style="color: #ffe486" />
              {{ record.fileName }}
            </template>
            <template v-else-if="record.fileTp == 'doc' || record.fileTp == 'docx'">
              <FileWordTwoTone />
              {{ record.fileName }}
            </template>
            <template v-else-if="record.fileTp == 'pdf'">
              <FilePdfTwoTone />
              {{ record.fileName }}
            </template>
            <template v-else>
              <FileTextTwoTone />
              {{ record.fileName }}
            </template>
          </template>
        </template>
        <!--字段回显插槽-->
        <template #htmlSlot="{ text }">
          <div v-html="text"></div>
        </template>
      </BasicTable>
    </div>
  </main>
  <DocMutiFilesModal @register="registerMutiModal" @success="handleSuccess" />
  <AuditComplianeItemModal @register="registerComModal" @success="handleSuccess" />
  <AuditInnerCtrlModal @register="registerStrModal" @success="handleSuccess" />
  <AuditInnerOrderModal @register="registerCtrlModal" @success="handleSuccess" />
  <AuditProblemModal @register="registerProbModal" @success="handleSuccess" />
  <AuditBestPracticeModal @register="registerPraModal" @success="handleSuccess" />
  <AuditRiskEventModal @register="registerRiskModal" @success="handleSuccess" />
  <ShowFileContentModal @register="registerShowFileContentModal" />
</template>

<script lang="ts" name="doc-docFiles" setup>
  import { ref, computed, unref, onMounted, defineProps, useAttrs } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage';
  import DocMutiFilesModal from '/@/views/doc/components/DocMutiFilesModal.vue';
  import { columns, searchFormSchema } from '/@/views/doc/DocFiles.data';
  import { list, deleteOne, batchDelete, queryAllList } from '/@/views/doc/DocFiles.api';
  import { getChildList } from '/@/views/doc/DocFilesDir.api';
  import { getAllDataByFileId } from './AuditDoc.api';
  import { Base64 } from 'js-base64';
  import { FolderFilled, FileTextTwoTone, MenuOutlined, AppstoreOutlined, FileWordTwoTone, FilePdfTwoTone } from '@ant-design/icons-vue';
  import ShowFileContentModal from '../modal/ShowFileContentModal.vue';
  import AuditComplianeItemModal from '../modal/AuditComplianeItemModal.vue';
  import AuditInnerCtrlModal from '../modal/AuditInnerCtrlModal.vue';
  import AuditInnerOrderModal from '../modal/AuditInnerOrderModal.vue';
  import AuditProblemModal from '../modal/AuditProblemModal.vue';
  import AuditBestPracticeModal from '../modal/AuditBestPracticeModal.vue';
  import AuditRiskEventModal from '../modal/AuditRiskEventModal.vue';
  const $attrs = useAttrs();
  const fileName = ref('');
  const labelNames = ref('');
  const treeNodeData = ref();
  const mergedData = ref([]);
  const listData = ref([]);
  const emit = defineEmits(['selectFolder', 'refresh']);
  function clickChild() {
    emit('refresh');
  }
  let fileList = ref([]);
  const previewVisible = ref(false);
  const handleCancel = () => {
    previewVisible.value = false;
    // previewTitle.value = '';
  };
  const handlePreview = async (file: UploadProps['fileList'][number]) => {
    if (!file.url && !file.preview) {
      file.preview = (await getBase64(file.originFileObj)) as string;
    }
    // previewImage.value = file.url || file.preview;
    previewVisible.value = true;
    // previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
  };
  //注册model
  const [registerMutiModal, { openModal: openMutiModal }] = useModal();
  const [registerComModal, { openModal: openComModal }] = useModal();
  const [registerCtrlModal, { openModal: openCtrlModal }] = useModal();
  const [registerStrModal, { openModal: openStrModal }] = useModal();
  const [registerProbModal, { openModal: openProbModal }] = useModal();
  const [registerPraModal, { openModal: openPraModal }] = useModal();
  const [registerRiskModal, { openModal: openRiskModal }] = useModal();
  const [registerShowFileContentModal, { openModal: openFileContentModel }] = useModal();
  //注册table数据
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: '',
      // api: list,
      dataSource: mergedData,
      columns,
      canResize: true,
      size: 'small',
      striped: true,
      scroll: { y: 500 },
      useSearchForm: false,
      showTableSetting: false,
      pagination: false,
      actionColumn: {
        width: 350,
        // fixed: 'right',
      },
    },
  });

  const [registerTable, { reload }, { rowSelection, selectedRowKeys }] = tableContext;
  const ctp = ref();
  const fileDirs = ref();

  function handleMutiAdd() {
    openMutiModal(true, {
      record: { ctp: ctp.value },
      isUpdate: false,
      showFooter: false,
    });
  }

  async function handleComAdd(record: Recordable, tp: any) {
    tp = 1;
    record.child = listData.value = await getAllDataByFileId(record.id, tp);
    openComModal(true, {
      docFile: record,
      isUpdate: false,
    });
  }
  async function handleStrAdd(record: Recordable, tp: any) {
    tp = 2;
    record.child = listData.value = await getAllDataByFileId(record.id, tp);
    openStrModal(true, {
      docFile: record,
      isUpdate: false,
    });
  }
  async function handleCtrlAdd(record: Recordable, tp: any) {
    tp = 3;
    record.child = listData.value = await getAllDataByFileId(record.id, tp);
    openCtrlModal(true, {
      docFile: record,
      isUpdate: false,
    });
  }
  async function handleProbAdd(record: Recordable, tp: any) {
    tp = 4;
    record.child = listData.value = await getAllDataByFileId(record.id, tp);
    openProbModal(true, {
      docFile: record,
      isUpdate: false,
    });
  }
  async function handlePraAdd(record: Recordable, tp: any) {
    tp = 7;
    record.child = listData.value = await getAllDataByFileId(record.id, tp);
    openPraModal(true, {
      docFile: record,
      isUpdate: false,
    });
  }
  async function handleRiskAdd(record: Recordable, tp: any) {
    tp = 6;
    record.child = listData.value = await getAllDataByFileId(record.id, tp);
    openRiskModal(true, {
      docFile: record,
      isUpdate: false,
    });
  }
  async function handleSuccess() {
    fileList.value = await queryAllList({ ctp: treeNodeData.value.key });
    mergedData.value = mergedData.value.filter((item) => item.isFolder).concat(fileList.value);
  }

  function getTableAction(record) {
    return [
      {
        label: '新增合规条目',
        onClick: handleComAdd.bind(null, record),
      },
      // {
      //   label: '新增内控策略',
      //   onClick: handleStrAdd.bind(null, record),
      // },
      {
        label: '新增内控制度',
        onClick: handleCtrlAdd.bind(null, record),
      },
    ];
  }

  // 文件操作
  const onContextFileClick = (item, menuKey: string) => {
    if (menuKey == 'addCom') {
      handleComAdd(item);
    } else if (menuKey == 'addStr') {
      handleStrAdd(item);
    } else if (menuKey == 'addCtrl') {
      handleCtrlAdd(item);
    } else if (menuKey == 'addProblem') {
      handleProbAdd(item);
    } else if (menuKey == 'addPra') {
      handlePraAdd(item);
    } else if (menuKey == 'addRisk') {
      handleRiskAdd(item);
    } else if (menuKey == 'dowload') {
      handleDownloadFile(item);
    }
  };

  async function setFileCtp(data) {
    if (data) {
      ctp.value = data.key;
      treeNodeData.value = data;
      fileDirs.value = data.children;
      fileList.value = await queryAllList({ ctp: data.key });
      let folderArr = [];
      if (fileDirs.value) {
        folderArr = fileDirs.value.map((item) => {
          return {
            fileName: item.title,
            label: item.otherData?.label,
            //children: item.children,
            isFolder: true,
            key: item.key,
          };
        });
        //树结构和文件列表合并
        mergedData.value = folderArr.concat(fileList.value);
      } else {
        mergedData.value = fileList.value;
      }
    } else {
      fileList.value = [];
      fileDirs.value = [];
    }
  }

  function handleGoFile(item) {
    let globOnlineViewUrl: string = import.meta.env.VITE_GLOB_ONLINE_VIEW_URL;
    let globOnlineViewServerUrl: string = import.meta.env.VITE_GLOB_ONLINE_VIEW_SERVER_URL;
    let urlpath = globOnlineViewUrl + item.filePath;
    urlpath = encodeURIComponent(Base64.encode(urlpath));
    window.open(globOnlineViewServerUrl + '?url=' + urlpath);
  }

  const draggingNode = ref();

  const dragStart = (event: DragEvent) => {
    const node = event.target as HTMLElement;
    draggingNode.value = node;
    event.dataTransfer.setData('text/plain', node.innerText);
  };

  function handleSelect(item) {
    emit('selectFolder', item);
  }

  async function searchData() {
    let paramDirs = { labelNames: labelNames.value };
    let paramFile = { labelNames: labelNames.value };

    paramFile['fileName'] = '*' + fileName.value + '*';
    paramDirs['name'] = '*' + fileName.value + '*';

    fileDirs.value = await getChildList(paramDirs);
    fileList.value = await queryAllList(paramFile);
    if (fileDirs.value) {
      fileDirs.value.forEach(function (item) {
        item['title'] = item['name'];
        item['fileName'] = item['name'];
        item['isFolder'] = true;
        item['key'] = item['id'];
        item['parentId'] = item['pid'];
      });
      mergedData.value = fileDirs.value.concat(fileList.value);
    } else {
      mergedData.value = fileList.value;
    }
  }

  async function handleSearch() {
    if (!fileName.value && !labelNames.value) {
      return;
    }

    searchData();
  }

  function searchReset() {
    fileName.value = '';
    labelNames.value = '';
    setFileCtp(treeNodeData.value);
  }

  const isShowFolder = ref<Boolean>(true);

  function changeShowMode() {
    isShowFolder.value = !isShowFolder.value;
  }

  function handleDownloadFile(item) {
    let globOnlineViewUrl: string = import.meta.env.VITE_GLOB_ONLINE_VIEW_URL;
    let url = globOnlineViewUrl + item.filePath;

    if (url) {
      window.open(url);
    }
  }
  function showFileContent(item) {
    if (item.filePath) {
      openFileContentModel(true, {
        record: item,
        isUpdate: false,
        showFooter: true,
      });
    }
  }
  defineExpose({
    setFileCtp,
  });
</script>

<style scoped>
  header {
    height: 50px;
  }
  .top-placeholder {
    height: 50px;
    border-bottom: 1px solid #d9d9d9;
  }
  .search-input {
    max-width: 25%;
    height: 32px;
    margin-right: 10px;
  }
  main {
    height: calc(90vh - 200px);
    overflow-y: auto;
  }
  .folder {
    width: 160px;
    height: 150px;
    margin-top: 20px;
    text-align: -webkit-center;
  }
  .ellipsis:hover {
    overflow: visible;
    text-overflow: inherit;
    display: block;
  }
  .ellipsis {
    /* white-space: nowrap; */
    width: 8em;
    text-overflow: ellipsis;
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
  ::-webkit-scrollbar {
    /* 隐藏滚动条 */
    display: none;
  }
</style>
