<template>
    <div class="hc-page-layout-box hc-file-collection">
        <div class="hc-layout-left-box" :style="'width:' + leftWidth + 'px;'">
            <div class="hc-project-box">
                <div class="hc-project-icon-box">
                    <HcIcon name="stack"/>
                </div>
                <div class="ml-2 project-name-box">
                    <span class="text-xl text-cut project-alias">{{projectInfo['projectAlias']}}</span>
                    <div class="text-xs text-cut project-name">{{projectInfo['name']}}</div>
                </div>
            </div>
            <div class="hc-tree-box" v-loading="treeLoading" element-loading-text="加载中...">
                <el-scrollbar>
                    <HcTree :projectId="projectId" :contractId="contractId" @nodeTap="projectTreeClick"  @nodeLoading="treeNodeLoading" ref="treeRef" :autoExpandKeys="treeAutoExpandKeys"    @menuTap="ElTreeMenuClick"/>
                </el-scrollbar>
            </div>
            <!--左右拖动-->
            <div class="horizontal-drag-line" @mousedown="onmousedown"/>
        </div>
        <div class="hc-page-content-box">
            <HcCard>
                <template #header>
                    <HcTooltip keys="file_collection_btn_upload_scanned_files">
                        <el-button type="primary" hc-btn @click="uploadModalClick">
                            <HcIcon name="qr-scan"/>
                            <span>上传扫描文件</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="file_collection_btn_sorting">
                        <el-button type="primary" hc-btn @click="sortingClick">
                            <HcIcon name="archive"/>
                            <span>分盒整理</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="file_collection_btn_download">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0">
                            <HcIcon name="download"/>
                            <span>下载</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="file_collection_btn_certified">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" @click="certificationModalClick">
                            <HcIcon name="vip-diamond"/>
                            <span>认证</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="file_collection_btn_report">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0">
                            <HcIcon name="send-plane-2"/>
                            <span>上报</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="file_collection_btn_edit">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" @click="batchEditClick">
                            <HcIcon name="edit"/>
                            <span>编辑</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="file_collection_btn_repeal">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0">
                            <HcIcon name="delete-back-2"/>
                            <span>废除</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="file_collection_btn_del">

                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" @click="delModalClick">
                            <HcIcon name="delete-bin"/>
                            <span>删除</span>
                        </el-button>
                    </HcTooltip>
                </template>
                <template #extra>
                    <HcTooltip keys="file_collection_btn_moves">
                        <el-button hc-btn @click="movesClick">
                            <HcIcon type="primary" name="arrow-left-right"/>
                            <span>跨目录移动</span>
                        </el-button>
                    </HcTooltip>
                </template>
                <template #search>
                    <div class="w-40">
                        <el-select v-model="searchForm.isApprovalValue" placeholder="审批状态" clearable>
                            <el-option v-for="item in approvalStatus" :key="item.value" :label="item['label']" :value="item['value']"/>
                        </el-select>
                    </div>
                    <div class="w-40 ml-2">
                        <el-select v-model="searchForm.isCertificationValue" placeholder="认证状态" clearable>
                            <el-option v-for="item in certifiedStatus" :key="item.value" :label="item['label']" :value="item['value']"/>
                        </el-select>
                    </div>
                    <div class="w-64 ml-2">
                        <el-input v-model="searchForm.queryValue" placeholder="请输入名称关键词检索" clearable @keyup="keyUpEvent"/>
                    </div>
                    <div class="ml-2">
                        <el-button type="primary" @click="searchClick">
                            <HcIcon name="search-2"/>
                            <span>搜索</span>
                        </el-button>
                    </div>
                </template>
                <HcTable ref="tableRef" :column="tableColumn" :datas="tableData" :loading="tableLoading" isCheck @selection-change="tableSelection">
                    <template #table-column-header-num>
                        <HcTooltip keys="file_collection_btn_sort">
                            <span class="text-link text-lg" @click="tableSortClick">
                                <HcIcon name="arrow-up-down"/>
                            </span>
                        </HcTooltip>
                    </template>
                    <template #fileName="{row}">
                        <span class="text-link" @click="tableRowName(row)">{{row?.fileName}}</span>
                    </template>
                </HcTable>
                <template #action>
                    <HcPages :pages="searchForm" @change="pageChange"/>
                </template>
            </HcCard>
        </div>

        <!--预组卷整理-->
        <HcDialog :show="sortingModal" title="预组卷整理" widths="850px" isTable isRowFooter @close="sortingModalClose">
            <div class="hc-sorting-modal-collapse">
                <el-collapse v-model="sortingActiveKey">
                    <template v-for="(item,index) in sortingItemData" :key="index">
                        <el-collapse-item :name="`item-${index}`" disabled :id="`item-${index}`">
                            <template #title>
                                <div class="hc-collapse-item-header">
                                    <div class="item-index">盒{{index+1}}</div>
                                    <el-divider direction="vertical" />
                                    <div class="item-input">
                                        <el-input
                                            v-model="item.boxName"
                                            :class="item['isName'] ? 'is-error' : ''"
                                            placeholder="请输入案卷题名"
                                            @input="tableIsInput($event, item, 'isName')"
                                            @change="tableIsInput($event, item, 'isName')"
                                        />
                                    </div>
                                    <el-divider direction="vertical" />
                                    <div class="item-action">
                                        <el-button type="primary" @click="sortingSelectFile(item,index)">选择文件</el-button>
                                        <el-button type="danger" @click="sortingDelData(item,index)">删除</el-button>
                                    </div>
                                </div>
                            </template>
                            <HcTable :column="sortingTableColumn" :datas="item.list" :loading="sortingTableLoading" isCheck @selection-change="rows => sortingTableSelection(rows,item.list,index)" ref="sorTableRef"
                                @single-select="singleCheck"
                                >
                                <template #name="{row}">
                                    <span class="text-link">{{row?.fileName}}</span>
                                </template>
                            </HcTable>
                        </el-collapse-item>
                    </template>
                </el-collapse>
            </div>
            <template #leftRowFooter>
                <el-button type="primary" hc-btn @click="addSortingModalClick">
                    <HcIcon name="add"/>
                    <span>添加分盒</span>
                </el-button>
            </template>
            <template #rightRowFooter>
                <el-button hc-btn @click="sortingModalClose">
                    <HcIcon name="close"/>
                    <span>取消</span>
                </el-button>
                <el-button type="primary" hc-btn :loading="sortingModalLoading" @click="sortingModalSave">
                    <HcIcon name="check"/>
                    <span>确认</span>
                </el-button>
            </template>
        </HcDialog>

        <!--预组卷整理 无数据-->
        <HcDialog :show="sortingNoneModal" title="预组卷整理" widths="850px" isTable isRowFooter @close="sortingNoneModalClose">
            <div class="flex-center">
                <i class="el-icon" data-v-029747aa="" style="font-size: 200px;color:#81b337;cursor: pointer;" @click="toSortingModal">
                    <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" data-v-029747aa="">
                        <path fill="currentColor" d="M512 64a448 448 0 1 1 0 896 448 448 0 0 1 0-896zm-38.4 409.6H326.4a38.4 38.4 0 1 0 0 76.8h147.2v147.2a38.4 38.4 0 0 0 76.8 0V550.4h147.2a38.4 38.4 0 0 0 0-76.8H550.4V326.4a38.4 38.4 0 1 0-76.8 0v147.2z"></path>
                    </svg>
                </i>
                <span>添加分盒</span>
            </div>
        </HcDialog>

        <!--跨目录移动-->
        <HcDialog :show="movesModal" title="跨目录移动" widths="990px" isTable @close="movesModalClose" @save="movesModalSave" :loading="movesModalLoading">
            <div class="hc-moves-transfer-box">
                <div class="hc-moves-transfer-panel">
                    <div class="panel-header">
                        <div class="panel-header-label">
                            <el-checkbox class="size-xl space" v-model="movesCheckAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">选择需要迁移的文件</el-checkbox>
                        </div>
                        <div class="panel-header-extra">{{checkedMoves.length}}/{{fileDatasList.length}}</div>
                    </div>
                    <div class="panel-body">
                        <el-scrollbar>
                            <el-checkbox-group v-model="checkedMoves" @change="handleCheckedMovesChange">
                                <div class="hc-file-checkbox" v-for="item in fileDatasList" :key="item.id">
                                    <el-checkbox class="size-xl space" :label="item">{{item.fileName}}</el-checkbox>
                                </div>
                            </el-checkbox-group>
                        </el-scrollbar>
                    </div>
                </div>
                <div class="hc-moves-transfer-buttons">
                    <HcIcon type="primary" name="arrow-right-double" style="font-size: 22px;"/>
                </div>
                <div class="hc-moves-transfer-panel">
                    <div class="panel-header">选择移动目录</div>
                    <div class="panel-body" v-loading="treePanelLoading">
                        <el-scrollbar>
                            <HcTree idPrefix="hc-tree-moves-" :projectId="projectId" :contractId="contractId" isRadio @radioChange="radioChange" :showRadioFun="showRadioFun" @nodeLoading="panelTreeLoading" :isShowMenu="false"/>
                        </el-scrollbar>
                    </div>
                </div>
            </div>
        </HcDialog>

        <!--调整排序-->
        <HcDialog :show="sortModal" title="调整排序" widths="980px" isTable isRowFooter @close="sortModalClose">
            <el-alert title="可拖动排序，也可在后面点击图标，切换排序" type="error" :closable="false"/>
            <div class="hc-table-h">
                <HcTable ui="hc-table-row-drop" :column="sortTableColumn" :datas="sortTableData" :loading="sortTableLoading" isRowDrop @row-drop="sortTableRowDrop">
                    <template #key2="{row}">
                        <span class="text-link">{{row?.key2}}</span>
                    </template>
                    <template #action="{index}">
                    <span class="text-link text-xl" @click="upSortClick(index)">
                        <HcIcon name="arrow-up" fill/>
                    </span>
                        <span class="text-link text-xl ml-2" @click="downSortClick(index)">
                        <HcIcon name="arrow-down" fill/>
                    </span>
                    </template>
                </HcTable>
            </div>
            <template #leftRowFooter>
                <el-button hc-btn @click="sortModalClose">
                    <HcIcon name="close"/>
                    <span>取消</span>
                </el-button>
                <el-button type="primary" hc-btn :loading="sortModalLoading" @click="sortModalSave">
                    <HcIcon name="check"/>
                    <span>确认</span>
                </el-button>
            </template>
            <template #rightRowFooter>
                <HcPages :pages="sortSearchForm" :sizes="[10, 20, 50, 100, 200, 300, 400, 500, 600]" @change="sortPageChange"/>
            </template>
        </HcDialog>

        <!--新增编辑文件-->
        <el-dialog v-model="showUploadModal" title="上传工程文件" width="80vw" class="hc-modal-border hc-modal-table" @close="uploadModalClose" :close-on-click-modal="false">
            <HcTable ui="hc-form-table" isSort :column="tableUploadColumn" :datas="tableUploadData" :loading="uploadSaveLoading" @row-sort="tableUploadRowSort">
                <template #fileNumber="{row}">
                    <!-- <el-input v-model="row.fileNumber" :class="row['isFileNumber'] ? 'is-error' : ''" @input="tableIsInput($event, row, 'isFileNumber')"/> -->
                    <el-input v-model="row.fileNumber"/>
                </template>
                <template #fileName="{row}">
                    <el-input v-model="row.fileName" :class="row['isFileName'] ? 'is-error' : ''" @input="tableIsInput($event, row, 'isFileName')"/>
                </template>
                <template #fileTime="{row}">
                    <el-date-picker v-model="row.fileTime" type="date" format="YYYYMMDD" value-format="YYYYMMDD" :clearable="false"/>
                    <!-- <el-input v-model="row.fileTime" :class="row['isFileTime'] ? 'is-error' : ''" @input="tableIsInput($event, row, 'isFileTime')"/> -->
                </template>
                <template #sheetType="{row}" v-if="isBuiltDrawing === 2">
                    <el-select v-model="row.sheetType">
                        <el-option v-for="item in sheetType" :key="item['dictKey']" :label="item['dictValue']" :value="item['dictKey']"/>
                    </el-select>
                </template>
                <template #sheetSource="{row}" v-if="isBuiltDrawing === 2">
                    <el-select v-model="row.sheetSource">
                        <el-option v-for="item in sheetSourceType" :key="item['dictKey']" :label="item['dictValue']" :value="item['dictKey']"/>
                    </el-select>
                </template>
                <template #drawingNo="{row}" v-if="isBuiltDrawing === 2">
                    <el-input v-model="row.drawingNo"/>
                </template>
                <template #citeChangeNumber="{row}" v-if="isBuiltDrawing === 2">
                    <el-input v-model="row.citeChangeNumber"/>
                </template>
                <template #isApproval="{row}">
                    <el-select v-model="row.isApproval">
                        <el-option v-for="item in whetherData" :key="item.value" :label="item.label" :value="item.value"/>
                    </el-select>
                </template>
                <template #isNeedCertification="{row}">
                    <el-select v-model="row.isNeedCertification">
                        <el-option v-for="item in whetherData" :key="item.value" :label="item.label" :value="item.value"/>
                    </el-select>
                </template>
                <template #dutyUser="{row}">
                    <el-input v-model="row.dutyUser"/>
                </template>
                <template #isElement="{row}">
                    <el-select v-model="row.isElement">
                        <el-option label="是" :value="1"/>
                        <el-option label="否" :value="0"/>
                    </el-select>
                </template>
                <template #action="{row,index}">
                    <HcFileUpload1 v-if="tableUploadType== 'edit'" @change="newUploadsChange($event, row)" style="display:inline-block"
                                   @progress="newUploadsProgress($event, row)">
                            <el-button :loading="row['newBtnLoading']" plain size="small" type="primary">替换</el-button>
                    </HcFileUpload1>
                    <el-button type="danger" plain size="small" :loading="row['delBtnLoading']" @click="delUploadData(row,index)">删除</el-button>
                </template>
            </HcTable>
            <template #footer>
                <div class="lr-dialog-footer">
                    <div class="left flex items-center" >
                        <el-button type="primary" hc-btn @click="uploadFileClick" v-if="tableUploadType== 'add'">
                            <HcIcon name="add-circle"/>
                            <span>新增上传</span>
                        </el-button>
                    </div>
                    <div class="right">
                        <el-button size="large" @click="batchUploadCancel" :disabled="uploadsLoading">
                            <HcIcon name="close"/>
                            <span>取消</span>
                        </el-button>
                        <el-button type="primary" hc-btn :disabled="uploadsLoading" :loading="uploadSaveLoading" @click="batchUploadSave">
                            <HcIcon name="save"/>
                            <span>提交保存</span>
                        </el-button>
                    </div>
                </div>
            </template>
        </el-dialog>

        <!--批量认证-->
        <el-dialog v-model="showCertificationModal" title="批量认证" width="80vw" class="hc-modal-border hc-modal-table">
            <div class="hc-card-body-flex">
                <div class="flex-table">
                    <HcTable ui="hc-form-table" :column="CertColumns" :datas="CertData" @row-click="CertRowClick">
                        <template #action="{row,index}">
                            <el-button type="primary" plain size="small" @click.stop="CertRowClick2(row)">预览</el-button>
                        </template>
                    </HcTable>
                </div>
                <div class="flex-iframe" v-if="CertPdf">
                    <iframe allow="display-capture" width='100%' height='100%' frameborder='1' :src="CertPdf"></iframe>
                </div>
                <div class="flex-iframe hc-no-table-form" v-else>
                    <div class="table-form-no">
                        <img :src="notableform" alt=""/>
                        <div class="desc">暂无 PDF 数据</div>
                    </div>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button size="large" @click="showCertificationModal = false">
                        <HcIcon name="close"/>
                        <span>取消</span>
                    </el-button>
                    <el-button type="primary" hc-btn :loading="CertLoading" @click="CertClick">
                        <HcIcon name="save"/>
                        <span>确认认证</span>
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <HcUploadFile ref="HcUploadFileRef" :options="UploadFileOptions" @progress="HcUploadFileProgress" @success="HcUploadFileSuccess" @change="HcUploadFileChange"/>
    </div>
