<template>
    <HcNewCard>
        <template #header>
            <div class="absolute inset-0" style="height: 32px; top: -14px">
                <div class="relative w-full">
                    <el-scrollbar>
                        <div v-if="!isWaterProject" class="relative whitespace-nowrap">
                            <!-- <div class="inline-block w-32">
                                <el-select v-model="searchInternalForm.taskStatus" clearable placeholder="审批状态">
                                    <el-option v-for="item in InternalApproval" :key="item.value" :label="item.label" :value="item.value" />
                                </el-select>
                            </div> -->
                            <div class="inline-block w-32">
                                <el-select v-model="searchInternalForm.isEvaluate" clearable placeholder="是否评定">
                                    <el-option v-for="item in InternalAssess" :key="item.value" :label="item.label" :value="item.value" />
                                </el-select>
                            </div>
                         
                            <div class="ml-2 inline-block w-32">
                                <el-select v-model="searchInternalForm.isExperiment" clearable placeholder="关联试验">
                                    <el-option v-for="item in InternalAssociation" :key="item.value" :label="item.label" :value="item.value" />
                                </el-select>
                            </div>
                            <div class="ml-2 inline-block w-60">
                                <el-input v-model="searchInternalForm.queryStr" clearable placeholder="请输入名称关键词检索" @keyup="searchInternalKeyUp" />
                            </div>
                            <div class="ml-2 inline-block">
                                <el-button type="primary" @click="searchInternalClick">
                                    <HcIcon name="search-2" />
                                    <span>搜索</span>
                                </el-button>
                            </div>
                        </div>
                        <div v-else class="relative whitespace-nowrap">
                            <div class="inline-block w-64">
                                <el-select v-model="searchWaterForm.type" clearable placeholder="审批状态">
                                    <el-option label="汇总统计" :value="1" />
                                    <el-option label="详细统计" :value="2" />
                                </el-select>
                                <el-button type="primary" @click="getTableWaterData">
                                    <HcIcon name="search-2" />
                                    <span>搜索</span>
                                </el-button>
                            </div>
                        </div>
                    </el-scrollbar>
                </div>
            </div>
        </template>
        <template #extra>
            <HcTooltip v-if="!isWaterProject" keys="write_industry_download">
                <el-button :disabled="tableInternalKeys.length <= 0" :loading="downloadLoading" hc-btn type="primary" @click="batchDownload">
                    <HcIcon name="download" />
                    <span>下载</span>
                </el-button>
            </HcTooltip>
            <HcTooltip v-if="isWaterProject" keys="write_industry_download">
                <el-button :disabled="tableWaterKeys.length <= 0" :loading="waterDownloadLoading" hc-btn type="primary" @click="waterBatchDownload">
                    <HcIcon name="download" />
                    <span>下载</span>
                </el-button>
            </HcTooltip>
        </template>
        <HcTable
            v-if="!isWaterProject" ref="tableInternalRef" :column="tableInternalColumn" :datas="tableInternalData"
            :loading="tableInternalLoading" is-new :index-style="{ width: 60 }" is-check
            :check-style="{ width: 29 }"
            @selection-change="tableInternalSelection"
        >
            <template #taskStatus="{ row }">
                <el-tag v-if="row.taskStatus === '已审批'" class="mx-1" effect="dark" type="success">已审批</el-tag>
                <el-tag v-if="row.taskStatus === '待审批'" class="mx-1" effect="dark" type="danger">待审批</el-tag>
                <el-tag v-if="row.taskStatus === '未上报'" class="mx-1" effect="dark" type="warning">未上报</el-tag>
            </template>
            <template #isEvaluate="{ row }">
                <el-tag v-if="row.isEvaluate" class="mx-1" effect="dark" type="success">是</el-tag>
                <el-tag v-else class="mx-1" effect="dark" type="info">否</el-tag>
            </template>
            <template #reportNumber="{ row }">
                {{ row.reportNumber === '-1' || row.reportNumber === '0' ? '' : row.reportNumber }}
            </template>
            <template #isExperiment="{ row }">
                <el-tag v-if="row.isExperiment" class="mx-1" effect="dark" type="success">是</el-tag>
                <el-tag v-else class="mx-1" effect="dark" type="info">否</el-tag>
            </template>
        </HcTable>
        <template #action>
            <HcPages v-if="!isWaterProject" :pages="searchInternalForm" @change="pageInternalChange" />
            <!-- <HcPages v-if="isWaterProject" :pages="searchWaterForm" @change="pageWaterChange" /> -->
        </template>

        <HcTable
            v-if="isWaterProject" :column="tableWaterColumn" :datas="tableWaterData"
            :loading="tableWaterLoading" is-new :index-style="{ width: 60 }" is-check @selection-change="tableWaterSelection"
        />
    </HcNewCard>
