<template>
    <HcNewCard>
        <template #header>
            <div class="absolute inset-0" style="height: 32px; top: -14px">
                <div class="relative w-full ">
                    <el-scrollbar>
                        <div class="relative whitespace-nowrap">
                            <div class="w-32 inline-block">
                                <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="w-32 ml-2  inline-block">
                                <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="w-32 ml-2  inline-block">
                                <el-select v-model="searchInternalForm.reportNumber" clearable placeholder="上报批次">
                                    <el-option v-for="item in InternalReportBatch" :key="item" :label="item" :value="item" />
                                </el-select>
                            </div>
                            <div class="w-32 ml-2  inline-block">
                                <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="w-60 ml-2  inline-block">
                                <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>
                    </el-scrollbar>
                </div>
            </div>
        </template>
        <template #extra>
            <HcTooltip 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 keys="write_industry_print">
                <el-button :disabled="tableInternalKeys.length <= 0" :loading="printLoading" hc-btn @click="batchPrint">
                    <HcIcon name="printer" />
                    <span>打印</span>
                </el-button>
            </HcTooltip>
        </template>
        <HcTable
            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 :pages="searchInternalForm" @change="pageInternalChange" />
        </template>
    </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'

//参数
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
    setQueryData(treeData)
})

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

//获取相关数据
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 InternalReportBatch = ref([
    //  {label: "1", value: 1},
    //  {label: "2", value: 2},
    //  {label: "3", value: 3},
])

//获取上报批次

const queryBatchList = async () => {

    if (contractId.value) {
        // const { error, code, data } = await internalApi.queryBatchList({
        //     projectId: projectId.value,
        //     contractId: contractId.value || ''
        // })
        const { error, code, data } = await queryApi.getReportNumber({
            projectId: projectId.value,
            contractId: contractId.value || '',
            type: 1,
        })
        if (!error && code === 200) {
            InternalReportBatch.value = getArrValue(data)
        } else {
            InternalReportBatch.value = []
        }
    } else {
        InternalReportBatch.value = []
    }
}
//是否关联试验
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
        getTableInternalData()

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

//分页被点击
const pageInternalChange = ({ current, size }) => {
    searchInternalForm.value.current = current
    searchInternalForm.value.size = size
    getTableInternalData()
}

//内业台账表头
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: 'reportNumber', name: '上报批次', width: 100, 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 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 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) {
        window.open(res, '_blank')
    }
}
</script>
