<template>
    <HcCard>
        <template #header>
            <div class="w-32">
                <el-select v-model="searchInternalForm.taskStatus" placeholder="审批状态" clearable size="large">
                    <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">
                <el-select v-model="searchInternalForm.isEvaluate" placeholder="是否评定" clearable size="large">
                    <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">
                <el-select v-model="searchInternalForm.reportNumber" placeholder="上报批次" clearable size="large">
                    <el-option v-for="item in InternalReportBatch" :key="item" :label="item" :value="item"/>
                </el-select>
            </div>
            <div class="w-32 ml-2">
                <el-select v-model="searchInternalForm.isExperiment" placeholder="关联试验" clearable size="large">
                    <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">
                <el-input v-model="searchInternalForm.queryStr" placeholder="请输入名称关键词检索" size="large" clearable @keyup="searchInternalKeyUp"/>
            </div>
            <div class="ml-2">
                <el-button type="primary" size="large" @click="searchInternalClick">
                    <HcIcon name="search-2"/>
                    <span>搜索</span>
                </el-button>
            </div>
        </template>
        <template #extra>
            <HcTooltip keys="write_industry_download">
                <el-button type="primary" hc-btn :disabled="tableInternalKeys.length <= 0"  @click="batchDownload"  :loading="downloadLoading">
                    <HcIcon name="download"/>
                    <span>下载</span>
                </el-button>
            </HcTooltip>
            <HcTooltip keys="write_industry_print">
                <el-button hc-btn :disabled="tableInternalKeys.length <= 0" :loading="printLoading" @click="batchPrint">
                    <HcIcon name="printer"/>
                    <span>打印</span>
                </el-button>
            </HcTooltip>
        </template>
        <HcTable ref="tableInternalRef" :column="tableInternalColumn" :datas="tableInternalData" :loading="tableInternalLoading" isCheck @selection-change="tableInternalSelection">
            <template #taskStatus="{row}">
                <el-tag type="success" class="mx-1" effect="dark" v-if="row['taskStatus'] === '已审批'">已审批</el-tag>
                <el-tag type="danger" class="mx-1" effect="dark" v-if="row['taskStatus'] === '待审批'">待审批</el-tag>
                <el-tag type="warning" class="mx-1" effect="dark" v-if="row['taskStatus'] === '未上报'">未上报</el-tag>
            </template>
            <template #isEvaluate="{row}">
                <el-tag type="success" class="mx-1" effect="dark" v-if="row['isEvaluate']">是</el-tag>
                <el-tag type="info" class="mx-1" effect="dark" v-else>否</el-tag>
            </template>
            
            <template #reportNumber="{row}">
              {{row['reportNumber']==='-1'||row['reportNumber']==='0'?'':row['reportNumber']}}
            </template>
            <template #isExperiment="{row}">
                <el-tag type="success" class="mx-1" effect="dark" v-if="row['isExperiment']">是</el-tag>
                <el-tag type="info" class="mx-1" effect="dark" v-else>否</el-tag>
            </template>
        </HcTable>
        <template #action>
            <HcPages :pages="searchInternalForm" @change="pageInternalChange"/>
        </template>
    </HcCard>
</template>

<script setup>
import {ref, nextTick, watch} from "vue";
import {getArrValue,isType, downloadBlob, isString} from "vue-utils-plus"
import internalApi from '~api/ledger/internal';
import queryApi from '~api/data-fill/query';

//参数
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??'') !== '';
    })
}
//拼接ID
const rowsToId = (rows) => {
    return rows.map((obj) => {
        return obj.id;
    }).join(",")
}
//下载
const downloadLoading = ref(false)
const batchDownload = async () => {
    const rows = tableInternalKeys.value;
    console.log(rows,'rows');
    const ids = rowsToId(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 = rowsToId(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>