</template>

<script setup>
import { nextTick, ref, watch } from 'vue'
import internalApi from '~api/ledger/internal'
import queryApi from '~api/data-fill/query'
import { arrToId, downloadBlob, getArrValue, isString } from 'js-fast-way'
import { toPdfPage } from '~uti/btn-auth'

//参数
const props = defineProps({
    projectId: {
        type: [String, Number],
        default: '',
    },
    contractId: {
        type: [String, Number],
        default: '',
    },
    treeData: {
        type: Object,
        default: () => ({}),
    },
    isWaterProject: {
        type: Boolean,
        default: false,
    },
})

//变量
const projectId = ref(props.projectId)
const contractId = ref(props.contractId)
const nodeData = ref(props.treeData)
const isWaterProject = ref(props.isWaterProject)
const searchWaterForm = ref({
    type:1,
 
})
const tableWaterColumn = ref([
{ key: 'className', name: '单位工程' },
    { key: 'partName', name: '分部工程' },
    { key: 'subPartName', name: '子分部工程' },
    { key: 'unitName', name: '单元工程' },
    { key: 'unitCount', name: '单元工程个数' },
    { key: 'passCount', name: '合格个数' },
    { key: 'goodCount', name: '其中优良个数' }, 
     { key: 'goodRate', name: '优良率(%)' },
  
])

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

//渲染完成
nextTick(() => {
    setQueryData(props.treeData)
 
})

//获取相关数据
const setQueryData = (data) => {
    const cid = data?.contractIdRelation || ''
    const wbsId = data['contractIdRelation'] ? data['id'] : data['primaryKeyId']
    if (wbsId) {
        searchInternalForm.value.contractId = cid ? cid : contractId.value
        searchInternalForm.value.contractIdRelation = data['contractIdRelation']
        searchInternalForm.value.wbsIds = [wbsId]
        searchInternalClick()
    }
}

//审批状态
const InternalApproval = ref([
    { label: '未上报', value: '0' },
    { label: '待审批', value: '1' },
    { label: '已审批', value: '2' },
])
//是否评定
const InternalAssess = ref([
    { label: '是', value: true },
    { label: '否', value: false },
])




//是否关联试验
const InternalAssociation = ref([
    { label: '是', value: true },
    { label: '否', value: false },
])

//搜索表单
const searchInternalForm = ref({
    taskStatus: null, isEvaluate: null, reportNumber: null, isExperiment: null,
    current: 1, size: 20, total: 0,
})

//回车
const searchInternalKeyUp = (e) => {
    if (e.key === 'Enter') {
        searchInternalClick()
    }
}

//搜索
const searchInternalClick = () => {
    if (searchInternalForm.value?.wbsIds) {
        searchInternalForm.value.current = 1
        if (isWaterProject.value) {
            getTableWaterData()
        } else {
            getTableInternalData()
        }
        

    } else {
        window?.$message?.warning('请先选择一个树节点')
    }
}

//分页被点击
const pageInternalChange = ({ current, size }) => {
    searchInternalForm.value.current = current
    searchInternalForm.value.size = size
    getTableInternalData()
}
// const pageWaterChange = ({ current, size }) => {
//     searchWaterForm.value.current = current
//     searchWaterForm.value.size = size
//     getTableWaterData()
// }
//获取水利水电工程台账

