<template>
    <div class="hc-layout-box">
        <div :style="`width:${leftWidth}px;`" class="hc-layout-left-box bg-white">
            <div class="hc-project-box">
                <div class="hc-project-icon-box">
                    <HcIcon name="stack" />
                </div>
                <div class="ml-2 project-name-box">
                    <span class="project-alias">{{ projectInfo.name }}</span>
                </div>
            </div>
            <div class="hc-tree-box">
                <el-scrollbar>
                    <ProjectTree :auto-expand-keys="TreeAutoExpandKeys" :datas="ElTreeData" @node-tap="nodeElTreeClick" />
                </el-scrollbar>
            </div>
            <!-- 左右拖动 -->
            <div class="horizontal-drag-line" @mousedown="onmousedown" />
        </div>
        <div class="hc-layout-content-box">
            <HcNewCard :scrollbar="false" action-size="lg">
                <template #header>
                    <HcTooltip keys="project-scanning-upload">
                        <el-button :disabled="!nodeIds" hc-btn type="primary" @click="uploadModalClick">
                            <HcIcon name="add-circle" />
                            <span>上传文件</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="project-scanning-download">
                        <el-button
                            :disabled="tableCheckedKeys.length <= 0" :loading="batchDownloadLoading" hc-btn
                            @click="batchDownload"
                        >
                            <HcIcon name="download" />
                            <span>批量下载</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="project-scanning-report">
                        <el-button
                            :disabled="tableCheckedKeys.length <= 0" :loading="reportLoading" hc-btn
                            @click="reportModalClick"
                        >
                            <HcIcon name="send-plane-2" />
                            <span>批量上报</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="project-scanning-attest">
                        <el-button :disabled="tableCheckedKeys.length <= 0" hc-btn @click="certificationModalClick">
                            <HcIcon name="vip-diamond" />
                            <span>批量认证</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="project-scanning-del">
                        <el-button :disabled="tableCheckedKeys.length <= 0" hc-btn @click="batchDel">
                            <HcIcon name="delete-bin-2" />
                            <span>批量删除</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="project-scanning-edit">
                        <el-button :disabled="tableCheckedKeys.length <= 0" hc-btn @click="batchEditClick">
                            <HcIcon name="draft" />
                            <span>批量编辑</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="project-scanning-abolish">
                        <el-button :disabled="tableCheckedKeys.length <= 0" hc-btn @click="batchAbolishClick">
                            <HcIcon name="delete-bin-3" />
                            <span>批量废除</span>
                        </el-button>
                    </HcTooltip>
                </template>
                <template #search>
                    <div class="w-32">
                        <el-select v-model="searchForm.isApprovalValue" clearable placeholder="审批状态">
                            <el-option
                                v-for="item in approvalData" :label="item.dictValue"
                                :value="item.dictKey"
                            />
                        </el-select>
                    </div>
                    <div class="w-32 ml-4">
                        <el-select v-model="searchForm.isCertificationValue" clearable placeholder="认证状态">
                            <el-option
                                v-for="item in certificationType" :label="item.dictValue"
                                :value="item.dictKey"
                            />
                        </el-select>
                    </div>
                    <div class="w-64 ml-3">
                        <el-input
                            v-model="searchForm.queryValue" clearable placeholder="请输入文件名、责任者进行搜索"
                            @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="tableListRef" :column="tableListColumn" :datas="tableListData" :loading="tableLoading"
                    is-new :index-style="{ width: 60 }" is-check :check-style="{ width: 29 }"
                    @selection-change="tableSelectionChange"
                >
                    <template #fileName="{ row }">
                        <span class="text-link" @click="tablePreview(row)">{{ row?.fileName }}</span>
                    </template>
                    <template #isApprovalValue="{ row }">
                        <el-tag
                            v-if="row.isApprovalValue"
                            :type="`${row.status === 2 ? 'success' : row.status === 0 ? 'warning' : row.status === 1 ? 'danger' : 'info'}`"
                            class="mx-1" effect="dark"
                        >
                            {{ row.isApprovalValue }}
                        </el-tag>
                    </template>
                </HcTable>
                <template #action>
                    <HcPages :pages="searchForm" @change="pageChange" />
                </template>
            </HcNewCard>
        </div>

        <!-- 新增编辑文件 -->
        <hc-new-dialog v-model="showUploadModal" is-table title="上传工程文件" widths="80vw">
            <HcTable
                :column="tableUploadColumn" :datas="tableUploadData" :loading="uploadSaveLoading"
                ui="hc-form-table" is-new :index-style="{ width: 60 }"
            >
                <template #fileNumber="{ row }">
                    <el-input
                        v-model="row.fileNumber" :class="row.isFileNumber ? 'is-error' : ''"
                        @input="tableInput($event, row, 'isFileNumber')"
                    />
                </template>
                <template #fileName="{ row }">
                    <el-input
                        v-model="row.fileName" :class="row.isFileName ? 'is-error' : ''"
                        @input="tableInput($event, row, 'isFileName')"
                    />
                </template>
                <template #fileTime="{ row }">
                    <el-date-picker
                        v-model="row.fileTime" :clearable="false" format="YYYY/MM/DD" type="date"
                        value-format="YYYY-MM-DD"
                    />
                </template>
                <template v-if="isBuiltDrawing === 1" #sheetType="{ row }">
                    <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 v-if="isBuiltDrawing === 1" #sheetSource="{ row }">
                    <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 v-if="isBuiltDrawing === 1" #drawingNo="{ row }">
                    <el-input v-model="row.drawingNo" />
                </template>
                <template v-if="isBuiltDrawing === 1" #citeChangeNumber="{ row }">
                    <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 #action="{ row, index }">
                    <HcFileUpload1
                        v-if="row.id" @change="newUploadsChange($event, row)"
                        @progress="newUploadsProgress($event, row)"
                    >
                        <el-button :loading="row.newBtnLoading" plain size="small" type="primary">
                            上传新文件
                        </el-button>
                    </HcFileUpload1>
                    <el-button
                        :loading="row.delBtnLoading" plain size="small" type="danger"
                        @click="delUploadData(row, index)"
                    >
                        删除
                    </el-button>
                </template>
            </HcTable>
            <template #footer>
                <div class="lr-dialog-footer">
                    <div class="left flex items-center">
                        <HcFileUpload @change="uploadsChange" @progress="uploadsProgress">
                            <el-button :disabled="uploadSaveLoading" :loading="uploadsLoading" hc-btn type="primary">
                                <HcIcon name="add-circle" />
                                <span>新增上传</span>
                            </el-button>
                        </HcFileUpload>
                    </div>
                    <div class="right">
                        <el-button size="large" @click="batchUploadCancel">
                            <HcIcon name="close" />
                            <span>取消</span>
                        </el-button>
                        <el-button
                            :disabled="uploadsLoading" :loading="uploadSaveLoading" hc-btn type="primary"
                            @click="batchUploadSave"
                        >
                            <HcIcon name="save" />
                            <span>提交保存</span>
                        </el-button>
                    </div>
                </div>
            </template>
        </hc-new-dialog>

        <!-- 批量上报审批 -->
        <HcReportModal
            :contract-id="contractId"
            :datas="reportDatas"
            :ids="reportIds"
            :project-id="projectId"
            :show="showReportModal"
            :task-name="reportTaskName"
            is-datas
            title="批量上报审批"
            url="archiveFile/batchApproval2"
            @finish="showReportFinish"
            @hide="showReportModal = false"
            @tag-close="reportTaskTagClose"
        />

        <!-- 批量认证 -->
        <hc-new-dialog v-model="showCertificationModal" is-table title="批量认证" widths="80vw">
            <div class="hc-card-body-flex">
                <div class="flex-table">
                    <HcTable :column="CertColumns" :datas="CertData" ui="hc-form-table" is-new :index-style="{ width: 60 }" @row-click="CertRowClick">
                        <template #action="{ row, index }">
                            <el-button plain size="small" type="primary" @click.stop="CertRowClick2(row)">
                                预览
                            </el-button>
                        </template>
                    </HcTable>
                </div>
                <div v-if="CertPdf" class="flex-iframe">
                    <iframe :src="CertPdf" allow="display-capture" frameborder="1" height="100%" width="100%" />
                </div>
                <div v-else class="flex-iframe hc-no-table-form">
                    <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 :loading="CertLoading" hc-btn type="primary" @click="CertClick">
                        <HcIcon name="save" />
                        <span>确认认证</span>
                    </el-button>
                </div>
            </template>
        </hc-new-dialog>
    </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { useAppStore } from '~src/store'
