<template>
    <div class="hc-layout-box" id="first-item-node-layout-target">
        <div class="hc-layout-left-box" :style="'width:' + leftWidth + 'px;'" v-show="!isFirstReportDrawer">
            <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>
                    <WbsTree :autoExpandKeys="TreeAutoExpandKeys" :projectId="projectId" :contractId="contractId" @nodeTap="nodeWbsElTreeClick"/>
                </el-scrollbar>
            </div>
            <!--左右拖动-->
            <div class="horizontal-drag-line" @mousedown="onmousedown"/>
        </div>
        <div class="hc-layout-content-box first-item" v-show="!isFirstReportDrawer">
            <HcCard :scrollbar="false" actionSize="lg">
                <template #header>
                    <HcTooltip keys="other-first-item-report" v-if="tabTypeKey === 'mark'">
                        <el-button type="primary" hc-btn :disabled="tableSelectionKeys.length <= 0" @click="firstReportClick">
                            <HcIcon name="send-plane-2"/>
                            <span>上报首件</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="other-first-item-report-approval" v-if="tabTypeKey === 'query'">
                        <el-button type="primary" hc-btn :disabled="tableSelectionKeys.length <= 0" @click="reportModalClick(1)">
                            <HcIcon name="send-plane-2"/>
                            <span>上报审批</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="other-first-item-repeal" v-if="tabTypeKey === 'query'">
                        <el-button hc-btn :disabled="tableSelectionKeys.length <= 0" @click="batchAbolishClick">
                            <HcIcon name="delete-bin-3"/>
                            <span>批量废除</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="other-first-item-down-print">
                        <el-button hc-btn :disabled="tableSelectionKeys.length <= 0" :loading="printLoading" @click="batchPrint">
                            <HcIcon name="printer"/>
                            <span>预览/打印</span>
                        </el-button>
                    </HcTooltip>
                </template>
                <template #extra>
                    <HcNewSwitch :datas="tabTypeTab" :keys="tabTypeKey" @change="tabTypeChange"/>
                </template>
                <template #search>
                    <div class="w-32">
                        <el-select v-model="searchForm.status" placeholder="流程状态" clearable>
                            <el-option v-for="item in processStatus" :label="item['dictValue']" :value="item['dictKey']"/>
                        </el-select>
                    </div>
                    <div class="w-32 ml-3">
                        <el-select v-model="searchForm.reportNumber" placeholder="上报批次" clearable>
                            <el-option v-for="item in reportBatch" :label="item" :value="item"/>
                        </el-select>
                    </div>
                    <div class="w-64 ml-3">
                        <HcDatePicker :dates="betweenTime" clearable @change="betweenTimeUpdate"/>
                    </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 #name="{row}">
                        <span class="text-link" @click="tableRowName(row)">{{row?.name}}</span>
                    </template>
                    <template #waitingUserList="{row}">
                        <template v-for="item in row['waitingUserList']">
                            <el-tag :type="`${item.status === 2 ? 'success' : item.status === 3 ? 'warning' : item.status === 999 ? 'danger' : 'info'}`"
                                    class="mx-1" effect="dark" v-if="item['waitingUserName']">{{item['waitingUserName']}}</el-tag>
                        </template>
                    </template>
                    <template #taskStatusStr="{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['taskStatusStr']">{{row['taskStatusStr']}}</el-tag>
                    </template>
                </HcTable>
                <template #action>
                    <div class="lr-dialog-footer">
                        <div class="left">
                            <span class="text-success">任务人中：</span>
                            <el-tag type="success" class="mx-1" effect="dark">已签字</el-tag>
                            <el-tag type="warning" class="mx-1" effect="dark">已废除</el-tag>
                            <el-tag type="danger" class="mx-1" effect="dark">签字异常</el-tag>
                        </div>
                        <div class="right">
                            <HcPages :pages="searchForm" @change="pageChange"/>
                        </div>
                    </div>
                </template>
            </HcCard>
        </div>

        <!--上报首件-->
        <HcDrawer :show="isFirstReportDrawer" :isCard="false" uis="hc-first-item-node-layout" to-id="first-item-node-layout-target" @close="FirstReportDrawerClose">
            <div class="node-content">
                <div class="node-form">
                    <el-scrollbar v-if="contractId && isTableForm">
                        <div class="hc-excel-table-form-view" :id="`table-form-${contractId}`"></div>
                    </el-scrollbar>
                    <HcStatus :desc="statusDesc" v-else/>
                </div>
                <div class="node-file">
                    <div class="title">上传总结报告</div>
                    <div class="node-upload-box" v-if="contractId && isTableForm">
                        <HcUpload :fileList="fileListData" :pkeyId="pkeyIds" @finish='uploadChange'/>
                    </div>
                    <div class="node-upload-box" v-else>
                        <el-alert title="表单异常，暂时无法使用上传" type="warning" show-icon :closable="false"/>
                    </div>
                    <el-divider border-style="dashed" />
                    <div class="title">文件附件</div>
                    <div class="hc-table-node-file-box">
                        <HcTable :column="tableFileColumn" :datas="tableFileData" :isIndex="false">
                            <template #action="{row,index}">
                                <el-button type="danger" plain size="small" @click="tableDelButton(index)">删除</el-button>
                            </template>
                        </HcTable>
                    </div>
                </div>
            </div>
            <div class="node-action">
                <el-button type="primary" hc-btn :disabled="!contractId || !isTableForm||NodeStatus === '3'" :loading="tableFormSaveLoading" @click="saveBussData">
                    <HcIcon name="save"/>
                    <span>保存</span>
                </el-button>
                <el-button hc-btn :disabled="!contractId || !isTableForm || !tableFormId||NodeStatus === '1'" @click="bussPdfInfo">
                    <HcIcon name="eye"/>
                    <span>预览</span>
                </el-button>
                <el-button v-if="NodeStatus !== '3'" hc-btn :disabled="!contractId || !isTableForm || !tableFormId||NodeStatus === '3' || NodeStatus === '1'" :loading="reportLoading" @click="reportModalClick(2)">
                    <HcIcon name="send-plane-2"/>
                    <span>上报</span>
                </el-button>

                <el-button hc-btn @click="abolishOneClick"  v-if="NodeStatus === '3'">
                    <HcIcon name="arrow-go-back"/>
                    <span>撤回上报流程</span>
                </el-button>

                <el-button hc-btn @click="FirstReportDrawerClose">
                    <HcIcon name="close"/>
                    <span>返回</span>
                </el-button>
            </div>
        </HcDrawer>

        <!--上报审批-->
        <HcReportModal
            title="上报审批"
            url="informationWriteQuery/batchTask"
            :show="showReportModal"
            :projectId="projectId"
            :contractId="contractId"
            type="first"
            :typeData="reportTypeData"
            :taskName="reportTaskName"
            :ids="reportIds"
            :isDatas="isReportModalDatas"
            :datas="reportDatas"
            @hide="showReportModal = false"
            @finish="showReportFinish"
            @tagClose="reportTaskTagClose"
        />
    </div>
