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

        <!-- 上报首件 -->
        <HcDrawer
            :is-card="false" :show="isFirstReportDrawer" to-id="first-item-node-layout-target"
            uis="hc-first-item-node-layout" @close="FirstReportDrawerClose"
        >
            <div class="node-content">
                <div class="node-form">
                    <el-scrollbar v-if="contractId && isTableForm" ref="ListItemScrollRef">
                        <!-- <div class="hc-excel-table-form-view" :id="`table-form-${contractId}`"></div> -->
                        <ListItem
                            ref="ListItemsRef"
                            :classify="authBtnTabKey"
                            :contract-id="contractId"
                            :datas="ListItemDatas"
                            :draw-type="isDrawType"
                            :finish-file="finishFile"
                            :project-info="projectInfo"
                            :status="NodeStatus"
                            :table-file-data="tableFileData"
                            :tree-item="treeItem"
                            @offset-top="ListItemOffsetTop"
                            @renew="renewtable"
                        />
                    </el-scrollbar>
                    <HcStatus v-else :desc="statusDesc" />
                </div>
                <div class="node-file">
                    <div class="title">上传总结报告1111</div>
                    <div v-if="contractId && isTableForm" class="node-upload-box">
                        <HcUpload :file-list="fileListData" :pkey-id="pkeyIds" @finish="uploadChange" />
                    </div>
                    <div v-else class="node-upload-box">
                        <el-alert :closable="false" show-icon title="表单异常，暂时无法使用上传" type="warning" />
                    </div>
                    <el-divider border-style="dashed" />
                    <div class="title">文件附件</div>
                    <div class="hc-table-node-file-box">
                        <HcTable :column="tableFileColumn" :datas="tableFileData" :is-index="false" is-new>
                            <template #action="{ row, index }">
                                <el-button plain size="small" type="danger" @click="tableDelButton(index)">
                                    删除
                                </el-button>
                            </template>
                        </HcTable>
                    </div>
                </div>
            </div>
            <div class="node-action">
                <el-button
                    :disabled="!contractId || !isTableForm || NodeStatus === '3'" :loading="tableFormSaveLoading"
                    hc-btn
                    type="primary" @click="saveBussData"
                >
                    <HcIcon name="save" />
                    <span>保存</span>
                </el-button>
                <el-button
                    :disabled="!contractId || !isTableForm || !tableFormId || NodeStatus === '1'" hc-btn
                    @click="bussPdfInfo"
                >
                    <HcIcon name="eye" />
                    <span>预览</span>
                </el-button>
                <el-button
                    :disabled="!contractId || !isTableForm || !tableFormId || NodeStatus === '3' || NodeStatus === '1'"
                    :loading="reportLoading"
                    hc-btn @click="reportModalClick(2)"
                >
                    <HcIcon name="send-plane-2" />
                    <span>上报</span>
                </el-button>
                <el-button hc-btn @click="FirstReportDrawerClose">
                    <HcIcon name="close" />
                    <span>返回</span>
                </el-button>
            </div>
        </HcDrawer>

        <!-- 上报审批 -->
        <HcReportModal
            :contract-id="contractId"
            :datas="reportDatas"
            :ids="reportIds"
            :is-datas="isReportModalDatas"
            :project-id="projectId"
            :show="showReportModal"
            :task-name="reportTaskName"
            :type-data="reportTypeData"
            title="上报审批"
            type="first"
            url="informationWriteQuery/batchTask"
            @finish="showReportFinish"
            @hide="showReportModal = false"
            @tag-close="reportTaskTagClose"
        />
    </div>
</template>

<script setup>
import { useAppStore } from '~src/store'
import { nextTick, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import WbsTree from './components/WbsTree.vue'
import HcUpload from './components/HcUpload.vue'
import HTableForm from '~src/plugins/HTableForm'
import { eVisaTaskCheckApi, getReportNumber } from '~api/other'
import firstApi from '~api/other/first-item'
import tasksApi from '~api/tasks/data'
import { getStoreValue, setStoreValue } from '~src/utils/storage'
import { arrToId, deepClone, getArrValue, getObjVal, getObjValue, isString } from 'js-fast-way'
import queryApi from '~api/data-fill/query'
import wbsApi from '~api/data-fill/wbs'
import ListItem from './components/ListItem.vue'
import { delMessageV2 } from '~com/message/index.js'
//变量
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(getStoreValue('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 renewtable = () => {
    getTableData()
    queryNodeStatus()
}
//项目树被点击
const treeItem = ref({})
const nodeWbsElTreeClick = ({ data, keys }) => {
    treeItem.value = data
    searchForm.value.contractIdRelation = data['contractIdRelation']
    searchForm.value.wbsId = data['primaryKeyId']
    //缓存自动展开
    TreeAutoExpandKeys.value = keys
    setStoreValue('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 { 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.queryNodeStatus({
        // primaryKeyId: info['contractIdRelation'] ? info['id'] : info['primaryKeyId'],
        // classify: 1
        primaryKeyId: authBtnTabKey.value == 1 ? info['id'] : info['primaryKeyId'],
        classify: authBtnTabKey.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({
        contractId: contractId.value,
        projectId: projectId.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 ListItemsRef = ref(null)
//是否是抽屉
const isDrawType = ref(false)
//设置滚动条位置
const ListItemScrollRef = ref(null)
const ListItemOffsetTop = (offsetTop) => {
    if (offsetTop > 0) {
        setTimeout(() => {
            ListItemScrollRef.value?.setScrollTop(offsetTop)
        }, 350)
    } else {
        ListItemScrollRef.value?.setScrollTop(offsetTop)
    }
}
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 ListItemDatas = ref([])
//上报首件
const isFirstReportDrawer = ref(false)
const isCanreport = ref(false)
const firstReportClick = () => {
    const rows = deepClone(tableSelectionKeys.value)
    console.log(rows, 'rows')
    nextTick(() => {
        ListItemDatas.value = rows

    })
    console.log(ListItemDatas.value, ' ListItemDatas.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
    // getTableData()
    queryNodeStatus()
    tableFileData.value = rows
    getFirstExcelHtml()
}
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 (getObjVal(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) {
        delMessageV2(async (action, instance, done) => {
            if (action === 'confirm') {
                instance.confirmButtonLoading = true
                tableFileData.value.splice(index, 1)
                instance.confirmButtonLoading = false
                done()
            } else {
                done()
            }
        })
    } 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
        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 = arrToId(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()
}
//上报完成
const showReportFinish = () => {
    showReportModal.value = false
    getTableDataAll()
}

//打印
const printLoading = ref(false)
const batchPrint = async () => {
    const rows = tableSelectionKeys.value
    const ids = arrToId(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 = arrToId(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, projectId:projectId.value, contractId:contractId.value })
    //处理数据
    if (!error && code === 200) {
        window.$message?.success('批量废除成功')
        tableSelectionKeys.value = []
        getTableData()
    }
}

//处理数据
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>