</template>

<script setup>
import {useAppStore} from "~src/store";
import {getStoreValue, setStoreValue} from '~src/utils/storage'
import {ref, watch, onMounted, nextTick } from "vue";
import HcTree from "~src/components/tree/hc-tree.vue"
import HcFileUpload1 from "./components/HcFileUpload1.vue"
import notableform from '~src/assets/view/notableform.svg';
import {delMessage, rowsToId, rowsToIdNumArr} from "~uti/tools";
import archiveFileApi from "~api/archiveFile/archiveFile";
import {getArrValue, deepClone, getObjVal, arrToId} from "js-fast-way"
import {getTokenHeader} from "~src/api/request/header";
import tasksApi from '~api/tasks/data';
import ossApi from "~api/oss";

//变量
const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId);
const contractId = ref(useAppState.getContractId);
const projectInfo = ref(useAppState.getProjectInfo);
const contractInfo =  ref(useAppState.getContractInfo);

const isCollapse = ref(useAppState.getCollapse)
const HcUploadFileRef = ref(null)

//上传进度
const uploadsLoading = ref(false)

//监听
watch(() => [
    useAppState.getCollapse
], ([Collapse]) => {
    isCollapse.value = Collapse
})

//渲染完成
onMounted(() => {
    treeLoading.value = true
    setTableColumns()
})