</template>

<script setup>
import {useAppStore} from "~src/store";
import {nextTick, onMounted, ref, watch} from 'vue'
import {useRouter, useRoute} from 'vue-router'
import WbsTree from "./components/WbsTree.vue"
import HcUpload from "./components/HcUpload.vue"
import HTableForm from "~src/plugins/HTableForm"
import {getReportNumber,eVisaTaskCheckApi} from "~api/other";
import firstApi from '~api/other/first-item';
import tasksApi from '~api/tasks/data';
import {getStoreData, setStoreData} from '~src/utils/storage'
import {getArrValue, isString, getObjValue, getObjNullValue,deepClone} from "vue-utils-plus"
import queryApi from "~api/data-fill/query";
import wbsApi from "~api/data-fill/wbs";
//变量
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 contractInfo = ref(useAppState.getContractInfo);
const isCollapse = ref(useAppState.getCollapse)

//路由参数
const routerQuery = useRoutes?.query;
const typeName = routerQuery?.type || 'mark'

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


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

//类型tab数据和相关处理
const tabTypeKey = ref(typeName)
const tabTypeTab = ref([
    {key:'mark',  name: '已标记为首件'},
    {key:'query', name: '首件查询'}
]);

const tabTypeChange = (item) => {
    tableFormId.value = ''
    tabTypeKey.value = item?.key
    if (searchForm.value.wbsId) {
        searchForm.value.current = 1;
        getTableData()
    }
    //路由跳转
    router.push({
        path: useRoutes.path,
        query: {type: item?.key}
    })
}

