<template>
    <div class="auditDocument">
        <el-row>
            <el-col :span="12">
                <h3>{{ isManage || isAudit ? $t('trials:tab:updateAuditDocument') : $t('trials:tab:viewAuditDocument')
                    }}
                </h3>
            </el-col>
            <el-col :span="12" style="text-align:right;">
                <h3>
                    <Pagination class="page" :total="total" :page.sync="searchData.pageIndex"
                        :limit.sync="searchData.pageSize" layout="total, sizes, prev, pager, next" :background="false"
                        style="display: inline-block;" @pagination="getList" />
                    <el-button icon="el-icon-refresh-left" size="small" circle :title="$t('common:button:reset')"
                        @click="handleReset" />
                </h3>
            </el-col>
        </el-row>
        <el-form :inline="true" class="base-search-form">
            <el-form-item>
                <el-input v-model="searchData.Name" clearable
                    :placeholder="$t('trials:trials-workbench:auditDocument:placeholder:search')"></el-input>
            </el-form-item>
            <el-form-item v-show="false">
                <el-input v-model="searchData.Name" clearable
                    :placeholder="$t('trials:trials-workbench:auditDocument:placeholder:search')"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">
                    {{ $t('common:button:search') }}
                </el-button>
                <el-button type="primary" icon="el-icon-refresh-left" @click="handleReset">
                    {{ $t('common:button:reset') }}
                </el-button>
            </el-form-item>
            <el-form-item v-if="isManage">
                <el-button type="primary" @click.stop="addFolder">
                    {{ $t('trials:trials-workbench:auditDocument:button:addFolder') }}
                </el-button>
                <el-button type="primary" @click.stop="openFile(false)">
                    {{ $t('trials:trials-workbench:auditDocument:button:uploadFile') }}
                </el-button>
                <el-button type="primary" @click.stop="openFile(true)">
                    {{ $t('trials:trials-workbench:auditDocument:button:uploadFolder') }}
                </el-button>
                <el-button type="primary" :disabled="checkList.length <= 0" @click.stop="auth(true)">
                    {{ $t('trials:trials-workbench:auditDocument:button:auth') }}
                </el-button>
                <el-button type="primary" :disabled="checkList.length <= 0" @click.stop="downLoad(checkList)">
                    {{ $t('trials:trials-workbench:auditDocument:button:download') }}
                </el-button>
                <el-button type="primary" :disabled="checkList.length <= 0" @click.stop="delData(checkList)">
                    {{ $t('trials:trials-workbench:auditDocument:button:del') }}
                </el-button>
            </el-form-item>
            <el-form-item v-if="isAudit">
                <el-button type="primary" :disabled="checkList.length <= 0" @click.stop="auditAuth(true)">
                    {{ $t('trials:trials-workbench:auditDocument:button:auth') }}
                </el-button>
            </el-form-item>
        </el-form>
        <div class="catalogue">
            <span>{{ $t('trials:trials-workbench:auditDocument:catalogue:title') }}</span>
            <el-button icon="el-icon-top" class="last_catalogue" :disabled="!Id" @click.stop="toCatalogue(false)"
                :title="$t('trials:trials-workbench:auditDocument:catalogue:lastCatalogue')"></el-button>
            <el-breadcrumb separator-class="el-icon-arrow-right" class="catalogue_name_box">
                <el-breadcrumb-item v-for="item of catalogueData" :key="item.Id">
                    <span class="catalogue_name" @click.stop="toCatalogue(item)">{{ item.Name }}</span>
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <el-table id="auditDocumentTable" ref="auditDocumentTable" :data="tableData" style="width: 99%" row-key="Id"
            :loading="loading" :row-style="setRowStyle" v-adaptive="{ bottomOffset: 75 }" height="100" :border="true"
            :expand-row-keys="expandedRows" :tree-props="{ children: 'Children', hasChildren: 'hasChildren' }"
            @sort-change="handleSortByColumn" @expand-change="handleExpandChange" @row-click="handleRowClick"
            @cell-mouse-enter="handleCellMouseEnter" @cell-mouse-leave="handleCellMouseLeave"
            @row-contextmenu="handleRowContextmenu" @row-dblclick="handleRowDblclick">
            <el-table-column prop="Name" :label="$t('trials:trials-workbench:auditDocument:table:name')"
                sortable="custom" min-width="300" class-name="catalogue_box">
                <template slot-scope="scope">
                    <div class="name_layout_box">
                        <div class="name_layout" v-if="renameId !== scope.row.Id">
                            <span class="name_box">
                                <i class="icon icon_folder" v-if="!scope.row.AuditDocumentTypeEnum" />
                                <img v-else-if="['png', 'jpg', 'jpeg'].includes(scope.row.FileFormat.toLowerCase())"
                                    :src="OSSclientConfig.basePath + scope.row.FilePath" alt="" class="icon_image">
                                <i v-else :class="`icon icon_file icon_${scope.row.FileFormat}`" />
                                <span class="name" :title="scope.row.Name">{{ scope.row.Name }}</span>
                                <i class="el-icon-edit icon_edit" v-if="(hoverId === scope.row.Id) && isManage"
                                    @click="addRenameId(scope.row)"
                                    :title="$t('trials:trials-workbench:auditDocument:icon:rename')" />
                            </span>
                            <i :class="{ 'el-icon-success': true, 'icon_check': true, isCheck: checkList.includes(scope.row.Id) }"
                                @click.stop="addCheck(scope.row)"
                                v-if="(hoverId === scope.row.Id || checkList.includes(scope.row.Id)) && (isManage || isAudit)" />
                            <span class="version"
                                v-if="(hoverId !== scope.row.Id && !checkList.includes(scope.row.Id)) && isManage && scope.row.HistoricalVersionsCount > 0">
                                <i class="el-icon-warning-outline"></i>{{ scope.row.HistoricalVersionsCount }}
                            </span>
                        </div>
                        <el-input v-model="scope.row.Name" :ref="`renameInp_${scope.row.Id}`" :autofocus="true"
                            class="renameInp" @blur="rename(scope.row)" v-else />
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="FileFormat" :label="$t('trials:trials-workbench:auditDocument:table:fileType')">
                <template slot-scope="scope">
                    <span>{{ formatFileType(scope.row) }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="FileSize" :label="$t('trials:trials-workbench:auditDocument:table:fileSize')">
                <template slot-scope="scope">
                    <span>{{ formatFileSize(scope.row) }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="IsAuthorization"
                :label="$t('trials:trials-workbench:auditDocument:table:IsAuthorization')" show-overflow-tooltip
                v-if="isManage">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.IsAuthorization" @change="(val) => auth(false, scope.row, val)"
                        :active-value="true" :inactive-value="false" :active-text="$fd('YesOrNo', true)"
                        class="IsAuthorization_swich" :inactive-text="$fd('YesOrNo', false)">
                    </el-switch>
                </template>
            </el-table-column>
            <el-table-column prop="IsCurrentAuditRecordAuthorization"
                :label="$t('trials:trials-workbench:auditDocument:table:IsAuthorization')" show-overflow-tooltip
                v-if="isAudit">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.IsCurrentAuditRecordAuthorization"
                        @change="(val) => auditAuth(false, scope.row, val)" :active-value="true" :inactive-value="false"
                        :active-text="$fd('YesOrNo', true)" class="IsAuthorization_swich"
                        :inactive-text="$fd('YesOrNo', false)">
                    </el-switch>
                </template>
            </el-table-column>
            <el-table-column prop="UpdateTime" show-overflow-tooltip
                :label="$t('trials:trials-workbench:auditDocument:table:updateTime')">
            </el-table-column>
            <el-table-column prop="CreateTime" show-overflow-tooltip
                :label="$t('trials:trials-workbench:auditDocument:table:createTime')">
            </el-table-column>
        </el-table>
        <contextmenu ref="contextmenu" :isCopy="isCopy" :checkList="checkList" @handleMenu="handleMenu" />
        <upload-files :config="config" :faccept="faccept" :uploadPath="uploadPath" :limitLength="limitLength"
            v-if="config.visible" @close="close" @uplaodFile="uplaodFile" />
        <detail ref="versionDetail" v-if="visible" :visible.sync="visible" :rowData="rowData"
            @openContextmenu="openContextmenu" @openFileNewVersion="openFileNewVersion" @delData="delData" />
        <viewer ref="picture_perview" style="margin: 0 10px"
            v-if="rowData.FileFormat && ['png', 'jpg', 'jpeg'].includes(rowData.FileFormat.toLowerCase())"
            :images="[`${OSSclientConfig.basePath}${rowData.FilePath}`]" :options="viewerOptions">

            <img v-show="false" :src="`${OSSclientConfig.basePath}${rowData.FilePath}`" alt="Image" />
        </viewer>
    </div>
</template>
<script>
import { getAuditDocumentData, addAuditDocument, getBreadcrumbData, updateAuditDocument, deleteAuditDocument, setCurrentVersion, movieFileOrFolder, copyFileOrFolder, setIsAuthorization, addFolder, setAuditRecordPermission } from '@/api/trials'
import Pagination from '@/components/Pagination'
import contextmenu from './contextmenu.vue'
import uploadFiles from '@/views/trials/trials-panel/trial-summary/trial-document/components/uploadFiles.vue'
import detail from './detail.vue'
import { downLoadFile } from '@/utils/stream.js'
const searchDataDefault = () => {
    return {
        Name: null,
        PageIndex: 1,
        PageSize: 20,
        Asc: false,
        SortField: ''
    }
}
export default {
    name: "auditDocument",
    components: { Pagination, contextmenu, uploadFiles, detail },
    props: {
        isManage: {
            type: Boolean,
            default: false
        },
        AuditRecordId: {
            type: String,
            default: ''
        },
        isAudit: {
            type: Boolean,
            default: false
        },
    },
    computed: {
        isCopy() {
            return (this.copyList && this.copyList.length > 0) || this.shearList && this.shearList.length > 0
        }
    },
    data() {
        return {
            searchData: searchDataDefault(),
            total: 0,
            Id: null,
            loading: false,
            expandedRows: [],
            tableData: [],
            catalogueData: [], // 目录层级

            visible: false, // 属性详情弹框
            rowData: {}, // 属性详情数据

            config: {
                visible: false,
                showClose: true,
                width: '800px',
                title: '',
                appendToBody: false,
                isFolder: false,
                isVersion: false
            },
            uploadPath: '/System/AuditDocument',
            faccept: ['.pdf'],
            limitLength: 0,

            checkList: [], // 选中的数据
            hoverId: null, // hover中的数据
            renameId: null, // 选中重命名的数据

            copyList: [], // 选中复制的数据
            shearList: [], // 选中剪切的数据
            type: null, // 操作类型（右键菜单、键盘操作）

            ctrlKey: false, // 键盘ctrl键是否按下

            viewerOptions: {
                toolbar: {
                    zoomIn: true,
                    zoomOut: true,
                    reset: true,
                    prev: false,
                    next: false,
                    rotateLeft: true,
                    rotateRight: true,
                    flipHorizontal: true,
                    flipVertical: true,
                }
            }
        }
    },
    watch: {
        isManage() {
            this.Id = null;
            this.resetOpt()
            this.getBreadcrumbData()
            this.getList()
        }
    },
    methods: {
        async auditAuth(isArray = true, row, IsAuthorization) {
            if (!this.isAudit) return false
            try {
                let data = {}
                if (isArray) {
                    data = {
                        AuditDocumentIdList: this.checkList,
                        AuditRecordId: this.AuditRecordId,
                        IsAuthorization: true,
                    }
                } else {
                    data = {
                        AuditDocumentIdList: [row.Id],
                        AuditRecordId: this.AuditRecordId,
                        IsAuthorization,
                    }
                }
                this.loading = true
                let res = await setAuditRecordPermission(data)
                this.loading = false
                if (res.IsSuccess) {
                    this.$t('trials:trials-workbench:auditDocument:message:authSuccessfully')
                    // if (isArray) {
                    this.getList()
                    // }
                }
            } catch (err) {
                this.loading = false
                if (!isArray) {
                    row.IsCurrentAuditRecordAuthorization = !row.IsCurrentAuditRecordAuthorization
                }
                console.log(err)
            }
        },
        async auth(isArray = true, row, IsAuthorization) {
            if (!this.isManage) return false
            try {
                let data = {}
                if (isArray) {
                    data = {
                        Ids: this.checkList,
                        IsAuthorization: true,
                    }
                } else {
                    data = {
                        Ids: [row.Id],
                        IsAuthorization,
                    }
                }
                this.loading = true
                let res = await setIsAuthorization(data)
                this.loading = false
                if (res.IsSuccess) {
                    this.$t('trials:trials-workbench:auditDocument:message:authSuccessfully')
                    // if (isArray) {
                    this.getList()
                    // }
                }
            } catch (err) {
                this.loading = false
                if (!isArray) {
                    row.IsAuthorizedView = !row.IsAuthorizedView
                }
                console.log(err)
            }
        },
        // 新建文件夹
        addFolder() {
            if (!this.isManage) return false
            let data = {
                ParentId: null,
                repeat: 0,
                Type: "addFolder",
                Name: this.$t("trials:trials-workbench:auditDocument:opt:addFloder"),
                IsAuthorization: false,
                AuditDocumentTypeEnum: 0,
                Id: `addFolder_${Date.now()}`,
                Children: []
            }
            data.ParentId = this.Id
            this.tableData.forEach(item => {
                if (item.Name === data.Name) {
                    data.repeat++;
                    data.Name = `${this.$t("trials:trials-workbench:auditDocument:opt:addFloder")}(${data.repeat})`
                }
            })
            this.tableData.unshift(data)
            this.addRenameId(data)
            // let parentData = {}
            // if (!this.rowData || !this.rowData.Id) {
            //     data.ParentId = this.Id
            //     this.tableData.forEach(item => {
            //         if (item.Name === data.Name) {
            //             data.repeat++;
            //             data.Name = `${this.$t("trials:trials-workbench:auditDocument:opt:addFloder")}(${data.repeat})`
            //         }
            //     })
            //     this.tableData.unshift(data)
            //     this.addRenameId(data)
            // } else {
            //     if (!this.rowData.AuditDocumentTypeEnum) {
            //         parentData = this.getData(this.tableData, this.rowData.Id)
            //         data.ParentId = parentData.Id
            //         parentData.Children.forEach(item => {
            //             if (item.Name === data.Name) {
            //                 data.repeat++;
            //                 data.Name = `${this.$t("trials:trials-workbench:auditDocument:opt:addFloder")}(${data.repeat})`
            //             }
            //         })
            //         if (!this.expandedRows.includes(parentData.Id)) {
            //             this.expandedRows.push(parentData.Id)
            //             this.$refs.auditDocumentTable.toggleRowExpansion(parentData, true)
            //         }
            //         parentData.Children.unshift(data)
            //         this.addRenameId(data)
            //     } else {
            //         let fileData = this.getData(this.tableData, this.rowData.Id)
            //         if (fileData.ParentId === this.Id) {
            //             data.ParentId = this.Id
            //             this.tableData.forEach(item => {
            //                 if (item.Name === data.Name) {
            //                     data.repeat++;
            //                     data.Name = `${this.$t("trials:trials-workbench:auditDocument:opt:addFloder")}(${data.repeat})`
            //                 }
            //             })
            //             this.tableData.unshift(data)
            //             this.addRenameId(data)
            //         } else {
            //             parentData = this.getData(this.tableData, this.fileData.ParentId)
            //             data.ParentId = parentData.Id
            //             parentData.Children.forEach(item => {
            //                 if (item.Name === data.Name) {
            //                     data.repeat++;
            //                     data.Name = `${this.$t("trials:trials-workbench:auditDocument:opt:addFloder")}(${data.repeat})`
            //                 }
            //             })
            //             parentData.Children.unshift(data)
            //             this.addRenameId(data)
            //         }
            //     }
            // }
        },
        // 获取当前目录层级
        async getBreadcrumbData() {
            if (!this.Id) return this.catalogueData = []
            try {
                let data = {
                    Id: this.Id
                }
                let res = await getBreadcrumbData(data)
                if (res.IsSuccess) {
                    this.catalogueData = res.Result
                }
            } catch (err) { console.log(err) }
        },
        async getList(id) {
            try {
                this.searchData.Id = this.Id
                this.loading = true
                if (!this.isManage) {
                    this.searchData.IsAuthorization = true
                } else {
                    this.searchData.IsAuthorization = null
                }
                if (this.AuditRecordId) this.searchData.AuditRecordId = this.AuditRecordId
                if (!this.isAudit) {
                    this.searchData.IsCurrentAuditRecordAuthorization = true
                } else {
                    this.searchData.IsCurrentAuditRecordAuthorization = null
                }
                let res = await getAuditDocumentData(this.searchData)
                this.loading = false
                if (res.IsSuccess) {
                    this.tableData = res.Result.CurrentPageData
                    this.total = res.Result.TotalCount
                    if (this.$refs.versionDetail) {
                        this.checkList = [id]
                        this.rowData = this.getData(this.tableData, id)
                    }
                }
            } catch (err) {
                this.loading = false
                console.log(err)
            }
        },
        // 排序
        handleSortByColumn(column) {
            if (column.order === 'ascending') {
                this.searchData.asc = true
            } else {
                this.searchData.asc = false
            }
            this.searchData.sortField = column.prop
            this.getList()
        },
        // 下载
        async downLoad(list, row = {}) {
            if (!this.isManage) return false
            try {
                if (row.Id && row.AuditDocumentTypeEnum) {
                    let name = row.Name.split('.')[1] ? row.Name : `${row.Name}.${row.FileFormat}`
                    return await downLoadFile(
                        this.OSSclientConfig.basePath + row.FilePath,
                        name
                    )
                }
                let arr = this.filterExternalIds(this.tableData, list)
                if (arr && arr.length === 1) {
                    let data = this.getData(this.tableData, arr[0])
                    if (data.AuditDocumentTypeEnum) {
                        let name = data.Name.split('.')[1] ? data.Name : `${data.Name}.${data.FileFormat}`
                        return await downLoadFile(
                            this.OSSclientConfig.basePath + data.FilePath,
                            name
                        )
                    } else {
                        let dataArray = this.getDataPath([data])
                        let files = this.formatDownloadFile(dataArray)
                        let name = `${data.Name}_${new Date().getTime()}.zip`
                        return await downLoadFile(files, name, 'zip')
                    }
                } else {
                    let name = null
                    let id = this.findDeepestCommonParent(this.tableData, arr)
                    if (id) {
                        let d = this.getData(this.tableData, id)
                        name = `${d.Name}_${new Date().getTime()}.zip`
                    } else {
                        name = `AuditDocument_${new Date().getTime()}.zip`
                    }
                    let data = arr.map(id => this.getData(this.tableData, id))
                    let dataArray = this.getDataPath(data)
                    let files = this.formatDownloadFile(dataArray)
                    return await downLoadFile(files, name, 'zip')
                }
            } catch (err) {
                console.log(err)
            }
        },
        formatDownloadFile(list) {
            let files = []
            for (const item of list) {
                let obj = {
                    name: item.Name.split('.')[1] ? item.Path : `${item.Path}.${item.FileFormat}`,
                    url: this.OSSclientConfig.basePath + item.FilePath
                }
                files.push(obj)
            }
            return files
        },
        findDeepestCommonParent(rootNodes, ids) {
            // 构建节点ID到节点的映射
            const nodeMap = new Map();
            function buildMap(nodes) {
                for (const node of nodes) {
                    nodeMap.set(node.Id, node);
                    if (node.Children && node.Children.length > 0) {
                        buildMap(node.Children);
                    }
                }
            }
            buildMap(rootNodes);

            // 生成每个ID的路径数组（从根到当前节点）
            const paths = [];
            for (const id of ids) {
                const path = [];
                let currentNode = nodeMap.get(id);
                if (!currentNode) continue; // 忽略无效ID

                // 向上遍历直到根节点
                while (currentNode) {
                    path.unshift(currentNode.Id); // 插入到前面以形成根到当前路径
                    const parentId = currentNode.ParentId;
                    if (parentId === null) break; // 根节点无父节点
                    currentNode = nodeMap.get(parentId);
                }
                paths.push(path);
            }

            if (paths.length === 0) return null; // 无有效ID

            // 寻找最长公共前缀
            const findLongestCommonPrefix = (paths) => {
                if (paths.length === 0) return [];
                let common = paths[0];
                for (let i = 1; i < paths.length; i++) {
                    const currentPath = paths[i];
                    let j = 0;
                    while (j < common.length && j < currentPath.length && common[j] === currentPath[j]) {
                        j++;
                    }
                    common = common.slice(0, j);
                    if (common.length === 0) break;
                }
                return common;
            };

            const lcp = findLongestCommonPrefix(paths);
            return lcp.length > 0 ? lcp[lcp.length - 1] : null;
        },
        getDataPath(list, str = '', ARRAY = []) {
            for (const item of list) {
                if (!str) {
                    item.Path = item.Name
                } else {
                    item.Path = str + '/' + item.Name
                }
                if (item.AuditDocumentTypeEnum) {
                    ARRAY.push(item)
                    continue
                } else {
                    if (item.Children && item.Children.length > 0) {
                        this.getDataPath(item.Children, item.Path, ARRAY)
                    }
                }
            }
            return ARRAY
        },
        getData(list, Id, data = {}) {
            for (const item of list) {
                if (item.Id === Id) {
                    data = item
                    break
                } else {
                    if (item.Children && item.Children.length > 0) {
                        data = this.getData(item.Children, Id, data)
                    }
                }

            }
            return data
        },
        filterExternalIds(tree, ids) {
            if (!tree || tree.length === 0 || !ids || ids.length === 0) return [];
            const parentMap = this.buildParentMap(tree);
            const idSet = new Set(ids);
            const externalIds = new Set();

            for (const id of ids) {
                let currentId = parentMap.get(id);
                while (currentId !== null) {
                    if (idSet.has(currentId)) {
                        externalIds.add(currentId);
                    }
                    currentId = parentMap.get(currentId);
                }
            }

            return ids.filter(id => !externalIds.has(id));
        },
        buildParentMap(tree) {
            const parentMap = new Map();
            const traverse = (node, parentId) => {
                parentMap.set(node.Id, parentId);
                for (const child of node.Children) {
                    traverse(child, node.Id);
                }
            };
            for (const root of tree) {
                traverse(root, null);
            }
            return parentMap;
        },
        handleSearch() {
            this.getList()
        },
        handleReset() {
            this.searchData = searchDataDefault()
            this.getList()
        },
        addCheck(row) {
            if (!this.isManage && !this.isAudit) return false
            let index = this.checkList.indexOf(row.Id)
            if (!!~index) {
                this.checkList.splice(index, 1)
            } else {
                this.checkList.push(row.Id)
            }

        },
        addRenameId(row) {
            if (!this.isManage) return false
            this.renameId = row.Id
            this.$nextTick(() => {
                if (this.$refs[`renameInp_${row.Id}`]) {
                    this.$refs[`renameInp_${row.Id}`].focus()
                }
            })
        },
        async rename(row) {
            if (!this.isManage) return false
            try {
                if (!row.Name) {
                    this.$message.warning(this.$t("trials:trials-workbench:auditDocument:noFolderName"))
                    return this.addRenameId(row)
                }
                this.renameId = null
                if (row.Type === 'addFolder') {
                    delete row.Id
                    let data = row
                    let res = await addFolder(data)
                    if (res.IsSuccess) {
                        this.getList()
                    }
                } else {
                    this.updateData(row)
                }
            } catch (err) {
                if (row.Type === 'addFolder') {
                    this.getList()
                }
                console.log(err)
            }

        },
        handleExpandChange(row, expanded) {
            if (expanded && !this.expandedRows.find(Id => Id === row.Id)) {
                this.expandedRows.push(row.Id)
            }
            if (!expanded) {
                let index = this.expandedRows.indexOf(row.Id)
                if (!!~index) {
                    this.expandedRows.splice(index, 1)
                }
            }
        },
        // 重置所有操作
        resetOpt() {
            this.expandedRows = []
            this.checkList = []
            this.hoverId = null
            this.renameId = null
            this.copyList = []
            this.shearList = []
            this.rowData = {}
        },
        // 跳转至目录
        toCatalogue(row) {
            if (!row) {
                let data = this.catalogueData[this.catalogueData.length - 2]
                if (data) {
                    return this.toCatalogue(data)
                } else {
                    row = {}
                }

            }
            this.Id = row.Id
            this.resetOpt()
            this.getList()
            this.getBreadcrumbData()
        },
        // 设置当前版本
        async setCurrentVersion(Id) {
            if (!this.isManage) return false
            try {
                let data = {
                    Id
                }
                let res = await setCurrentVersion(data)
                if (res.IsSuccess) {
                    this.getList(Id)
                }
            } catch (err) {
                console.log(err)
            }
        },
        // 复制数据
        async copyData(list) {
            if (!this.isManage) return false
            try {
                let DATA = this.getData(this.tableData, this.checkList[0])
                let Ids = this.filterExternalIds(this.tableData, list)
                let data = {
                    Ids: Ids,
                    ParentId: DATA.AuditDocumentTypeEnum ? DATA.ParentId : DATA.Id
                }
                let res = await copyFileOrFolder(data)
                if (res.IsSuccess) {
                    this.getList()
                    this.copyList = []
                }
            } catch (err) {
                console.log(err)
            }
        },
        // 移动数据
        async moveData(list) {
            if (!this.isManage) return false
            try {
                let DATA = this.getData(this.tableData, this.checkList[0])
                let Ids = this.filterExternalIds(this.tableData, list)
                let data = {
                    Ids: Ids,
                    ParentId: DATA.AuditDocumentTypeEnum ? DATA.ParentId : DATA.Id
                }
                let res = await movieFileOrFolder(data)
                if (res.IsSuccess) {
                    this.getList()
                    this.shearList = []
                }
            } catch (err) {
                console.log(err)
            }
        },
        // 删除数据
        async delData(Ids) {
            if (!this.isManage) return false
            try {
                let confirm = await this.$confirm(this.$t('trials:trials-workbench:auditDocument:delData'))
                if (!confirm) return false
                let data = { Ids }
                let res = await deleteAuditDocument(data)
                if (res.IsSuccess) {
                    this.checkList = []
                    if (this.$refs.versionDetail) {
                        // this.$refs.versionDetail.getHistoricalVersion()
                        this.getList(this.rowData.Id)
                        this.checkList = [this.rowData.Id]
                    } else {
                        this.getList()
                        this.rowData = {}
                    }
                }
            } catch (err) {
                console.log(err)
            }
        },
        // 修改数据
        async updateData(row) {
            if (!this.isManage) return false
            try {
                let data = {
                    AuditDocumentTypeEnum: row.AuditDocumentTypeEnum,
                    FileFormat: row.FileFormat,
                    FilePath: row.FilePath,
                    FileSize: row.FileSize,
                    Id: row.Id,
                    IsAuthorization: row.IsAuthorization,
                    Name: row.Name,
                    ParentId: row.ParentId

                }
                let res = await updateAuditDocument(data);
                if (res.IsSuccess) {
                    this.getList()
                }
            } catch (err) {
                this.getList()
                console.log(err)
            }
        },
        // 新增列表数据
        async uplaodFile(list) {
            if (!this.isManage) return false
            let data = []
            if (this.config.isVersion) {
                data.push({
                    ParentId: this.rowData.ParentId,
                    Name: this.rowData.Name,
                    IsAuthorization: this.rowData.IsAuthorization,
                    FileSize: list[0].FileSize,
                    filePath: list[0].FilePath,
                    FileFormat: list[0].FileFormat,
                    AuditDocumentTypeEnum: 1
                })
            } else {
                data = this.formatData(list)
                let ParentId = this.Id
                // if (this.rowData && this.rowData.Id) {
                //     if (this.rowData.AuditDocumentTypeEnum) {
                //         ParentId = this.rowData.ParentId
                //     } else {
                //         ParentId = this.rowData.Id
                //     }
                // }
                data.forEach(item => {
                    item.ParentId = ParentId
                })
            }
            try {
                let res = await addAuditDocument(JSON.stringify(data))
                if (res.IsSuccess) {
                    let id = res.Result ? res.Result[0] : null
                    this.getList(id)
                    // if (this.$refs.versionDetail) {
                    //     this.$refs.versionDetail.getHistoricalVersion()
                    // }
                }
            } catch (err) {
                console.log(err)
            }
        },
        // 格式化上传数据
        formatData(arr) {
            let list = [], strObj = {}
            arr.forEach(item => {
                if (item.catalogue) {
                    let catalogueStr = item.catalogue.split("/")
                    catalogueStr.pop()
                    let obj = {}, strKey = []
                    catalogueStr.forEach((str, index) => {
                        strKey.forEach((key, i) => {
                            if (i === 0) {
                                obj = strObj[key]
                            } else {
                                obj = obj[key]
                            }

                        })
                        if (index === 0) {
                            if (!strObj[str]) {
                                strObj[str] = {
                                    children: []
                                }
                            }
                        } else {
                            if (!obj[str]) {
                                obj[str] = {
                                    children: []
                                }
                            }
                        }
                        obj = obj[str] || strObj[str]
                        strKey.push(str)

                    })
                    obj.children.push({
                        ParentId: null,
                        Name: item.FileName,
                        IsAuthorization: false,
                        FileSize: item.FileSize,
                        filePath: item.FilePath,
                        FileFormat: item.FileFormat,
                        AuditDocumentTypeEnum: 1
                    })
                } else {
                    list.push({
                        ParentId: null,
                        Name: item.FileName,
                        IsAuthorization: false,
                        FileSize: item.FileSize,
                        filePath: item.FilePath,
                        FileFormat: item.FileFormat,
                        AuditDocumentTypeEnum: 1
                    })
                }
            })
            let ARRAY = this.objToArr(strObj)
            list = list.concat(ARRAY)
            return list
        },
        objToArr(obj, list = []) {
            Object.keys(obj).forEach(key => {
                if (key !== 'children') {
                    let item = list.find(d => d.Name === key)
                    if (!item) {
                        let data = {
                            ParentId: null,
                            Name: key,
                            IsAuthorization: false,
                            AuditDocumentTypeEnum: 0,
                            children: obj[key].children
                        }
                        list.push(data)
                    }
                    this.objToArr(obj[key], obj[key].children)
                }

            })
            return list;
        },
        // 格式化文件类型
        formatFileType(row) {
            if (!row.AuditDocumentTypeEnum) {
                return this.$t('trials:trials-workbench:auditDocument:fileType:folder')
            } else {
                return row.FileFormat
                // return `${row.FileFormat}${this.$t('trials:trials-workbench:auditDocument:fileType:file')}`
            }
        },
        // 格式化文件大小
        formatFileSize(row) {
            if (!row.FileSize && row.FileSize !== 0) return ''
            if (row.FileSize < 1000) {
                return row.FileSize + "B"
            }
            if (row.FileSize < 1000 * 1024) {
                return (row.FileSize / 1024).toFixed(2) + "KB"
            }
            if (row.FileSize < 1000 * 1000 * 1024) {
                return (row.FileSize / 1000 / 1024).toFixed(2) + "MB"
            }
            if (row.FileSize < 1000 * 1000 * 1000 * 1024) {
                return (row.FileSize / 1000 / 1000 / 1024).toFixed(2) + "GB"
            }
        },
        openFileNewVersion(faccept) {
            if (!this.isManage) return false
            this.faccept = [faccept]
            this.limitLength = 1
            this.config.title = this.$t(
                'trials:trials-workbench:auditDocument:form:title:uploadFile'
            )
            this.config.visible = true
            this.config.isVersion = true
            this.config.isFolder = false
        },
        openFile(isFolder = false) {
            if (!this.isManage) return false
            this.faccept = [
                '.jpg',
                '.jpeg',
                '.png',
                '.pdf',
                '.ppt',
                '.pptx',
                '.zip',
                '.doc',
                '.docx',
                '.xls',
                '.xlsx',
            ]
            this.limitLength = 0
            this.config.title = this.$t(
                'trials:trials-workbench:auditDocument:form:title:uploadFile'
            )
            this.config.visible = true
            this.config.isVersion = false
            this.config.isFolder = isFolder
        },
        close() {
            this.config.visible = false
            this.faccept = ['.pdf']
            this.limitLength = 0
        },
        // 预览文件
        perview(data) {
            if (['.ppt',
                '.pptx',
                '.doc',
                '.docx',
                '.xls',
                '.xlsx'].includes(`.${data.FileFormat.toLowerCase()}`)) {
                this.$onlyOffice({
                    path: data.FilePath,
                    type: data.FileFormat,
                    title: data.Name
                })
            }
            if (['.jpg',
                '.jpeg',
                '.png'].includes(`.${data.FileFormat.toLowerCase()}`)) {
                this.$refs['picture_perview'].$viewer.show()
            }
            if (['.pdf'].includes(`.${data.FileFormat.toLowerCase()}`)) {
                this.$preview({
                    path: data.Path || data.FilePath,
                    type: 'pdf',
                    title: data.Name,
                })
            }

        },
        // 版本记录（右键菜单）
        openContextmenu(data) {
            if (!this.isManage) return false
            let { e, row, type, zIndex } = data
            this.$refs.contextmenu.init(e, row, type, zIndex)
        },
        // 单行右键单击（右键菜单）
        handleRowContextmenu(row, column, e) {
            if (!this.isManage) return false
            e.preventDefault();
            if (!this.checkList.includes(row.Id)) this.handleRowClick(row, {}, e)
            if (this.checkList.length > 1) return this.$refs.contextmenu.init(e, row, 'files')
            if (!row.AuditDocumentTypeEnum) return this.$refs.contextmenu.init(e, row, 'folder')
            this.$refs.contextmenu.init(e, row, 'file')
        },
        // 单行左键双击（进入文件夹或者预览文件）
        handleRowDblclick(row, column, event) {
            if (this.$refs.contextmenu) {
                this.$refs.contextmenu.foo()
            }
            // 判断点击目标是否为展开按钮
            let isExpandButton = event.target.closest('.el-table__expand-icon');
            if (isExpandButton) return; // 阻止触发
            isExpandButton = event.target.closest('.IsAuthorization_swich');
            if (isExpandButton) return; // 阻止触发
            if (!row.AuditDocumentTypeEnum) {
                this.Id = row.Id
                this.resetOpt()
                this.getList()
                this.getBreadcrumbData()
            } else {
                this.perview(this.rowData)
            }
        },
        // 单行左键单击
        handleRowClick(row, column, e) {
            e.stopPropagation();
            this.rowData = row
            // let index = this.checkList.indexOf(row.Id)
            if (this.ctrlKey) {
                this.checkList.push(row.Id)
            } else {
                this.checkList = [row.Id]
            }
            if (this.$refs.contextmenu) {
                this.$refs.contextmenu.foo()
            }
            // if (this.ctrlKey) {
            //     if (!!~index) {
            //         this.checkList.splice(index, 1)
            //     } else {
            //         this.checkList.push(row.Id)
            //     }
            // } else {
            //     if (this.checkList.length > 1 || this.checkList.length <= 0) {
            //         this.checkList = [row.Id]
            //     } else {
            //         if (!!~index) {
            //             this.checkList.splice(index, 1)
            //         } else {
            //             this.checkList = [row.Id]
            //         }
            //     }

            // }


        },
        // 单行hover移入
        handleCellMouseEnter(row) {
            this.hoverId = row.Id
        },
        // 单行hover移出
        handleCellMouseLeave() { this.hoverId = null },
        // 右键菜单操作
        handleMenu(data) {
            if (!this.isManage) return false
            let { key, row } = data
            // console.log(key, row)
            this.type = key;
            if (key === 'rename') {
                // this.renameId = this.checkList[0]
                this.addRenameId(row)
            }
            if (key === 'version') {
                this.visible = true
            }
            if (key === 'open') {
                if (!this.rowData.AuditDocumentTypeEnum) {
                    this.Id = this.rowData.Id
                    this.resetOpt()
                    this.getList()
                    this.getBreadcrumbData()
                } else {
                    this.perview(row)
                }
            }
            if (key === 'del') {
                this.delData(this.checkList)
            }
            if (key === 'delVersion') {
                this.delData([row.Id])
            }
            if (key === 'delAllVersion') {
                if (this.$refs.versionDetail) {
                    this.$refs.versionDetail.delAll()
                }
            }
            if (key === 'setVersion') {
                this.setCurrentVersion(row.Id)
            }
            if (key === 'copy') {
                this.copy()
            }
            if (key === 'shear') {
                this.shear()
            }
            if (key === 'stickup') {
                this.stickup()
            }
            if (key === 'downLoad') {
                this.downLoad(this.checkList, row)
            }
        },
        setRowStyle({ row, rowIndex }) {
            if (this.checkList.includes(row.Id)) {
                return {
                    backgroundColor: '#cce8ff', // 错误行红色背景
                }
            }
        },
        // 复制
        copy() {
            if (!this.checkList || this.checkList.length <= 0) return this.$message.warning(this.$t("trials:trials-workbench:auditDocument:message:nothingCopy"))
            this.copyList = [...this.checkList]
            this.shearList = []
            this.$message.success(this.$t("trials:trials-workbench:auditDocument:message:copySuccess"))
        },
        // 剪切
        shear() {
            if (!this.checkList || this.checkList.length <= 0) return this.$message.warning(this.$t("trials:trials-workbench:auditDocument:message:nothingShear"))
            this.shearList = [...this.checkList]
            this.copyList = []
            this.$message.success(this.$t("trials:trials-workbench:auditDocument:message:shearSuccess"))
        },
        // 粘贴
        stickup() {
            if (this.checkList.length > 1) return this.$message.warning(this.$t("trials:trials-workbench:auditDocument:message:stickupCheckDataMore"))
            if (this.shearList && this.shearList.length > 0) return this.moveData(this.shearList)
            if (this.copyList && this.copyList.length > 0) return this.copyData(this.copyList)
        },

        // 键盘事件（按下）
        keydown(e) {
            if (!this.isManage) return false
            this.ctrlKey = e.ctrlKey
            if (e.key === 'Control') {
                e.preventDefault();
            }
            if (e.ctrlKey && e.key === 'c') {
                // e.preventDefault();
                if (this.checkList.length > 0 && !this.renameId) {
                    this.type = 'copy'
                    this.copy()
                }

            }
            if (e.ctrlKey && e.key === 'v') {
                // e.preventDefault();
                this.type = 'stickup'
                this.stickup()
            }
            if (e.ctrlKey && e.key === 'x') {
                // e.preventDefault();
                if (this.checkList.length > 0 && !this.renameId) {
                    this.type = 'shear'
                    this.shear()
                }

            }
        },
        // 键盘事件（松开）
        keyup(e) {
            if (!this.isManage) return false
            this.ctrlKey = e.ctrlKey
        },
        docClick() {
            this.checkList = []
        }
    },
    mounted() {
        document.addEventListener('keydown', this.keydown);
        document.addEventListener('keyup', this.keyup);
        // let table = document.getElementById("auditDocumentTable")
        document.addEventListener('click', this.docClick);
        this.getList()
        this.getBreadcrumbData()
    },
    destroyed() {
        document.removeEventListener('keydown', this.keydown);
        document.removeEventListener('keyup', this.keyup);
    }
}
</script>
<style lang="scss" scoped>
.base-search-form .el-form-item {
    margin-bottom: 22px;
}

.auditDocument {

    // position: relative;
    ::v-deep .catalogue_box.el-table__cell {
        .cell {
            display: flex;
            align-items: center;
        }
    }
}

.renameInp {
    ::v-deep .el-input__inner {
        line-height: 23px;
        height: 23px;
    }
}

.name_layout_box {
    display: inline-block;
    flex: 1 1 0%;
    min-width: 0;
}


.catalogue {
    width: 99%;
    display: flex;
    align-items: center;
    margin: 0 0 22px;



    span {
        font-size: 16px;
    }

    .last_catalogue {
        width: 36px;
        height: 36px;
        line-height: 36px;
        text-align: center;
        border: 1px solid #ddd;
        // cursor: pointer;
        padding: 0;
        border-radius: 4px 0 0 4px;

        // &:hover {
        //     background-color: #e4f8ff;
        //     border-color: #aedaff;
        // }
    }

    .catalogue_name_box {
        flex: 1 0 0%;
        box-sizing: border-box;
        border: 1px solid #ddd;
        border-left: none;
        padding: 0 10px;
        border-radius: 0 4px 4px 0;
        height: 36px;
        line-height: 36px;
    }

    .catalogue_name {
        cursor: pointer;
        font-size: 14px;

        &:hover {
            color: #3b8cff;
        }
    }
}

.name_layout {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: relative;

    .name_box {
        display: flex;
        align-items: center;
        width: calc(100% - 20px);

        .name {
            max-width: calc(100% - 60px);
            white-space: nowrap;
            /* 文本不换行 */
            overflow: hidden;
            /* 超出部分隐藏 */
            text-overflow: ellipsis;
        }
    }

    .version {
        position: absolute;
        right: 0;
        top: 2px;
        background: #ff980021;
        color: #ff9800;
        font-size: 12px;
        padding: 0 3px;
        border-radius: 2px;
        z-index: 1;

        i {
            margin-right: 3px;
        }
    }
}

.icon_edit {
    cursor: pointer;
    color: rgba(0, 0, 0, 0.3);
    margin-left: 2px;

    &:hover {
        color: rgba(0, 0, 0, 0.5);
    }
}

.icon_check {
    font-size: 22px;
    cursor: pointer;
    color: rgba(0, 0, 0, 0.3);

    &:hover {
        color: rgba(0, 0, 0, 0.5);
    }

    z-index: 9;
}

.isCheck {
    color: #3b8cff;
}

::v-deep .el-table--enable-row-hover .el-table__body tr:hover>td.el-table__cell {
    background-color: #e5f3ff
}

::v-deep .el-table {
    .caret-wrapper {
        height: 24px;
    }

    .sort-caret.ascending {
        top: 0;
    }

    .sort-caret.descending {
        bottom: 3px;
    }
}

.icon_image {
    max-height: 20px;
    max-width: 20px;
    padding: 0px;
    line-height: 20px;
    margin-right: 6px;
    // margin-top: 6px;
}

.icon {
    height: 20px;
    width: 20px;
    padding: 0px;
    line-height: 20px;
    margin-right: 6px;
    margin-top: 6px;
}

/*文件*/
.icon_file {
    width: 16px !important;
    height: 16px !important;
    margin-right: 6px;
    background-size: inherit;
    background-image: url(@/assets/0.file-16.png);
    background-position: 0 0;
    margin-top: -2px;
    background-repeat: no-repeat;
    font-style: normal;
    display: inline-block;
    pointer-events: none;
    font-size: 85%;
}

/*文件夹*/
.icon_folder {
    background-image: url(@/assets/folder_win11_small.png);
    margin-top: -6px;
    margin-left: 2px;
    margin-right: 6px;
    background-repeat: no-repeat;
}

/*docx*/
.icon_docx {
    background-position: -81px -560px !important;
    margin-top: 0;
    margin-left: 2px;
}

/*doc*/
.icon_doc {
    background-position: -81px -592px !important;
    margin-top: 0;
    margin-left: 2px;
}

/*xlsx*/
.icon_xlsx {
    background-position: -81px -48px !important;
    margin-top: 0;
    margin-left: 2px;
}

/*pdf*/
.icon_pdf {
    background-position: -81px -352px !important;
    margin-top: 0;
    margin-left: 2px;
}

/*pptx*/
.icon_pptx {
    background-position: -81px -288px !important;
    margin-top: 0;
    margin-left: 2px;
}

/*zip*/
.icon_zip {
    background-position: 0 0 !important;
    margin-top: -2px;
    margin-left: 2px;
}

/*ppt*/
.icon_ppt {
    background-position: -81px -304px !important;
    margin-top: 0;
    margin-left: 2px;
}

/*xls*/
.icon_xls {
    background-position: -81px -96px !important;
    margin-top: 0;
    margin-left: 2px;
}
</style>