import { useRoute, useRouter } from 'vue-router'
import ProjectTree from './components/ProjectTree.vue'
import HcFileUpload from './components/HcFileUpload.vue'
import HcFileUpload1 from './components/HcFileUpload1.vue'
import { getStoreValue, setStoreValue } from '~src/utils/storage'
import projectScanningApi from '~api/other-file/projectScanning'
import notableform from '~src/assets/view/notableform.svg'
import { arrToId, deepClone, downloadBlob, getArrValue } from 'js-fast-way'
import { eVisaTaskCheckApi } from '~api/other'
import tasksDataApi from '~api/tasks/data'
import ossApi from '~api/oss'
import dayjs from 'dayjs'
import { delMessageV2 } from '~com/message/index.js'
import { toPdfPage } from '~uti/btn-auth'

//变量
const router = useRouter()
const useRoutes = useRoute()
const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId)
const contractId = ref(useAppState.getContractId)
const projectInfo = ref(useAppState.getProjectInfo)
const isCollapse = ref(useAppState.getCollapse)

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

//自动展开缓存
const TreeAutoExpandKeys = ref(getStoreValue('scanningTreeExpandKeys') || [])

const dayDate = ref('')

//渲染完成
onMounted(() => {
    getClassIfyList()
    firstTaskStatus()
    certificationStatus()
    dayDate.value = dayjs(new Date()).format('YYYY-MM-DD')
})