//渲染完成
onMounted(() => {
    firstTaskStatus()
})

//项目树被点击
const treeItem = ref({})
const nodeWbsElTreeClick = ({data, keys}) => {
    treeItem.value = data
    searchForm.value.contractIdRelation = data['contractIdRelation']
    searchForm.value.wbsId = data['primaryKeyId']
    //缓存自动展开
    TreeAutoExpandKeys.value = keys
    setStoreData('firstItemTreeKeys', keys)
    //获取相关数据
    getReportNumberByContractId(data['contractIdRelation'])
    searchClick()
}

//获取流程状态
const processStatus = ref([])
const firstTaskStatus = async () => {
    const { data } = await tasksApi.queryTaskTypeStatus({
        typeOrStatus: 'first_task_status'
    })
    //处理数据
    processStatus.value = getArrValue(data)
}
//查询状态
const NodeStatus = ref('1')
const queryNodeStatusId=ref('')
 const { contractType } = contractInfo.value;
const authBtnTabKey = ref(contractType===2?'2':'1')
const queryNodeStatus = async () => {
    const info = treeItem.value;
    console.log(info,'info')
    const {error, code, data} = await wbsApi.queryNodeStatusSj({
        // primaryKeyId: info['contractIdRelation'] ? info['id'] : info['primaryKeyId'],
        // classify: 1
    //    primaryKeyId: authBtnTabKey.value==1 ? info['id'] : info['primaryKeyId'],
        primaryKeyId:info.primaryKeyId,
        classify: authBtnTabKey.value,
        id:queryNodeStatusId.value

    })
    //1 未填报，2待上报，3已上报
    if (!error && code === 200) {
        NodeStatus.value = data ?? '1'
    } else {
        NodeStatus.value = '1'
    }
}
//获取上报批次
const reportBatch = ref([])
const getReportNumberByContractId = async (cid) => {
    const { data } = await getReportNumber({
         projectId:projectId.value,
        contractId: contractId.value,
        contractIdRelation: cid ?? '',
        firstTitle: tabTypeKey.value === 'query' ? 1: null
    })
    //处理数据
    reportBatch.value = getArrValue(data)
}

//搜索表单
const searchForm = ref({
    wbsId: '', status: null, reportNumber: null, queryValue: '', betweenTime: '',
    contractIdRelation: '', current: 1, size: 20, total: 0
})

//日期时间被选择
const betweenTime = ref(null)
const betweenTimeUpdate = ({query,arr}) => {
    betweenTime.value = arr
    searchForm.value.betweenTime = query
}

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

//搜索
const searchClick = () => {
    if (searchForm.value.wbsId) {
        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:'name', name: '文件名称'},
    {key:'waitingUserList', name: '任务人'},
    {key:'startTime', name: '开始时间', width: 180},
    {key:'taskStatusStr', name: '流程状态', width: 140},
    {key:'reportNumber', name: '上报批次', width: 120},
])

//获取表格数据
const tableLoading = ref(false)
const tableListData = ref([])
const getTableData = async () => {
    const searchInfo = searchForm.value
    const tabKey = tabTypeKey.value
    if (!!searchInfo.wbsId) {
        //初始处理
        tableLoading.value = true
        tableListRef.value?.clearSelection()
        tableSelectionKeys.value = []
        tableListData.value = []
        //获取相关数据
        let addFormData = {
            projectId: projectId.value,
            contractId: contractId.value,
            isFirst: 1,
        }
        const treeInfo = treeItem.value
        //已标记的首件
        if (tabKey === 'mark' && addFormData['firstTitle']) {
            delete addFormData.firstTitle
        }
        //查询数据
        if (tabKey === 'query') {
            addFormData['firstTitle'] = 1
        }
        addFormData['wbsId'] = treeInfo['contractIdRelation'] ? treeInfo['id'] : treeInfo['primaryKeyId']
        //处理数据
        const { error, code, data } = await firstApi.getQueryPageData({
            ...addFormData,
            ...searchInfo,
        })
        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
        }
    } else {
        window?.$message?.warning('请先选择一个树节点')
    }
}

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