//上传配置
const UploadFileOptions = {
    headers: getTokenHeader()
}

const {contractType} = contractInfo.value;
const dutyUser=ref('')
//设置责任者
const setdutyUser=async()=>{
    const { error, code, data,msg } = await archiveFileApi.getDutyUser({
        contractId: treecontractId.value,
        projectId:projectId.value
    })
    if (!error && code === 200) {
            if(data?.contractType===1){
            dutyUser.value=data?.constructionUnitName||''
            }else if(data?.contractType===2){
                    dutyUser.value=data?.supervisionUnitName||''
            }else if(data?.contractType===3){
                    dutyUser.value=data?.contractorUnitName||''
            }
    }

}
//打开文件选择框
const uploadFileClick = () => {
    HcUploadFileRef?.value.selectFile()
}

// 文件上传进度
const HcUploadFileProgress = ({file, status}) => {
    uploadsLoading.value = true
}
// 文件上传成功的回调
const HcUploadFileSuccess = (res) => {
    console.log('文件上传成功', res)
    uploadsLoading.value = false
    uploadsChange(res)
}

// 文件全部上传成功
const HcUploadFileChange = () => {
    console.log('文件全部上传成功')
    uploadsLoading.value = false
    HcUploadFileRef?.value.setModalShow(false)
}