//获取树的数据
const ElTreeData = ref([])
const getClassIfyList = async () => {
    const { error, code, data } = await projectScanningApi.getClassIfyList({
        projectId: projectId.value,
        contractId: contractId.value,
    })
    //处理数据
    if (!error && code === 200) {
        ElTreeData.value = getArrValue(data)
    } else {
        ElTreeData.value = []
    }
}

//项目树被点击
const treeNodeInfo = ref({})
const treeDataInfo = ref({})
const nodeIds = ref('')
const isStorageNode = ref(0)
const isBuiltDrawing = ref(0)
const nodeElTreeClick = ({ node, data, keys, key }) => {
    treeNodeInfo.value = node
    treeDataInfo.value = data
    //设置变量
    nodeIds.value = key || ''
    isStorageNode.value = data['isStorageNode'] || 0
    isBuiltDrawing.value = data['isBuiltDrawing'] || 0
    //设置搜索数据
    searchForm.value.current = 1
    searchForm.value.nodeIds = key || ''
    setTableColumns()
    getTableData()
    //缓存展开的节点
    setStoreValue('scanningTreeExpandKeys', keys)
}

//获取任务类型
const approvalData = ref([])
const firstTaskStatus = async () => {
    const { error, code, data } = await tasksDataApi.queryTaskTypeStatus({
        typeOrStatus: 'first_task_status',
    })
    //处理数据
    if (!error && code === 200) {
        approvalData.value = getArrValue(data)
    } else {
        approvalData.value = []
    }
}

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

//获取图幅类型
const sheetType = ref([])
const sheetTypeStatus = async () => {
    const { error, code, data } = await tasksDataApi.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 tasksDataApi.queryTaskTypeStatus({
        typeOrStatus: 'sheet_source',
    })
    //处理数据
    if (!error && code === 200) {
        sheetSourceType.value = getArrValue(data)
    } else {
        sheetSourceType.value = []
    }
}

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

//回车搜索
const keyUpEvent = (e) => {
    if (e.key === 'Enter') {
        searchClick()
    }
}

//搜索
const searchClick = () => {
    if (nodeIds.value) {
        searchForm.value.current = 1
        getTableData()
    } else {
        window?.$message?.warning('请先在左边选择一个树节点')
    }
}

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