//文件名称被点击
const tableRowName = (row) => {
    //如果 evisaPdfUrl 不为空，使用evisaPdfUrl，反之使用pdfUrl
    if (tabTypeKey.value === 'query') {
        //首件查询时，直接调用接口
        getBussPdfInfo(row.id + '')
    } else if (row['evisaPdfUrl']) {
        window.open(row['evisaPdfUrl'],'_blank')
    } else if (row['pdfUrl']) {
        window.open(row['pdfUrl'],'_blank')
    } else {
        window.$message?.warning('文件不存在')
    }
}

//上报首件
const isFirstReportDrawer = ref(false)
const isCanreport=ref(false)
const firstReportClick = () => {
    const rows = deepClone(tableSelectionKeys.value)
    //判断是否满足条件
    const result = rows.every(({status})=> {
        return status === 2
        // return status === 0 || status === 3
    })
    isCanreport.value=result
    //判断状态
    // if (result) {
    //     isFirstReportDrawer.value = true
    //     queryNodeStatus()
    //     tableFileData.value = rows
    //     getFirstExcelHtml()
    // } else {
    //     tableFileData.value = []
    //     window.$message?.warning('已上报的文件不能进行再次上报，若要重新上报，要先撤回之前的上报，再重新上报')
    // }
        isFirstReportDrawer.value = true
        queryNodeStatus()
        tableFileData.value = rows
        getFirstExcelHtml()
}
//撤回上报流程
const abolishOneClick = () => {
    window?.$messageBox?.alert('请谨慎考虑后，是否确定撤回？', '撤回上报', {
        showCancelButton: true,
        confirmButtonText: '确定撤回',
        cancelButtonText: '取消',
        callback: (action) => {
            if (action === 'confirm') {
                abolishOneSave()
            }
        }
    })
}

//撤回请求
const abolishOneSave = async () => {
    const info = treeItem.value;
    const {error, code} = await wbsApi.abolishOneSJ({
        primaryKeyId:  info?.primaryKeyId || '',
        id:queryNodeStatusId.value
    })
    if (!error && code === 200) {
        window.$message?.success('撤回成功')
        getTableDataAll()
        window?.location?.reload()  //刷新页面
    }
}

const FirstReportDrawerClose = () => {
    isFirstReportDrawer.value = false
}

//获取表单
const statusDesc = ref('')
const isTableForm = ref(false)
const pkeyIds = ref('')
const getFirstExcelHtml = async () => {
    const cid = contractId.value;
    const { error, code, data } = await firstApi.getFirstExcelHtml({
        contractId: contractId.value || ''
    }, false)
    //处理数据
    const temp = isString(data?.data) ? data?.data || '' : ''
    if (!error && code === 200 && temp) {
        let pkeyId = data?.id || ''
        pkeyIds.value = pkeyId
        await getFirstBussDataInfo(pkeyId)
        setHTableForm(temp, cid)
    } else {
        isTableForm.value = false
        statusDesc.value = '暂无表单'
        window?.$message?.warning('暂无表单')
    }
}

//渲染表单
const tableFormApp = ref(null)
const setHTableForm = (resData, cid) => {
    //先卸载
    if (tableFormApp.value) {
        tableFormApp.value?.unmount()
    }
    if (resData) {
        isTableForm.value = true
        nextTick(() => {
            tableFormApp.value = HTableForm.createForm({
                template: resData,
                tableForm: tableFormData.value,
                appId: `#table-form-${cid}`
            })
        })
    } else {
        isTableForm.value = false
        statusDesc.value = '暂无表单'
        window?.$message?.warning('暂无表单')
    }
}

//获取回显数据
const tableFormData = ref({})
const getFirstBussDataInfo = async (pkeyId) => {
    if (pkeyId) {
        const { data } = await firstApi.getFirstBussDataInfo({
            contractId: contractId.value || '',
            firstId: pkeyId + ''
        }, false)
        const info = getObjValue(data)
        if (getObjNullValue(info)) {
            HTableForm.setPickerKey(info)
            tableFormData.value = info
        } else {
            tableFormData.value = {}
        }
    } else {
        tableFormData.value = {}
    }
}

