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

import org.jeecg.modules.bu_zy_jcw.entity.BuZyJcwOnline;
import org.jeecg.modules.bu_zy_jcw.mapper.BuZyJcwOnlineMapper;
import org.jeecg.modules.bu_zy_jcw.service.IBuZyJcwOnlineService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: bu_zy_jcw_online
 * @Author: jeecg-boot
 * @Date:   2025-11-26
 * @Version: V1.0
 */
@Slf4j
@Service
public class BuZyJcwOnlineServiceImpl extends ServiceImpl<BuZyJcwOnlineMapper, BuZyJcwOnline> implements IBuZyJcwOnlineService {
	
	@Autowired
	private BuZyJcwOnlineMapper buZyJcwOnlineMapper;
	
	@Override
	public IPage<BuZyJcwOnline> queryHistoryDataByMonth(Page<BuZyJcwOnline> page, String month) {
		try {
			String tableName = "bu_zy_jcw_history_" + month;
			log.info("Querying historical data from table: {}", tableName);
			return buZyJcwOnlineMapper.queryHistoryDataByMonth(page, tableName);
		} catch (Exception e) {
			// Handle exceptions such as table doesn't exist
			log.error("Error querying historical data", e);
			throw new RuntimeException(e);
		}
	}
	
	@Override
	public IPage<BuZyJcwOnline> queryHistoryDataByCondition(Page<BuZyJcwOnline> page, String condition) {
		try {
			// 根据条件构建表名，假设表名格式为 bu_zy_jcw_history_yyyyMM
			String tableName = "bu_zy_jcw_history_" + condition.substring(0, Math.min(6, condition.length()));
			log.info("Querying historical data from table: {} with condition: {}", tableName, condition);
			
			// 调用Mapper方法进行查询
			return buZyJcwOnlineMapper.queryHistoryDataByCondition(page, tableName, condition);
		} catch (Exception e) {
			// Handle exceptions such as table doesn't exist
			log.error("Error querying historical data", e);
			throw new RuntimeException(e);
		}
	}
	
	@Override
	public IPage<BuZyJcwOnline> queryHistoryDataByTimeRange(Page<BuZyJcwOnline> page, String startTime, String endTime) {
		try {
			// 根据开始时间确定表名（这里假设按月分表）
			String month = startTime.substring(0, 7).replace("-", "");
			String tableName = "bu_zy_jcw_history_" + month;
			log.info("Querying historical data from table: {} with time range: {} to {}", tableName, startTime, endTime);
			
			// 调用Mapper方法进行查询
			return buZyJcwOnlineMapper.queryHistoryDataByTimeRange(page, tableName, startTime, endTime);
		} catch (Exception e) {
			// Handle exceptions such as table doesn't exist
			log.error("Error querying historical data by time range", e);
			throw new RuntimeException(e);
		}
	}
	
	@Override
	public boolean updateHistoricalData(BuZyJcwOnline buZyJcwOnline, String month) {
		try {
			// Log the length of data fields before validation
			logDataFieldLengths(buZyJcwOnline);
			
			// Validate data lengths before attempting update
			validateDataLengths(buZyJcwOnline);
			
			String tableName = "bu_zy_jcw_history_" + month;
			log.info("Attempting to update historical data for ID: {} in table: {}", buZyJcwOnline.getId(), tableName);
			log.info("Data to update: {}", buZyJcwOnline);
			
			// The update method returns the number of affected rows
			// We need to check if any rows were affected to determine success
			int rowsAffected = buZyJcwOnlineMapper.updateHistoricalData(buZyJcwOnline, tableName);
			
			log.info("Rows affected: {}", rowsAffected);
			
			return rowsAffected > 0;
		} catch (Exception e) {
			log.error("Error updating historical data", e);
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * Log the length of data fields for debugging purposes
	 * @param entity The entity to log
	 */
	private void logDataFieldLengths(BuZyJcwOnline entity) {
		log.info("Data field lengths - data1: {}, data2: {}, data3: {}, data4: {}, data5: {}, data6: {}, data7: {}, data8: {}, data9: {}, data10: {}, data11: {}, data12: {}, data13: {}, data14: {}",
				getBooleanValue(entity.getData1()),
				getBooleanValue(entity.getData2()),
				getBooleanValue(entity.getData3()),
				getBooleanValue(entity.getData4()),
				getBooleanValue(entity.getData5()),
				getBooleanValue(entity.getData6()),
				getBooleanValue(entity.getData7()),
				getBooleanValue(entity.getData8()),
				getBooleanValue(entity.getData9()),
				getBooleanValue(entity.getData10()),
				getBooleanValue(entity.getData11()),
				getBooleanValue(entity.getData12()),
				getBooleanValue(entity.getData13()),
				getBooleanValue(entity.getData14()));
	}
	
	/**
	 * Get boolean value or false if null
	 * @param value The boolean to check
	 * @return The boolean value or false if null
	 */
	private String getBooleanValue(Boolean value) {
		return value != null ? value.toString() : "null";
	}
	
	/**
	 * Get string length or 0 if null
	 * @param str The string to measure
	 * @return The length of the string or 0 if null
	 */
	private int getStringLength(String str) {
		return str != null ? str.length() : 0;
	}
	
	/**
	 * Validate data field lengths to prevent database truncation errors
	 * @param entity The entity to validate
	 */
	private void validateDataLengths(BuZyJcwOnline entity) {
		// Increase limit to 255 characters which should be more than enough for most use cases
		final int MAX_STRING_LENGTH = 255;
		
		// No need to validate length for Boolean fields
		// data1-data14 are now Boolean fields, so no length validation needed
		
		if (entity.getServerName() != null && entity.getServerName().length() > MAX_STRING_LENGTH) {
			log.warn("Truncating serverName from {} to {} characters", entity.getServerName().length(), MAX_STRING_LENGTH);
			entity.setServerName(entity.getServerName().substring(0, MAX_STRING_LENGTH));
		}
		if (entity.getSensorId() != null && entity.getSensorId().length() > MAX_STRING_LENGTH) {
			log.warn("Truncating sensorId from {} to {} characters", entity.getSensorId().length(), MAX_STRING_LENGTH);
			entity.setSensorId(entity.getSensorId().substring(0, MAX_STRING_LENGTH));
		}
		if (entity.getStatusname() != null && entity.getStatusname().length() > MAX_STRING_LENGTH) {
			log.warn("Truncating statusname from {} to {} characters", entity.getStatusname().length(), MAX_STRING_LENGTH);
			entity.setStatusname(entity.getStatusname().substring(0, MAX_STRING_LENGTH));
		}
	}
}