//树加载
const treeLoading = ref(false)
const treeNodeLoading = () => {
    treeLoading.value = false
}


const treePanelLoading = ref(false)
const panelTreeLoading = () => {
    treePanelLoading.value = false
}

//审批状态
const approvalStatus = ref([
    {label: '未上报', value: '0'},
    {label: '待审批', value: '1'},
    {label: '已审批', value: '2'}
])

//认证状态
const certifiedStatus = ref([
    {label: '已认证', value: '1'},
    {label: '未认证', value: '0'}
])

//搜索表单
const searchForm = ref({
    nodeIds:'',
    approval: null, certified: null, queryValue: null,
    current: 1, size: 20, total: 0
})

//树相关的变量
const primaryKeyId = ref('')
const isBuiltDrawing = ref(0)
const isStorageNode = ref(0)
const nodeIds = ref('')
const treecontractId=ref('')
//自动展开缓存
const treeAutoExpandKeys = ref(getStoreValue('wbsTreeExpandKeys') || [])
const projectTreeClick = ({node, data, keys, key}) => {
    setStoreValue('wbsTreeExpandKeys', keys)
    treeAutoExpandKeys.value = keys || []
    nodeIds.value = data.id || '';
    isStorageNode.value = data['isStorageNode'] || 0;
    treecontractId.value=data?.contractId||''

    //设置搜索数据
    searchForm.value.current = 1;
    searchForm.value.nodeIds = data.id || '';

    sortSearchForm.value.nodeIds = data.id || '';
    isBuiltDrawing.value=data.storageType
    getTableData()
}
//树菜单被点击
const ElTreeMenuClick = async ({key, node, data, keys}) => {
    setStoreValue('wbsTreeExpandKeys', keys)
    treeAutoExpandKeys.value = keys || []

}
//回车搜索
const keyUpEvent = (e) => {
    if (e.key === "Enter") {
        searchForm.value.current = 1;
        getTableData()
    }
}

//搜索
const searchClick = () => {
    searchForm.value.current = 1;
    getTableData()
}

//分页被点击
const pageChange = ({current, size}) => {
    searchForm.value.current = current
    searchForm.value.size = size
    getTableData()
}

//表格数据
const tableRef = ref(null)
const tableColumn = ref([])
//设置表头
const setTableColumns = () => {
    if (isBuiltDrawing.value === 1) {
        tableColumn.value = [
            {key:'fileNumber', name: '文件编号', width: 160},
            {key:'fileName', name: '文件名称'},
            {key:'filePage', name: '文件页数', width: 120},
            {key:'sheetType', name: '图幅'},
            {key:'sheetSourceValue', name: '图表来源'},
            {key:'drawingNo', name: '图号'},
            {key:'citeChangeNumber', name: '引用变更令编号'},
            {key:'isCertificationValue', name: '认证状态', width: 160},
            {key:'isApprovalValue', name: '状态', width: 160},
            {key:'fileTime', name: '文件时间', width: 160},
            {key:'dutyUser', name: '责任者', width: 160}
        ]
        sheetTypeStatus()
        sheetSourceStatus()
    } else {
        tableColumn.value = [
            {key:'fileNumber', name: '文件编号', width: 160},
            {key:'fileName', name: '文件名称'},
            {key:'filePage', name: '文件页数', width: 100},
            {key:'isCertificationValue', name: '认证状态', width: 120},
            {key:'isApprovalValue', name: '状态', width: 120},
            {key:'fileTime', name: '文件时间', width: 180},
            {key:'dutyUser', name: '责任者', width: 180}
        ]
    }
}
const tableData = ref([])

//获取数据
const tableLoading = ref(false)
const getTableData = async () => {
    tableLoading.value = true
    const { error, code, data } = await archiveFileApi.getarchiveFilePage({
        ...searchForm.value,
        projectId: projectId.value,
        contractId: contractId.value
    })
    tableLoading.value = false
    if (!error && code === 200) {
        tableData.value = getArrValue(data['records'])
        searchForm.value.total = data['total'] || 0
    } else {
        tableData.value = []
        searchForm.value.total = 0
    }
}

//多选
const tableCheckedKeys = ref([]);
const tableSelection = (rows) => {
    tableCheckedKeys.value = rows
}

//分盒整理
const sortingModal = ref(false)
const sortingClick = async() => {
    if (nodeIds.value && isStorageNode.value === 1) {
        const { error, code, data } = await archiveFileApi.getBoxNameAndBoxNumber({
            nodeId:nodeIds.value
        })
        if (!error && code === 200) {
            if(data.length > 0){
                sortingActiveKey.value = [];
                sortingModal.value = true
                sortingItemData.value = getArrValue(data)
                sortingOldData.value = deepClone(sortingItemData.value)
            }else{
                console.log(1111111);
                sortingNoneModal.value = true
            }
        }

    } else {
        window?.$message?.warning('请先选择一个子节点')
    }
}