//上传变量
const fileListData = ref([]);
const finishFile = ref({
    sourceUrl: '', pdfUrl: '', firstFileName: ''
})
//上传文件
const uploadChange = async ({type, res}) => {
    if (type === 'success') {
        const {code, data, msg} = res
        if (code === 200) {
            finishFile.value = {
                sourceUrl: data?.sourceUrl,
                pdfUrl: data?.pdfUrl,
                firstFileName: data?.fileName,
            }
            window.$message?.success(msg);
        } else {
            window.$message?.error(msg || '上传失败');
        }
    }
}

//文件附件列表
const tableFileColumn = ref([
    {key:'name', name: '文件名称'},
    {key:'action', name: '操作', width: 80, align: 'center'}
]);
const tableFileData = ref([]);
const tableDelButton = (index) => {
    const arr = tableFileData.value
    if (arr.length > 1) {
        window?.$messageBox?.alert('确定删除该文件吗？', '删除提醒', {
            type: 'warning',
            showCancelButton: true,
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            callback: (action) => {
                if (action === 'confirm') {
                    tableFileData.value.splice(index, 1)
                }
            }
        })
    } else {
        window?.$message?.warning('至少保留一个文件')
    }
}

//填报数据保存
const pdfId=ref('')
const saveBussData = async () => {
    console.log('保存');
    const { id } = treeItem.value
    const res = await saveExcelBussData(id + '')
    //刷新页面
    //  window?.location?.reload()  //刷新页面
    if (res) {
        pdfId.value=res
        queryNodeStatusId.value=res
         queryNodeStatus()
        await getBussPdfInfo(res)



    }
}

//保存请求
const tableFormSaveLoading = ref(false)
const tableFormId = ref('')
const saveExcelBussData = async (pkeyId) => {
    tableFormId.value = ''
    const { primaryKeyId } = treeItem.value
    tableFormSaveLoading.value = true
    const linkIds = rowsToArr(tableFileData.value);
    const { error, code, data } = await firstApi.saveBussData({
        ...tableFormData.value,
        projectId: projectId.value,
        contractId: contractId.value,
        firstNodeId: primaryKeyId,
        pkeyId: pkeyId,
        classify: '1',
        isFirst: 1,
        linkProcessList: linkIds,
        ...finishFile.value
    }, false)
    //判断状态
    tableFormSaveLoading.value = false
    if (!error && code === 200 && isString(data)) {
        window.$message?.success('保存成功')
        tableFormId.value = data
        return data
    } else {
        window.$message?.error('保存失败')
        tableFormId.value = ''
        return ''
    }
}

//pdf预览
const bussPdfInfo = () => {
    const { id } = treeItem.value
    // getBussPdfInfo(id + '')
     getBussPdfInfo(pdfId.value)

}

//预览PDF请求
const getBussPdfInfo = async (pkeyId) => {
    const { error, code, data } = await firstApi.getFirstBussPdfInfo({
        firstId: pkeyId
    })
    //判断状态
    const res = isString(data)? data ?? '': ''
    if (!error && code === 200 && res) {
        window.open(res,'_blank')
    }
}

