package org.jeecg.modules.ZyExpDataOnline.service.impl;

import org.jeecg.modules.ZyExpDataOnline.entity.BuZyExpDataOnline;
import org.jeecg.modules.ZyExpDataOnline.mapper.BuZyExpDataOnlineMapper;
import org.jeecg.modules.ZyExpDataOnline.service.IBuZyExpDataOnlineService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

/**
 * @Description: bu_zy_exp_data_online
 * @Author: jeecg-boot
 * @Date:   2025-11-25
 * @Version: V1.0
 */
@Slf4j
@Service
public class BuZyExpDataOnlineServiceImpl extends ServiceImpl<BuZyExpDataOnlineMapper, BuZyExpDataOnline> implements IBuZyExpDataOnlineService {
    
    @Override
    public IPage<BuZyExpDataOnline> queryHistoryDataByMonth(Page<BuZyExpDataOnline> page, String month) {
        // 构造历史表名
        String tableName = "bu_zy_exp_data_history_" + month;
        // 查询历史数据
        return baseMapper.queryHistoryDataByMonth(page, tableName);
    }
    
    @Override
    public IPage<BuZyExpDataOnline> queryHistoryDataByTimeRange(Page<BuZyExpDataOnline> page, String startTime, String endTime) {
        // 根据开始时间确定表名
        String month = startTime.substring(0, 7).replace("-", "");
        String tableName = "bu_zy_exp_data_history_" + month;
        // 查询历史数据
        return baseMapper.queryHistoryDataByTimeRange(page, tableName, startTime, endTime);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateById(BuZyExpDataOnline entity) {
        log.info("准备更新实体: {}", entity);
        // Use the mapper directly to ensure the update happens
        int result = baseMapper.updateById(entity);
        boolean updated = result > 0;
        log.info("更新结果: {}", updated);
        if (updated) {
            BuZyExpDataOnline updatedEntity = this.getById(entity.getId());
            log.info("更新后数据库中的数据: {}", updatedEntity);
        }
        return updated;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateHistoricalData(BuZyExpDataOnline entity, String month) {
        log.info("准备更新历史数据实体: {}, 月份: {}", entity, month);
        // 构造历史表名
        String tableName = "bu_zy_exp_data_history_" + month;
        // 使用自定义SQL更新历史数据
        boolean result = baseMapper.updateHistoricalData(entity, tableName);
        log.info("历史数据更新结果: {}", result);
        return result;
    }
}