const sortingNoneModal = ref(false)//无数据显示的弹窗
const toSortingModal = ()=>{
    sortingNoneModal.value = false;
    sortingActiveKey.value = [];
    sortingItemData.value=[]
    sortingModal.value = true
}
const sortingNoneModalClose=()=>{
    sortingNoneModal.value=false
}

const sortingItemData = ref([])
const sortingOldData = ref([])//旧数据，用来对比是否修改名字

//获取数据
const sortingItemLoading = ref(false)
const getSortingItemData = () => {

}

//校验
const tableIsInput = (val, row, key) => {
    //console.log(!val);
    //检测是否改过案卷名字
    if(key == 'isName'){
        row.isChange = true;
    }

    row[key] = !val;
}

//选择文件
// const sortingActiveKey = ref('')
// const sortingSelectFile = (row, index) => {
//     //取当前展开组的key
//     const key = sortingActiveKey.value;
//     const keys = key ? key.split('-') : [];
//     const active = keys.length > 0 ? keys[1]: -1;
//     if (Number(active) === index) {
//         sortingActiveKey.value = null;
//     } else {
//         sortingActiveKey.value = `item-${index}`;
//     }
// }

const sortingActiveKey = ref([])
const tableIndex=ref('')
const sortingSelectFile = (row, index) => {
    tableIndex.value=index
    const key = `item-${index}`;
    const indexNum = sortingActiveKey.value.indexOf(key);
    if(indexNum > -1){
        sortingActiveKey.value.splice(indexNum,1);
    }else{
        sortingActiveKey.value.push(key);
        if(!(row.list && row.list.length > 0)){
            getSortingTableData(row, index)
        }
    }
}

//表格
const sortingTableColumn = [
    {key:'name', name: '文件名称'},
];
const sortingTableData = ref([])

//获取数据
const sortingTableLoading = ref(false)
const getSortingTableData = async(row, index) => {
    sortingTableLoading.value = true
    tableindex.value=index
    const { error, code, data } = await archiveFileApi.pageByBoxName({
        size: 99999,
        current: 1,
        projectId: projectId.value,
        contractId: contractId.value,
        nodeIds:nodeIds.value,
        boxName:row.boxName?row.boxName:''
    })
    sortingTableLoading.value = false
    if (!error && code === 200) {
        row.list = getArrValue(data['records'])

        setTableCheck(row, index)



    } else {
        row.list = []
    }
}

//表格ref
const sorTableRef = ref([]);
const tableindex=ref('')
//回显勾选
const setTableCheck = async(row, index) => {
    //console.log(row)
    if(row.ids){
        const keys = row.ids.split(',');
        row.list.forEach(async (item)=>{
            if(keys.indexOf(item.id) > -1){
                item.checked = true;
                await nextTick();
                sorTableRef.value[index].toggleRowSelection(item,true);


            }
        })
    }
}

//多选
const sortingTableKeys = ref([]);
const checkList=ref([])
const arrfliter=ref([])
const singleCheck=async({row})=>{
  let isCheck=false
    let checkrow=JSON.parse(JSON.stringify(row))
    if(checkrow.checked===false||checkrow.checked===undefined){

        if( checkList.value.length>0){
            let arr=checkList.value.filter(e => e.id === checkrow.id)
            if(arr.length>0){
                window.$message.warning('多个盒子不能选择同一份文件')
                await nextTick();
                sorTableRef.value[tableindex.value].toggleRowSelection(row,false);
                isCheck=true



            }else{
              isCheck=false
                row.tableindex=tableindex.value
                checkList.value.push(row)
            }

        }else{
            row.tableindex=tableindex.value
            checkList.value.push(row)
        }


    }else{
        let arr=checkList.value.filter(e => e.id === checkrow.id)
        if(isCheck===false&&arr[0]?.checked===true||isCheck){
            arrfliter.value=checkList.value.filter(e => e.id !== checkrow.id)

        }else{
            arrfliter.value=checkList.value
        }
        let newarr=[]
        arrfliter.value.forEach((item)=>{
            newarr.push(JSON.parse(JSON.stringify(item)))

        })
        checkList.value=newarr
    }



}
const sortingTableSelection = (rows,list,index) => {
    tableindex.value=index
    if(list){
        list.forEach(element => {
                element.checked = false;
        });
    }
    rows.forEach((element)=>{
            element.checked = true;
    })
}

//删除
const sortingDelData = (row,index) => {
    sortingItemData.value.splice(index,1);
    console.log(checkList.value,'checkList.value');
    // checkList.value=[]
    //过滤掉当前选择的文件
    checkList.value= checkList.value.filter(e => e.tableindex !== index)
    if(row.boxNumber){
        delMessage(async () => {
            const { error, code } = await archiveFileApi.removeAllocation({
                boxName: row.boxName,
                boxNumber:row.boxNumber
            })
            if (!error && code === 200) {
                window.$message?.success('删除成功！')
                // searchClick()
                sortingClick()
            }
        })
    }
}

//添加分盒
const addSortingModalClick = () => {
    console.log('添加分盒');
    sortingItemData.value.push({
        boxName: ''
    })
}