//上报审批
const reportIds = ref('')
const showReportModal = ref(false)
const reportTaskName = ref('')
const reportAddition = ref({})
const reportLoading = ref(false)
const reportTypeData = ref('')
const reportDatas = ref([])
const isReportModalDatas = ref(false)
const iscanReport=ref(false)
//上报方法封装
const toreportModalClick = async (type) => {
    if(type){
            const { primaryKeyId, contractIdRelation } = treeItem.value
            let rows = [];
            //处理获取流程的条件
            if (tabTypeKey.value === 'mark') {
                reportTypeData.value = tableFormId.value
                isReportModalDatas.value = false
                rows = tableFileData.value
            } else {
                isReportModalDatas.value = true
                rows = tableSelectionKeys.value
            }
            if (rows.length > 0) {
                reportLoading.value = true
                const taskCheck = await eVisaTaskCheckApi({
                    projectId: projectId.value,
                    contractId: contractId.value
                })
                if (taskCheck) {
                    if (tabTypeKey.value === 'mark') {
                        reportIds.value = tableFormId.value
                        const { data } = await firstApi.queryFirstDocumentTitle({
                            projectId: projectId.value,
                            contractId: contractId.value,
                            queryId: tableFormId.value
                        })
                        reportTaskName.value = isString(data) ? data ?? '' : ''
                    } else {
                        reportIds.value = rowsToId(rows)
                        //设置任务数据
                        let reportDataArr = []
                        rows.forEach(item => {
                            reportDataArr.push({
                                id: item?.id,
                                name: item?.name
                            })
                        })
                        reportDatas.value = reportDataArr
                        //其他数据
                        reportTypeData.value = rows[0]['id']
                        reportTaskName.value = rows.length > 1?`${rows[0].name}等${rows.length}个文件`:rows[0].name
                    }
                    reportLoading.value = false
                    //附加数据
                    reportAddition.value = {
                        classify: 1,
                        isFirst: 1,
                        primaryKeyId: primaryKeyId,
                        contractIdRelation: contractIdRelation ?? contractId.value,
                    }
                    showReportModal.value = true
                } else {
                    reportLoading.value = false
                }
            } else {
                window.$message?.warning('暂无相关数据')
            }
        }else{
             window.$message?.warning('当前工序资料还未审批，待审批完成才能进行首件模板上报')

        }
}
const reportModalClick = async (type) => {
    if(type===2){
         console.log('上报')
        iscanReport.value=isCanreport.value;
        toreportModalClick(iscanReport.value)

    }

    else{
         const rows = deepClone(tableSelectionKeys.value)
         let result=false
            console.log('上报审批',rows)
        //判断自身是否满足条件
         const result1 = rows.every(({taskStatusStr})=> {
            return taskStatusStr === '未上报'||taskStatusStr === '已废除'
        })
        if(result1){
             //判断工序节点是否满足条件
             result = rows.every(({isApprove})=> {
                return isApprove === true
            })
             iscanReport.value=result
              toreportModalClick(iscanReport.value)
        }else{
              window.$message?.warning('已上报的数据不能重复上报')
               iscanReport.value=false
        }



    }

}

//上报的审批内容移除
const reportTaskTagClose = (index) => {
    const row = tableSelectionKeys.value[index];
    tableListRef.value?.toggleRowSelection(row,false)
}
const getTableDataAll = () => {
    getTableData()
    firstTaskStatus()
    queryNodeStatus()
}
//上报完成
const showReportFinish = () => {
    showReportModal.value = false
    getTableDataAll()
}

//打印
const printLoading = ref(false)
const batchPrint = async () => {
    const rows = tableSelectionKeys.value;
    const ids = rowsToId(rows)
    //批量下载
    printLoading.value = true
    const { error, code, data } = await firstApi.batchPrint({
        ids: ids
    })
    //处理数据
    printLoading.value = false
    //判断状态
    const res = isString(data)? data ?? '': ''
    if (!error && code === 200 && res) {
        window.open(res,'_blank')
    }
}

//废除
const batchAbolishClick = () => {
    const rows = tableSelectionKeys.value;
    //判断是否满足条件
    const result = rows.every(({status})=> {
        return status !== 0 && status !== 3
    })
    //判断状态
    if (result) {
        //拼接ID
        const ids = rowsToId(rows)
        window?.$messageBox?.alert('是否废除勾选的已上报文件？', '废除文件', {
            showCancelButton: true,
            confirmButtonText: '确定废除',
            cancelButtonText: '取消',
            callback: (action) => {
                if (action === 'confirm') {
                    batchAbolishSave(ids)
                }
            }
        })
    } else {
        window.$message?.warning('未上报的文件不能废除')
    }
}
//废除勾选的已上报文件
const batchAbolishSave = async (ids) => {
    const { error, code } = await queryApi.batchAbolish({ids: ids})
    //处理数据
    if (!error && code === 200) {
        window.$message?.success('批量废除成功')
        tableSelectionKeys.value = []
        getTableData()
    }
}

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

//处理数据
const rowsToArr = (rows) => {
    let newArr = [];
    for (let i = 0; i < rows.length; i++) {
        newArr.push({
            id: rows[i]?.id,
            name: rows[i]?.name
        })
    }
    return newArr
}

//左右拖动，改变树形结构宽度
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/first-item.scss";
</style>

<style lang="scss">
.hc-first-item-node-layout.el-overlay {
    position: absolute;
    background-color: transparent;
    margin: -24px;
    height: revert;
    .hc-drawer-box.el-drawer {
        --el-drawer-bg-color: transparent;
        .el-drawer__body {
            padding: 24px;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }
    }
}
</style>
