<template>
    <div class="hc-layout-box">
        <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">
                <el-scrollbar>
                    <ProjectTree :datas="ElTreeData" :autoExpandKeys="TreeAutoExpandKeys" @nodeTap="nodeElTreeClick"/>
                </el-scrollbar>
            </div>
            <!--左右拖动-->
            <div class="horizontal-drag-line" @mousedown="onmousedown"/>
        </div>
        <div class="hc-layout-content-box">
            <HcCard :scrollbar="false" actionSize="lg">
                <template #header>
                    <HcTooltip keys="project-scanning-upload">
                        <el-button type="primary" :disabled="!nodeIds" hc-btn @click="uploadModalClick">
                            <HcIcon name="add-circle"/>
                            <span>上传文件</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="project-scanning-download">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" :loading="batchDownloadLoading" @click="batchDownload">
                            <HcIcon name="download"/>
                            <span>批量下载</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="project-scanning-report">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" :loading="reportLoading" @click="reportModalClick">
                            <HcIcon name="send-plane-2"/>
                            <span>批量上报</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="project-scanning-attest">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" @click="certificationModalClick">
                            <HcIcon name="vip-diamond"/>
                            <span>批量认证</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="project-scanning-del">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" @click="batchDel">
                            <HcIcon name="delete-bin-2"/>
                            <span>批量删除</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="project-scanning-edit">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" @click="batchEditClick">
                            <HcIcon name="draft"/>
                            <span>批量编辑</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="project-scanning-abolish">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" @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" placeholder="审批状态" clearable>
                            <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" placeholder="认证状态" clearable>
                            <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" 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="tableListRef" :column="tableListColumn" :datas="tableListData" :loading="tableLoading" isCheck @selection-change="tableSelectionChange">
                    <template #fileName="{row}">
                        <span class="text-link" @click="tablePreview(row)">{{row?.fileName}}</span>
                    </template>
                    <template #isApprovalValue="{row}">
                        <el-tag :type="`${row.status === 2 ? 'success' : row.status === 0 ? 'warning' : row.status === 1 ? 'danger' : 'info'}`"
                                class="mx-1" effect="dark" v-if="row['isApprovalValue']">{{row['isApprovalValue']}}</el-tag>
                    </template>
                </HcTable>
                <template #action>
                    <HcPages :pages="searchForm" @change="pageChange"/>
                </template>
            </HcCard>
        </div>

        <!--新增编辑文件-->
        <el-dialog v-model="showUploadModal" title="上传工程文件" width="80vw" class="hc-modal-border hc-modal-table">
            <HcTable ui="hc-form-table" :column="tableUploadColumn" :datas="tableUploadData" :loading="uploadSaveLoading">
                <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" type="date" format="YYYY/MM/DD" value-format="YYYY-MM-DD" :clearable="false"/>
                </template>
                <template #sheetType="{row}" v-if="isBuiltDrawing === 1">
                    <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 === 1">
                    <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 === 1">
                    <el-input v-model="row.drawingNo"/>
                </template>
                <template #citeChangeNumber="{row}" v-if="isBuiltDrawing === 1">
                    <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 @change="newUploadsChange($event, row)" @progress="newUploadsProgress($event, row)" v-if="row.id">
                        <el-button type="primary" plain size="small" :loading="row['newBtnLoading']">上传新文件</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">
                        <HcFileUpload @change="uploadsChange" @progress="uploadsProgress">
                            <el-button type="primary" hc-btn :loading="uploadsLoading" :disabled="uploadSaveLoading">
                                <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 type="primary" hc-btn :disabled="uploadsLoading" :loading="uploadSaveLoading" @click="batchUploadSave">
                            <HcIcon name="save"/>
                            <span>提交保存</span>
                        </el-button>
                    </div>
                </div>
            </template>
        </el-dialog>

        <!--批量上报审批-->
        <HcReportModal
            title="批量上报审批"
            url="archiveFile/batchApproval"
            :show="showReportModal"
            :projectId="projectId"
            :contractId="contractId"
            :taskName="reportTaskName"
            :ids="reportIds"
            isDatas
            :datas="reportDatas"
            @hide="showReportModal = false"
            @finish="showReportFinish"
            @tagClose="reportTaskTagClose"
        />

        <!--批量认证-->
        <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>

    </div>
</template>

<script setup>
import {onMounted, ref, watch} from 'vue'
import {useAppStore} from "~src/store";
import {useRouter, useRoute} from 'vue-router'
import ProjectTree from "./components/ProjectTree.vue"
import HcFileUpload from "./components/HcFileUpload.vue"
import HcFileUpload1 from "./components/HcFileUpload1.vue"
import {getStoreData, setStoreData} from '~src/utils/storage'
import projectScanningApi from "~api/other-file/projectScanning";
import {downloadBlob, getArrValue, deepClone} from "vue-utils-plus"
import notableform from '~src/assets/view/notableform.svg';
import {eVisaTaskCheckApi} from "~api/other"
import tasksDataApi from '~api/tasks/data';
import ossApi from "~api/oss";
import dayjs from "dayjs"

//变量
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(getStoreData('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()
    //缓存展开的节点
    setStoreData('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) {
        window.open(evisaFile,'_blank')
    } else if (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 = rowsToId(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 = rowsToId(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 = 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 batchDel = () => {
    const rows = tableCheckedKeys.value;
    const result = rows.every(({status})=> {
        return status === 0
    })
    if (result) {
        const ids = rowsToId(rows)
        window?.$messageBox?.alert('请谨慎考虑是否要 批量删除文件？', '删除文件', {
            type: 'error',
            showCancelButton: true,
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            callback: (action) => {
                if (action === 'confirm') {
                    removeArchiveFile(ids)
                }
            }
        })
    } 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 = rowsToId(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('批量废除失败')
    }
}

//拼接ID
const rowsToId = (rows) => {
    return rows.map((obj) => {
        return obj.id;
    }).join(",")
}

//左右拖动，改变树形结构宽度
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>