//确认保存
const sortingModalLoading = ref(false)
const sortingModalSave = async() => {
    sortingModalLoading.value = true
    //检测案卷名是否重复
    let nameRes = await checkNames();
    //console.log(nameRes)
    //return;
    for (let i = 0; i < nameRes.length; i++) {
        if(typeof nameRes[i].data == 'string'){
            window.$message?.error(nameRes[i].data+',案卷名重复')
            sortingModalLoading.value = false
            return;
        }
    }

    //组装数据
    let rows = [];
    sortingItemData.value.forEach((item,index)=>{
        let obj = {
            ids:'',
            boxName:item.boxName,
            boxNumber:index+1,
        };
        let list = [];
        if(item.list){
            item.list.forEach((item2)=>{
                if(item2.checked){
                    list.push(item2.id)
                }
            })
            obj.ids = list.join(',');
        }else{
            obj.ids = item.ids;
        }

        rows.push(obj)
    })
    console.log(rows,'rows');
    if(rows[0]?.ids){
        const { error, code, data } = await archiveFileApi.allocation({
            list: rows
        })
        if (!error && code === 200) {
            window.$message?.success('保存成功')
            sortingModal.value = false
        } else {
            window.$message?.error('保存失败')
        }
    }else{
        window.$message?.warning('空数据不能提交')

    }
    sortingModalLoading.value = false
}

const checkNames =() =>{
    const arr = [];
    sortingItemData.value.forEach((item)=>{
        if(item.boxNumber){
            if(item.isChange){
                //是否修改过
                //对比旧的数据，是否相同
                for (let i = 0; i < sortingOldData.value.length; i++) {
                    if(sortingOldData.value[i].boxNumber == item.boxNumber){
                        if(sortingOldData.value[i].boxName != item.boxName){
                            arr.push(
                                archiveFileApi.getIsBoxName({
                                    boxName:item.boxName
                                })
                            )
                        }
                        return;
                    }
                }
            }
        }else{
            arr.push(
                archiveFileApi.getIsBoxName({
                    boxName:item.boxName
                })
            )
        }
    })
    return Promise.all(arr);
}

//关闭
const sortingModalClose = () => {
    sortingModal.value = false
}

//删除
const delModalClick = async () => {
    const rows = tableCheckedKeys.value
    if(rows.length <= 0){
        window.$message?.error('请选择需要删除的数据')
    } else {
        delMessage(async () => {
            const keys = arrToId(rows);
            const { error, code } = await archiveFileApi.removeFile({
                ids: keys
            })
            if (!error && code === 200) {
                window.$message?.success('删除成功！')
                searchClick()
            }
        })
    }
}


//跨目录移动
const movesModal = ref(false)
const movesClick = async() => {
    movesModal.value = true
    checkedMoves.value=[]
    movesCheckAll.value=false
    treePanelLoading.value = true
    const { error, code, data } = await archiveFileApi.getarchiveFilePage({
        ...searchForm.value,
        size:9999,
        projectId: projectId.value,
        contractId: contractId.value
    })
    if (!error && code === 200) {
        fileDatasList.value = getArrValue(data['records'])
    } else {
        fileDatasList.value = []
    }
}

//选择需要迁移的文件
const movesCheckAll = ref(false)
const isIndeterminate = ref(true)
const checkedMoves = ref([])

//左侧待迁移文件
const fileDatasList = ref([])

//全选
const handleCheckAllChange = (val) => {
    const checked = fileDatasList.value
    checkedMoves.value = val ? checked : []
    isIndeterminate.value = false
}

//勾选
const handleCheckedMovesChange = (value) => {
    const keys = fileDatasList.value
    const checkedCount = value.length
    movesCheckAll.value = checkedCount === keys.length
    isIndeterminate.value = checkedCount > 0 && checkedCount < keys.length
}

//右侧radio
let radioNodeId = ''
const radioChange = (id)=>{
    //console.log(id)
    radioNodeId = id;
}

//只显示储存节点的单选
const showRadioFun = (data)=>{
    if(data.isStorageNode == 1){
        return true;
    }else{
        return false;
    }
}

//保存
const movesModalLoading = ref(false)
const movesModalSave = async() => {
    const keys = rowsToIdNumArr(checkedMoves.value);
    let ids =keys.join(',')
    if(checkedMoves.value.length < 1){
        window.$message?.warning('请勾选需要迁移的文件')
        return;
    }
    if(radioNodeId == ''){
        window.$message?.warning('请选择要移动到的节点')
        return;
    }
    movesModalLoading.value = true;
    const { error, code, data } = await archiveFileApi.migrateFile({
        ids:ids,
        nodeId:radioNodeId
    })
    movesModalLoading.value = false
    if (!error && code === 200) {
        window.$message?.success('保存成功')
        movesModal.value = false
        getTableData()
    } else {
        window.$message?.error('保存失败')
    }

}

//关闭
const movesModalClose = () => {
    movesModal.value = false
}


//表格排序
const sortModal = ref(false)
//显示
const tableSortClick = () => {
    sortModal.value = true
    getSortTableData()
}

//搜索表单
const sortSearchForm = ref({
    nodeIds:'',
    current: 1, size: 20, total: 0
})

//分页被点击
const sortPageChange = ({current, size}) => {
    sortSearchForm.value.current = current
    sortSearchForm.value.size = size
    getSortTableData()
}

//表格数据
const sortTableColumn = ref([
    {key:'fileNumber', name: '文件编号', width: 160},
    {key:'fileName', name: '文件名称'},
    {key:'action', name: '排序', width: 90},
])
const sortTableData = ref([])

const sortTableLoading = ref(false)
const getSortTableData = async () => {
    sortTableLoading.value = true
    const { error, code, data } = await archiveFileApi.getarchiveFilePage({
        ...sortSearchForm.value,
        projectId: projectId.value,
        contractId: contractId.value
    })
    sortTableLoading.value = false
    if (!error && code === 200) {
        sortTableData.value = getArrValue(data['records'])
        sortSearchForm.value.total = data['total'] || 0
    } else {
        sortTableData.value = []
        sortSearchForm.value.total = 0
    }
}

//拖动完成
const sortTableRowDrop = (rows) => {
    sortTableData.value = rows
}

//向下
const downSortClick = (index) => {
    const indexs = index + 1
    const data = sortTableData.value
    if(indexs !== data.length) {
        const tmp = data.splice(indexs,1);
        sortTableData.value.splice(index,0,tmp[0]);
    } else {
        window?.$message?.warning('已经处于置底，无法下移')
    }
}

