<template>
    <div class="app-container app-container-bg">
        <el-card class="first-card" ref='firstCard' shadow="always">
            <el-form :model="queryParams" ref="queryForm" :inline="true" @submit.native.prevent>
                <el-form-item label="选择站点">
                    <ESelectSingle ref="eSelectSingle" :stationType="stationType" @stationChange="handleStationChange" @loadingChange="handleStationLoading" />
                </el-form-item>
                <el-form-item label="年份">
                    <el-date-picker v-model="queryParams.year" type="year" value-format="YYYY" placeholder="选择年" :clearable="false">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                    <el-button type="warning" icon="Download" @click="handleExport">下载</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <div class="el-card-p card-shadow carder-border mt10 pad10" style="max-width: 100%; overflow-x: hidden;padding-top:0" v-loading="loading">
            <div class="main-table-header sticky-header">
                <div class="table-title">
                    <span class="pr10" v-if="selectStnm!==''">{{selectStnm}}</span>
                    <span>{{tableTitle}}</span>
                </div>
            </div>
            <el-empty v-if="total==0" description="暂无数据" />
            <div v-for="(item,index) in tableData" :key="index" class="mb50 main-table-header">
                <div class="table-time mb5">
                    <div>
                        <span>年份: </span><span id="title1">{{queryParams.year }}</span>
                    </div>
                    <div>
                        <span>测站编码: </span><span id="title2">{{queryParams.stnmId}}</span>
                    </div>
                    <div>
                        <span>共{{total}}页 </span><span id="title3" class="pl10">第{{index+1}}页</span>
                    </div>
                </div>
                <div style="height:100%;display: flex;">
                    <template v-for="(info,idx) in item.slice(0,5)" :key="idx">
                        <el-table class="report-table merge-header no-border-table" :data="info" style="width: 100%;" :table-layout="tableLayout">
                            <el-table-column label="日期" :align="alignment">
                                <el-table-column label="月" :align="alignment">
                                    <template #default="scope">
                                        <span v-if="scope.row.month !== getPrevRow(scope,'month','1')">
                                            {{ scope.row.month }}
                                        </span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="日" :align="alignment">
                                    <template #default="scope">
                                        <span v-if=" scope.row.day !== getPrevRow(scope,'day','2')">
                                            {{ scope.row.day }}
                                        </span>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="hourMinute2" label="时分">
                                </el-table-column>
                            </el-table-column>
                            <el-table-column prop="valueDecimal" align="right">
                                <template #header>
                                    <div style="line-height: 1.2;text-align: center;">
                                        <div>水位</div>
                                        <div>(m)</div>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                    </template>
                </div>

            </div>

        </div>

    </div>
</template>
<script setup>
    import dayjs from 'dayjs';
    import ESelectSingle from '@/components/ESelectSingle/index.vue'
    import { ref, reactive, onMounted } from 'vue';

    const props = defineProps({
        tableTitle: {
            type: String,
            default: '表格标题'
        },

    })

    const { proxy } = getCurrentInstance()
    const alignment = 'center'
    const stationType = 'C'
    const tableLayout = ref('fixed')
    const singleStationRef = ref(null)
    const selectStnm = ref('')

    const handleStationLoading = (loadingState) => {
        loading.value = loadingState;
    }
    // 新增处理站点变化的函数
    const handleStationChange = (stnmId, options, stnm) => {
        queryParams.stnmId = stnmId
        selectStnm.value = stnm
        if (stnmId == undefined) {
            proxy.$modal.msgWarning("请选择站点后查询");
            return
        } else {
            getList()
        }
    }
    const loading = ref(false);
    const tableData = ref([]);
    const queryParams = reactive({
        year: dayjs(new Date()).format('YYYY'),
        stnmId: ""
    });
    let total = ref(0)

    const getList = async () => {
        try {
            const res = await proxy.axiosGet('/report/getWaterZlData', queryParams)
            if (res.code == 0) {
                total.value = res.data.datas.length
                let data = res.data.datas
                selectStnm.value = res.data.station.stnm
                // 处理数据，每五行插入一组空数据
                const processedData = data.map(page => {
                    return page.map(table => {
                        const newTable = [];
                        for (let i = 0; i < table.length; i += 5) {
                            // 添加原始数据的5行
                            newTable.push(...table.slice(i, i + 5));
                            // 每5行后插入一组空数据（如果不是最后一批数据）
                            if (i + 5 < table.length) {
                                newTable.push({
                                    month: '',
                                    day: '',
                                    hourMinute2: '',
                                    valueDecimal: ''
                                });
                            }
                        }
                        return newTable;
                    });
                });

                tableData.value = processedData;
            }
        } catch (error) {
            console.error(error)
        } finally {
            // 确保在请求完成后隐藏loading
            loading.value = false
        }
    }

    // 优化后的获取上一行月份的方法
    const getPrevRow = (scope, field, type) => {
        const rowIndex = scope.$index;
        const data = scope.store.states.data;

        // 如果是第一行，返回null
        if (rowIndex === 0) return null;

        // 找到上一个非空行的月份
        let prevRowIndex = rowIndex - 1;
        while (prevRowIndex >= 0 && (!data.value[prevRowIndex][field] || data.value[prevRowIndex][field] === '')) {
            prevRowIndex--;
        }
        if (type == '1') {
            field = 'month'
        }
        let result = prevRowIndex >= 0 ? data.value[prevRowIndex][field] : null;
        // 如果找到有效的上一行数据，返回其月份；否则返回null
        return result
    };


    // 搜索按钮操作
    const handleQuery = () => {
        getList()
    }
    // 下载按钮操作
    const handleExport = () => { }
    onMounted(() => { })
</script>
<style scoped lang="scss">
    .no-border-table :deep(.el-table__body-wrapper .el-table__cell) {
        border-bottom: 0 !important;
    }

    .no-border-table :deep(.el-table__body-wrapper .el-table__cell) {
        padding: 2px 0 !important;
    }

    .no-border-table :deep(.el-table__body-wrapper .el-table__row:nth-child(6n) .el-table__cell) {
        padding: 10px 0 !important;
        background-color: #f9f9f9;
    }
</style>