//设置表头
const tableListColumn = ref([
    { key: 'fileNumber', name: '文件编号', width: 160 },
    { key: 'fileName', name: '文件名称' },
    { key: 'filePage', name: '文件页数', width: 120 },
    { key: 'isCertificationValue', name: '认证状态', width: 160 },
    { key: 'isApprovalValue', name: '状态', width: 160 },
    { key: 'fileTime', name: '文件时间', width: 160 },
    { key: 'dutyUser', name: '责任者', width: 160 },
])
const setTableColumns = () => {
    if (isBuiltDrawing.value === 1) {
        tableListColumn.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 {
        tableListColumn.value = [
            { key: 'fileNumber', name: '文件编号', width: 160 },
            { key: 'fileName', name: '文件名称' },
            { key: 'filePage', name: '文件页数', width: 120 },
            { key: 'isCertificationValue', name: '认证状态', width: 160 },
            { key: 'isApprovalValue', name: '状态', width: 160 },
            { key: 'fileTime', name: '文件时间', width: 160 },
            { key: 'dutyUser', name: '责任者', width: 160 },
        ]
    }
}

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

//多选
const tableListRef = ref(null)
const tableCheckedKeys = ref([])
const tableSelectionChange = (rows) => {
    tableCheckedKeys.value = rows.filter((item) => {
        return (item ?? '') !== ''
    })
}

//文件名称被点击
const tablePreview = (row) => {
    const pdfUrl = row['pdfFileUrl'] || ''
    const evisaFile = row['evisaFile'] || ''
    if (evisaFile) {
        toPdfPage(evisaFile)
        //window.open(evisaFile, '_blank')
    } else if (pdfUrl) {
        toPdfPage(pdfUrl)
        //window.open(pdfUrl, '_blank')
    } else {
        window.$message?.warning('该数据暂无PDF')
    }
}

//新增文件
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
    } else {
        window?.$message?.warning('请先选择一个子节点')
    }
}

//设置文件表头
const tableUploadColumn = ref([
    { key: 'fileNumber', name: '文件编号' },
    { key: 'fileName', name: '文件名称' },
    { key: 'fileTime', name: '文件时间' },
    { key: 'isApproval', name: '是否需要审批' },
    { key: 'isNeedCertification', name: '是否需要认证' },
    { key: 'dutyUser', name: '责任者' },
    { key: 'action', name: '操作', width: 180 },
])
const setTableUploadColumn = () => {
    if (isBuiltDrawing.value === 1) {
        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: 'action', name: '操作', width: 180 },
        ]
    } else {
        tableUploadColumn.value = [
            { key: 'fileNumber', name: '文件编号' },
            { key: 'fileName', name: '文件名称' },
            { key: 'fileTime', name: '文件时间' },
            { key: 'isApproval', name: '是否需要审批' },
            { key: 'isNeedCertification', name: '是否需要认证' },
            { key: 'dutyUser', name: '责任者' },
            { key: 'action', name: '操作', width: 180 },
        ]
    }
}
const tableUploadData = ref([])

//上传的文件结果
const uploadsChange = ({ fileList }) => {
    let newArr = []
    const sheet = sheetType.value, source = sheetSourceType.value
    for (let i = 0; i < fileList.length; i++) {
        const item = fileList[i]
        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: dayDate.value,
            fileUrl: item?.link || '',
            sheetType: sheet.length > 0 ? sheet[0]['dictKey'] || '' : '',
            sheetSource: source.length > 0 ? source[0]['dictKey'] || '' : '',
            drawingNo: '',
            citeChangeNumber: '',
            isApproval: 0,
            isNeedCertification: 0,
            dutyUser: '',
            pdfFileUrl: item?.pdfUrl || '',
            filePage: item?.page || '',
        })
    }
    tableUploadData.value = newArr
}

//上传进度
const uploadsLoading = ref(false)
const uploadsProgress = (val) => {
    uploadsLoading.value = val
}

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

//输入框验证
const tableInput = (val, row, isv) => {
    if (val) {
        row[isv] = false
    } else {
        row[isv] = true
    }
}


//上传新文件
const newUploadsChange = ({ fileList }, row) => {
    if (fileList.length > 0) {
        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 || ''
    }
}

const newUploadsProgress = (val, row) => {
    row.newBtnLoading = val
}