//向上
const upSortClick = (index) => {
    const data = sortTableData.value || []
    if(index !== 0) {
        const tmp = data.splice(index - 1,1);
        sortTableData.value.splice(index,0,tmp[0]);
    } else {
        window?.$message?.warning('已经处于置顶，无法上移')
    }
}

//保存
const sortModalLoading = ref(false)
const sortModalSave = async() => {
    await batchEditSaveApi(sortTableData.value)

    sortModal.value = false
}

//关闭
const sortModalClose = () => {
    sortModal.value = false
}


//获取认证状态
const certificationType = ref([])
const certificationStatus = async () => {
    const { error, code, data } = await tasksApi.queryTaskTypeStatus({
        typeOrStatus: 'certification_status'
    })
    //处理数据
    if (!error && code === 200) {
        certificationType.value = getArrValue(data)
    } else {
        certificationType.value = []
    }
}

//获取图幅类型
const sheetType = ref([])
const sheetTypeStatus = async () => {
    console.log(1111111);
    const { error, code, data } = await tasksApi.queryTaskTypeStatus({
        typeOrStatus: 'sheet_type'
    })
    //处理数据
    if (!error && code === 200) {
        sheetType.value = getArrValue(data)
    } else {
        sheetType.value = []
    }
}

//获取图表来源
const sheetSourceType = ref([])
const sheetSourceStatus = async () => {
    const { error, code, data } = await tasksApi.queryTaskTypeStatus({
        typeOrStatus: 'sheet_source'
    })
    //处理数据
    if (!error && code === 200) {
        sheetSourceType.value = getArrValue(data)
    } else {
        sheetSourceType.value = []
    }
}

//新增文件
const tableUploadType = ref('add')
const showUploadModal = ref(false)
const uploadModalClick = () => {
    if (nodeIds.value && isStorageNode.value === 1) {
        tableUploadType.value = 'add'
        setTableUploadColumn()
        uploadSaveLoading.value = false
        tableUploadData.value = []
        showUploadModal.value = true
        setdutyUser()
    } else {
        window?.$message?.warning('请先选择一个子节点')
    }
}
const uploadModalClose=()=>{
    batchUploadCancel()
    //HcUploadFileRef?.value.cancel()
    HcUploadFileRef?.value.setModalShow(false)
}
//设置文件表头
const tableUploadColumn = ref([
    {key:'fileNumber', name: '文件编号'},
    {key:'fileName', name: '文件名称'},
    {key:'fileTime', name: '文件时间'},
    {key:'isApproval', name: '是否需要审批'},
    {key:'isNeedCertification', name: '是否需要认证'},
    {key:'dutyUser', name: '责任者'},
    {key:'isElement', name: '是否四要素'},
    {key:'action', name: '操作', width: 180}
])
const setTableUploadColumn = () => {
    if (isBuiltDrawing.value === 2) {
        tableUploadColumn.value = [
            {key:'fileNumber', name: '文件编号'},
            {key:'fileName', name: '文件名称'},
            {key:'fileTime', name: '文件时间'},
            {key:'sheetType', name: '图幅'},
            {key:'sheetSource', name: '图表来源'},
            {key:'drawingNo', name: '图号'},
            {key:'citeChangeNumber', name: '引用变更令编号'},
            {key:'isApproval', name: '是否需要审批'},
            {key:'isNeedCertification', name: '是否需要认证'},
            {key:'dutyUser', name: '责任者'},
            {key:'isElement', name: '是否四要素'},
            {key:'action', name: '操作', width: 180}
        ]
        sheetTypeStatus()
        sheetSourceStatus()
    } else {
        tableUploadColumn.value = [
            {key:'fileNumber', name: '文件编号'},
            {key:'fileName', name: '文件名称'},
            {key:'fileTime', name: '文件时间'},
            {key:'isApproval', name: '是否需要审批'},
            {key:'isNeedCertification', name: '是否需要认证'},
            {key:'dutyUser', name: '责任者'},
            {key:'isElement', name: '是否四要素'},
            {key:'action', name: '操作', width: 180}
        ]
    }
}
const tableUploadData = ref([])

//上传的文件结果
const uploadsChange = (item) => {
    if (getObjVal(item)) {
        let newArr = tableUploadData.value
        const sheet = sheetType.value, source = sheetSourceType.value
        let name = item['originalName'] || ''
        let fileName = name.substring(0, name.lastIndexOf("."))
        newArr.push({
            projectId: projectId.value,
            contractId: contractId.value,
            nodeId: nodeIds.value,
            fileNumber: '',
            fileName: fileName,
            ossFileName: item?.name || '',
            fileTime: null,
            fileUrl: item?.link || '',
            sheetType: sheet.length > 0 ? sheet[0]['dictKey'] || '': '',
            sheetSource: source.length > 0 ? source[0]['dictKey'] || '': '',
            drawingNo: '',
            citeChangeNumber: '',
            isApproval: 1,
            isNeedCertification: 1,
            dutyUser: dutyUser.value,
            pdfFileUrl: item?.pdfUrl || '',
            filePage: item?.page || '',
            isElement: 0,
            isUpdateUrl:0,
            fileSize:item?.fileSize
        })
        tableUploadData.value = newArr
    } else {
        console.log(item)
    }
}

//表单下拉数据
const whetherData = ref([
    {label: "不需要", value: 0},
    {label: "需要", value: 1}
])

//表格数据排序
const tableUploadRowSort = (arr) => {
    tableUploadData.value = arr
}

//删除
const delUploadData = async (row,index) => {
    if (row['ossFileName']) {
        row['delBtnLoading'] = true
        await ossApi.removeFile({fileName: row['ossFileName']})
        row['delBtnLoading'] = false
        tableUploadData.value.splice(index,1);
    } else {
        tableUploadData.value.splice(index,1);
    }
}

