<template>
    <hc-new-card scrollbar>
        <template #header>
            <HcTooltip keys="file_collection_btn_upload_scanned_files"> <el-checkbox v-model="checkedval" label="全选" size="large" @change="clickAll" /> </HcTooltip>
        </template>
        <template #extra>
            <!-- <HcNewSwitch :datas="tabData" :keys="tabKey" :round="false" @change="tabChange" /> -->
            <el-button hc-btn color="#626aef">
                <HcIcon name="eye" />
                <span>历史验收报告</span>
            </el-button>
            <el-button hc-btn class=" m-1" type="warning">
                <HcIcon name="eye" />
                <span>历史整改报告</span>
            </el-button>
            <HcTooltip keys="file_collection_btn_upload_scanned_files">
                <el-button v-if="!showBtn" type="primary" hc-btn @click="reportModalClick">
                    <HcIcon name="git-pull-request" />
                    <span>申请验收</span>
                </el-button>
                <el-button v-else type="primary" hc-btn @click="cancelClick">
                    <HcIcon name="git-pull-request" />
                    <span>撤回验收申请</span>
                </el-button>
            </HcTooltip>
        </template>
        <div v-loading="totalLoaing" class="h-screen">
            <div v-for="(item, index) in totalData" :key="item.unitInfo">
                <div class="hc-card-table-title">{{ item.unitInfo }}</div>
                <template v-for="(item1, index1) in item.nodeLists" :key="item1.nodeInfo">
                    <HcCardItem v-if="item1.list && item1.list.length > 0" ui="h-half">
                        <template #header>
                            <!-- <el-checkbox v-model="item1.checkedval" label="全选" size="large" @change="clickAll($event, index)" />  -->
                            <span>{{ item1.nodeInfo }}</span>
                           
                            <!-- <span class="text-gray">（238卷）</span> -->
                        </template>
                        <div :style="`height: ${item1.list !== null && item1.list.length > 9 ? '300px' : 'auto'};`">
                            <visualTable ref="visuatable" :table-data="item1.list " :index-num="index" @getTableKeys="getTableKeys($event, index1)" />
                        </div>
                    </HcCardItem>
                </template>
            </div>
        </div>
    </hc-new-card>

    <!-- 批量上报审批 -->
    <HcReportModal
        title="申请验收"
        widths="1080px"
        url="archivesauto/saveApply"
        :show="showReportModal"
        :project-id="projectId"
        :contract-id="contractId"
        :task-name="reportTaskName"
        :ids="reportIds"
        is-datas
        :datas="reportDatas"
        @hide="hidereport"
        @finish="showReportFinish"
        @tagClose="reportTaskTagClose"
    />
</template>

<script setup>
import { nextTick, onMounted, ref, watch } from 'vue'
import { getArrValue, getObjValue } from 'js-fast-way'
import { rowsToId } from '~uti/tools'
import initialgApi from '~api/initial/initial'
import visualTable from './visual-table.vue'
//参数
const props = defineProps({
    projectId: {
        type: [String, Number],
        default: '',
    },
    contractId: {
        type: [String, Number],
        default: '',
    },
    treeData: {
        type: Object,
        default: () => ({}),
    },
})

//变量
const projectId = ref(props.projectId)
const contractId = ref(props.contractId)
const nodeData = ref(props.treeData)

//监听
watch(() => [
    props.treeData,
], ([treeData]) => {
    nodeData.value = treeData
})

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

    getBtnstatus()
    getTotalData()
})
//查看验收申请状态
const showBtn = ref(true)
const getBtnstatus = async ()=>{
    const { error, code, data } = await initialgApi.getApplyStatus({
        projectId: projectId.value,
    })
    if (!error && code === 200) {
        console.log(data, 'data')
        showBtn.value = data
    } else {
        showBtn.value = true
     
    }
}
const totalData = ref([])
const totalTabledata = ref([])
const totalLoaing = ref(false)
const getTotalData = async ()=>{
    totalLoaing.value = true
    const { error, code, data } = await initialgApi.getAllUnitArchivesView({
        projectId: projectId.value,
    })
    totalLoaing.value = false
    if (!error && code === 200) {
        console.log(data, 'data')
        totalData.value = getArrValue(data)
        getTotalTabledata(totalData.value)
    } else {
        totalData.value = []
     
    }
}
const getTotalTabledata = (data)=>{
    totalTabledata.value = []
    data.forEach((ele)=>{
       ele.nodeLists.forEach((ele1)=>{
        if (ele1.list !== null) {
            ele1?.list.forEach((ele2)=>{
                totalTabledata.value.push(ele2)
            })
        }
            
       })
    })
}



//------立项审批











//上报
const tableKeys = ref([])
const reprotTitle = ref(new Map())
const getTableKeys = (val, index)=>{
    let arr = []
    reprotTitle.value.set(index, val)
    for (const value of reprotTitle.value.values()) {
        console.log(value)
        value.forEach((ele)=>{
            arr.push(ele)
        })
     }
     tableKeys.value = arr

}
const checkedval = ref(false)
const clickAll = (val)=>{
    if (val) {
        tableKeys.value = totalTabledata.value
    } else {
        tableKeys.value = []
    }
    // visuatable.value[index].tableSelectAll(val)
}
const reportIds = ref('')
const reportTaskName = ref('')
const reportDatas = ref([])
const showReportModal = ref(false)
const reportLoading = ref(false)
const reportModalClick = async () => {

    const rows = tableKeys.value
    console.log(rows, 'rows验收申请行')
    if (rows.length > 0) {
        //初始ID
        const row = getObjValue(rows[0])
        reportIds.value = rowsToId(rows)
        //设置任务数据
        let reportDataArr = []
        rows.forEach(item => {
            reportDataArr.push({
                id: item?.id,
                name: item?.name,
            })
        })
        reportDatas.value = reportDataArr
        //设置任务名称
        reportTaskName.value = rows.length > 1 ? `${row.name}等${rows.length}个文件` : row.name
        reportLoading.value = false
        showReportModal.value = true
    } else {
        window.$message?.warning('请先勾选需要申请验收的数据')
    }
}
const hidereport = ()=>{
    showReportModal.value = false
    checkedval.value = false
    visuatable.value.forEach((ele, index)=>{
        visuatable.value[index]?.clearSelection()
    })
}
const visuatable = ref(null)
//上报的审批内容移除
const reportTaskTagClose = (index) => {
    // const row = tableKeys.value[index]
    console.log(visuatable.value[0])
    tableKeys.value.splice(index, 1)
  
    // // tableRef.value?.toggleRowSelection(row, false)
    // console.log(visuatable.value[index], '1111')
}

//上报完成
const showReportFinish = async () => {
    showReportModal.value = false
    tableKeys.value = []
    await getBtnstatus()
    getTotalData()
}
//撤回验收申请
const cancelClick = ()=>{
    window?.$messageBox?.alert('确认撤销? 撤销之后专家账号也一并清空删除', '提示', {
        showCancelButton: true,
        confirmButtonText: '确认撤销',
        cancelButtonText: '取消',
        callback: async (action, ctx ) => {
            if (action === 'confirm') {
                ctx.confirmButtonLoading = true
                const { code, msg, error } = await initialgApi.annulApply({
                    projectId:projectId.value,
                })
                ctx.confirmButtonLoading = true
                if (!error && code === 200) {
                    window.$message?.success(msg)
                    getBtnstatus()
                    getTotalData()
                  
                }
            }
        },
    })
}
</script>

<style lang="scss" scoped>
@import '~style/transfer/scoped/initial.scss';
</style>