//删除
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 (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 projectScanningApi.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 batchEditClick = () => {
    const rows = deepClone(tableCheckedKeys.value)
    //判断是否满足条件
    const result = rows.every(({ status }) => {
        return status !== 1 && status !== 2
    })
    console.log(rows)
    //判断状态
    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 projectScanningApi.batchEditSave({
        list: rows,
    }, false)
    //判断状态
    uploadSaveLoading.value = false
    if (!error && code === 200) {
        window.$message?.success('保存成功')
        batchUploadCancel()
        getTableData()
    } else {
        window.$message?.error('保存失败')
    }
}

//批量下载
const batchDownloadLoading = ref(false)
const batchDownload = async () => {
    const rows = deepClone(tableCheckedKeys.value)
    const ids = arrToId(rows)
    //批量下载
    batchDownloadLoading.value = true
    const { error, disposition, res } = await projectScanningApi.batchDownloadFileToZip({ ids: ids })
    //处理数据
    batchDownloadLoading.value = false
    if (!error) {
        if (disposition) {
            downloadBlob(res, disposition)
        } else {
            window.$message?.error('数据异常')
        }
    }
}

//批量上报
const reportIds = ref('')
const reportTaskName = ref('')
const reportDatas = ref([])
const showReportModal = ref(false)
const reportLoading = ref(false)
const reportModalClick = async () => {
    const rows = tableCheckedKeys.value
    const result = rows.every(({ status }) => {
        return status === 0 //isApproval !== 1 && status !== 0 || isApproval === 1 && status !== 0
    })
    if (result) {
        reportLoading.value = true
        const taskCheck = await eVisaTaskCheckApi({
            projectId: projectId.value,
            contractId: contractId.value,
        })
        if (taskCheck) {
            reportIds.value = arrToId(rows)
            //设置任务数据
            let reportDataArr = []
            rows.forEach(item => {
                reportDataArr.push({
                    id: item?.id,
                    name: item?.fileName,
                })
            })
            reportDatas.value = reportDataArr
            //设置任务名称
            reportTaskName.value = rows.length > 1 ? `${rows[0].fileName}等${rows.length}个文件` : rows[0].fileName
            reportLoading.value = false
            showReportModal.value = true
        } else {
            reportLoading.value = false
        }
    } else {
        window.$message?.warning('已上报的文件不能进行再次上报，若要重新上报，要先撤回之前的上报，再重新上报')
    }
}

//上报的审批内容移除
const reportTaskTagClose = (index) => {
    const row = tableCheckedKeys.value[index]
    tableListRef.value?.toggleRowSelection(row, false)
}

//上报完成
const showReportFinish = () => {
    showReportModal.value = false
    getTableData()
}

//批量认证
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
    const result = rows.every(({ isCertification }) => {
        return isCertification === 0
    })
    if (result) {
        CertData.value = rows
        CertIds.value = arrToId(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.split(','),
    }, false)
    //判断状态
    CertLoading.value = false
    if (!error && code === 200) {
        window.$message?.success('认证成功')
        showCertificationModal.value = false
        getTableData()
    } else {
        window.$message?.error('认证失败')
    }
}

//批量删除
const batchDel = () => {
    const rows = tableCheckedKeys.value
    const result = rows.every(({ status }) => {
        return status === 0
    })
    if (result) {
        const ids = arrToId(rows)
        delMessageV2(async (action, instance, done) => {
            if (action === 'confirm') {
                instance.confirmButtonLoading = true
                removeArchiveFile(ids)
                instance.confirmButtonLoading = false
                done()
            } else {
                done()
            }
    })
    } else {
        window.$message?.warning('已上报的文件需要先废除，才能执行删除')
    }
}
//确认批量删除
const removeArchiveFile = async (ids) => {
    const { error, code } = await projectScanningApi.removeArchiveFile({
        ids: ids,
    }, false)
    //判断状态
    CertLoading.value = false
    if (!error && code === 200) {
        window.$message?.success('删除成功')
        getTableData()
    } else {
        window.$message?.error('删除失败')
    }
}

//批量废除
const batchAbolishClick = () => {
    const rows = tableCheckedKeys.value
    const result = rows.every(({ status }) => {
        return status > 0
    })
    if (result) {
        const ids = arrToId(rows)
        window?.$messageBox?.alert('是否废除勾选的已上报文件？', '确认操作', {
            type: 'warning',
            showCancelButton: true,
            confirmButtonText: '确定废除',
            cancelButtonText: '取消',
            callback: (action) => {
                if (action === 'confirm') {
                    batchAbolishSave(ids)
                }
            },
        })
    } else {
        window.$message?.warning('未上报的文件不能废除')
    }
}
//确认批量废除
const batchAbolishSave = async (ids) => {
    const { error, code } = await projectScanningApi.batchAbolishSave({
        ids: ids,
    }, false)
    //判断状态
    if (!error && code === 200) {
        window.$message?.success('批量废除成功')
        getTableData()
    } else {
        window.$message?.error('批量废除失败')
    }
}

//左右拖动，改变树形结构宽度
const leftWidth = ref(382)
const onmousedown = () => {
    const leftNum = isCollapse.value ? 142 : 272
    document.onmousemove = (ve) => {
        const 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 '../../styles/other-file/project-scanning.scss';
</style>

<style lang="scss">
.el-table td.el-table__cell .hc-file-upload-box {
    display: inline-block;
    margin-right: 12px;
}
</style>