//批量上传保存
const uploadSaveLoading = ref(false)
const batchUploadSave = async () => {
    const rows = tableUploadData.value
    if (rows.length > 0) {
        //验证表单数据
        uploadSaveLoading.value = true
        let isTableRows = false;
        for (let i = 0; i < rows.length; i++) {
            // if (!rows[i]['fileNumber']) {
            //     rows[i]['isFileNumber'] = true
            //     isTableRows = true
            // } else if (!rows[i]['fileName']) {
            //     rows[i]['isFileName'] = true
            //     isTableRows = true
            // }

            // if (!rows[i]['fileTime']) {
            //     rows[i]['isFileTime'] = true
            //     isTableRows = true
            // }
            // else
            if (!rows[i]['fileName']) {
                rows[i]['isFileName'] = true
                isTableRows = true
            }
        }
        //判断数据
        if (isTableRows) {
            uploadSaveLoading.value = false
            window.$message?.warning('请先完善表单信息')
        } else {
            if (tableUploadType.value === 'add') {
                await batchUploadSaveApi(rows)
            } else {
                await batchEditSaveApi(rows)
            }
        }
    } else {
        window.$message?.warning('请先上传文件')
    }
}

//确认上传保存
const batchUploadSaveApi = async (rows) => {
    uploadSaveLoading.value = true
    const {error, code} = await archiveFileApi.batchUploadSave({
        list: rows
    },false)
    //判断状态
    uploadSaveLoading.value = false
    if (!error && code === 200) {
        window.$message?.success('保存成功')
        batchUploadCancel()
        getTableData()
    } else {
        window.$message?.error('保存失败')
    }
}

//取消上传
const batchUploadCancel = () => {
    tableUploadData.value = []
    uploadSaveLoading.value = false
    uploadsLoading.value = false
    showUploadModal.value = false


}
//上传新文件
const newUploadsChange = ({fileList}, row) => {
    if (fileList.length > 0) {
        tableUploadType.value = 'edit'
        const item = fileList[0]
        const name = item['originalName'] || ''
        const fileName = name.substring(0, name.lastIndexOf("."))
        //更新数据
        row.fileName = fileName;
        row.ossFileName = item?.name || ''
        row.fileUrl = item?.link || ''
        row.pdfFileUrl = item?.pdfUrl || ''
        row.filePage = item?.page || ''
        row.isUpdateUrl=1
    }
}

const newUploadsProgress = (val, row) => {
    row.newBtnLoading = val
}
//批量编辑
const batchEditClick = () => {
    const rows = deepClone(tableCheckedKeys.value)
    //判断是否满足条件
    const result = rows.every(({status})=> {
        return status !== 1 && status !== 2
    })
    //判断状态
    if (result) {
        tableUploadType.value = 'edit'
        setTableUploadColumn()
        uploadSaveLoading.value = false
        tableUploadData.value = rows
        showUploadModal.value = true
    } else {
        window.$message?.warning('已上报或已审批的文件不能编辑')
    }
}

//确认编辑上传保存
const batchEditSaveApi = async (rows) => {
    uploadSaveLoading.value = true
    const {error, code} = await archiveFileApi.batchUpdateSort({
        list: rows
    },false)
    //判断状态
    uploadSaveLoading.value = false
    if (!error && code === 200) {
        window.$message?.success('保存成功')
        batchUploadCancel()
        getTableData()
    } else {
        window.$message?.error('保存失败')
    }
}


//批量认证
const CertData = ref([])
const CertIds = ref([])
const CertPdf = ref('')
const CertColumns = [
    {key:'fileName', name: '文件名称'},
    {key:'action', name: '操作', width: 100}
]

//批量认证弹窗
const showCertificationModal = ref(false)
const certificationModalClick = () => {
    const rows = tableCheckedKeys.value;
    CertData.value = rows
    CertIds.value = rowsToId(rows)
    CertPdf.value = rows[0]?.pdfFileUrl || ''
    showCertificationModal.value = true
    /*const result = rows.every(({isCertification})=> {
        return isCertification === 0
    })
    if (result) {
        CertData.value = rows
        CertIds.value = rowsToId(rows)
        CertPdf.value = rows[0]?.pdfFileUrl || ''
        showCertificationModal.value = true
    } else {
        window.$message?.warning('已认证的文件不能再认证')
    }*/
}

//认证行被点击
const CertRowClick = ({row}) => {
    const pdfFileUrl = row?.pdfFileUrl || ''
    if (CertPdf.value !== pdfFileUrl) {
        CertPdf.value = pdfFileUrl
    }
}

//认证预览被点击
const CertRowClick2 = ({pdfFileUrl}) => {
    const pdfUrl = pdfFileUrl || ''
    if (CertPdf.value !== pdfUrl) {
        CertPdf.value = pdfUrl
    }
}

//确认认证
const CertLoading = ref(false)
const CertClick = async () => {
    /*CertLoading.value = true
    const {error, code} = await projectScanningApi.batchCertification({
        ids: CertIds.value
    }, false)
    //判断状态
    CertLoading.value = false
    if (!error && code === 200) {
        window.$message?.success('认证成功')
        showCertificationModal.value = false
        getTableData()
    } else {
        window.$message?.error('认证失败')
    }*/
}

//名称被点击
const tableRowName = (row) => {
    if (row['pdfFileUrl']) {
        window.open(row['pdfFileUrl'], '_blank')
    } else {
        window.$message?.warning('文件不存在')
    }
}


//左右拖动，改变树形结构宽度
const leftWidth = ref(382);
const onmousedown = () => {
    const leftNum = isCollapse.value ? 142 : 272
    document.onmousemove = (ve) => {
        let diffVal = ve.clientX - leftNum;
        if(diffVal >= 310 && diffVal <= 900) {
            leftWidth.value = diffVal;
        }
    }
    document.onmouseup = () => {
        document.onmousemove = null;
        document.onmouseup = null;
    }
}
</script>

<style lang="scss" scoped>
@import '~style/file/scoped/collection.scss';

.flex-center{
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    flex-direction: column;
}
</style>

<style lang="scss">
@import '~style/file/collection.scss';
</style>