//内业台账表头
const tableInternalRef = ref(null)
const tableInternalColumn = ref([
    { key: 'unitProject', name: '单位工程' },
    { key: 'partProject', name: '分部工程' },
    { key: 'partChildProject', name: '子分部工程' },
    { key: 'subentryProject', name: '分项工程' },
    { key: 'subentryChildProject', name: '子分项工程' },
    { key: 'process', name: '工序' },
    { key: 'taskStatus', name: '审批状态', width: 120, align: 'center' },
    { key: 'isEvaluate', name: '是否评定', width: 100, align: 'center' },
    { key: 'isExperiment', name: '关联试验', width: 100, align: 'center' },
])
const tableInternalData = ref([])

//获取数据
const tableInternalLoading = ref(false)
const getTableInternalData = async () => {
    tableInternalLoading.value = true
    const { error, code, data } = await internalApi.queryInternalPage({
        ...searchInternalForm.value,
        projectId: projectId.value,
    })
    //判断状态
    tableInternalLoading.value = false
    if (!error && code === 200) {
        tableInternalData.value = getArrValue(data['records'])
        searchInternalForm.value.total = data['total'] || 0
    } else {
        tableInternalData.value = []
        searchInternalForm.value.total = 0
    }
}

//获取数据
const tableWaterData = ref([])
const tableWaterLoading = ref(false)
const getTableWaterData = async () => {
    tableWaterLoading.value = true
    const { error, code, data } = await internalApi.queryCurrentNodeNeiYeLedger1({
        ...searchWaterForm.value,
        projectId: projectId.value,
        pkeyId: nodeData.value['primaryKeyId'],
       
    })
    //判断状态
    tableWaterLoading.value = false
    if (!error && code === 200) {
        tableWaterData.value = getArrValue(data)
 
    } else {
        tableWaterData.value = []
  
    }
}

//多选
const tableInternalKeys = ref([])
const tableInternalSelection = (rows) => {
    tableInternalKeys.value = rows.filter((item) => {
        return (item ?? '') !== ''
    })
}

//下载
const downloadLoading = ref(false)
const batchDownload = async () => {
    const rows = tableInternalKeys.value
    console.log(rows, 'rows')
    const ids = arrToId(rows)
    //批量下载
    downloadLoading.value = true
    const { error, disposition, res } = await queryApi.batchDownloadFileToZip({ ids: ids })
    //处理数据
    downloadLoading.value = false
    if (!error) {
        if (disposition) {
            downloadBlob(res, disposition)
        } else {
            window.$message?.error('选择的资料未生成文件')
        }
    }
}
const waterDownloadLoading = ref(false)
const tableWaterKeys = ref([])
const tableWaterSelection = (rows) => {
    tableWaterKeys.value = rows.filter((item) => {
        return (item ?? '') !== ''
    })
}

const waterBatchDownload = async () => {
    const rows = tableWaterKeys.value
  
    const ids = arrToId(rows)
    //批量下载
    waterDownloadLoading.value = true
    const { error, disposition, res } = await queryApi.downloadNeiYe({ ids: ids })
    //处理数据
    waterDownloadLoading.value = false
    if (!error) {
        if (disposition) {
            downloadBlob(res, disposition)
        } else {
            window.$message?.error('选择的资料未生成文件')
        }
    }
}
//打印
const printLoading = ref(false)
const batchPrint = async () => {
    const rows = tableInternalKeys.value
    const ids = arrToId(rows)
    //批量下载
    printLoading.value = true
    const { error, code, data } = await queryApi.batchPrint({ ids: ids })
    //处理数据
    printLoading.value = false
    const res = isString(data) ? data ?? '' : ''
    if (!error && code === 200 && res) {
        toPdfPage(res)
        //window.open(res, '_blank')
    }
}
</script>
