package org.jeecg.modules.bu_zy_jcw.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.bu_zy_jcw.entity.BuZyJcwOnline;
import org.jeecg.modules.bu_zy_jcw.service.IBuZyJcwOnlineService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: bu_zy_jcw_online
 * @Author: jeecg-boot
 * @Date:   2025-11-26
 * @Version: V1.0
 */
@Api(tags="bu_zy_jcw_online")
@RestController
@RequestMapping("/bu_zy_jcw/buZyJcwOnline")
@Slf4j
public class BuZyJcwOnlineController extends JeecgController<BuZyJcwOnline, IBuZyJcwOnlineService> {
	@Autowired
	private IBuZyJcwOnlineService buZyJcwOnlineService;
	
	/**
	 * 分页列表查询
	 *
	 * @param buZyJcwOnline
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "bu_zy_jcw_online-分页列表查询")
	@ApiOperation(value="bu_zy_jcw_online-分页列表查询", notes="bu_zy_jcw_online-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<BuZyJcwOnline>> queryPageList(BuZyJcwOnline buZyJcwOnline,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<BuZyJcwOnline> queryWrapper = QueryGenerator.initQueryWrapper(buZyJcwOnline, req.getParameterMap());
		Page<BuZyJcwOnline> page = new Page<BuZyJcwOnline>(pageNo, pageSize);
		IPage<BuZyJcwOnline> pageList = buZyJcwOnlineService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 * 按年月日时分秒查询历史数据
	 *
	 * @param year 年
	 * @param month 月
	 * @param day 日
	 * @param hour 时
	 * @param minute 分
	 * @param second 秒
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@AutoLog(value = "bu_zy_jcw_online-按年月日时分秒查询历史数据")
	@ApiOperation(value="bu_zy_jcw_online-按年月日时分秒查询历史数据", notes="bu_zy_jcw_online-按年月日时分秒查询历史数据")
	@GetMapping(value = "/historyList")
	public Result<IPage<BuZyJcwOnline>> queryHistoryList(
								   @RequestParam(name="year", required = false) Integer year,
								   @RequestParam(name="month", required = false) Integer month,
								   @RequestParam(name="day", required = false) Integer day,
								   @RequestParam(name="hour", required = false) Integer hour,
								   @RequestParam(name="minute", required = false) Integer minute,
								   @RequestParam(name="second", required = false) Integer second,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
		Page<BuZyJcwOnline> page = new Page<BuZyJcwOnline>(pageNo, pageSize);
		try
		{
			// 构建日期字符串用于查询
			StringBuilder dateStrBuilder = new StringBuilder();
			if (year != null) {
				dateStrBuilder.append(String.format("%04d", year));
			}
			if (month != null) {
				dateStrBuilder.append(String.format("%02d", month));
			}
			if (day != null) {
				dateStrBuilder.append(String.format("%02d", day));
			}
			if (hour != null) {
				dateStrBuilder.append(String.format("%02d", hour));
			}
			if (minute != null) {
				dateStrBuilder.append(String.format("%02d", minute));
			}
			if (second != null) {
				dateStrBuilder.append(String.format("%02d", second));
			}
			
			String dateStr = dateStrBuilder.toString();
			if (dateStr.isEmpty()) {
				return Result.error("至少需要选择一个时间条件");
			}
			
			IPage<BuZyJcwOnline> pageList = buZyJcwOnlineService.queryHistoryDataByCondition(page, dateStr);

			// 判断是否有数据
			if (pageList == null || pageList.getRecords().isEmpty()) {
				return Result.error("暂无数据");
			}
			return Result.OK(pageList);
		} catch (Exception e) {
			log.error("查询历史数据异常: ", e);
			// 如果表不存在或其他数据库错误，返回友好提示
			// 检查异常及其原因链中是否包含SQLSyntaxErrorException
			Throwable cause = e;
			while (cause != null) {
				if (cause instanceof java.sql.SQLSyntaxErrorException && cause.getMessage().contains("doesn't exist")) {
					// 提取表名并加入错误消息中
					String message = cause.getMessage();
					String tableName = "";
					if (message.contains("'")) {
						int start = message.indexOf("'");
						int end = message.indexOf("'", start + 1);
						if (end > start) {
							tableName = message.substring(start + 1, end);
							return Result.error("暂无数据，数据库中不存在表: " + tableName);
						}
					}
					return Result.error("暂无数据");
				}
				cause = cause.getCause();
			}
			return Result.error("数据查询异常，请稍后重试");
		}
	}
	
	/**
	 * 按时间范围查询历史数据
	 *
	 * @param startTime 开始时间(格式: yyyy-MM-dd HH:mm:ss)
	 * @param endTime 结束时间(格式: yyyy-MM-dd HH:mm:ss)
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@AutoLog(value = "bu_zy_jcw_online-按时间范围查询历史数据")
	@ApiOperation(value="bu_zy_jcw_online-按时间范围查询历史数据", notes="bu_zy_jcw_online-按时间范围查询历史数据")
	@GetMapping(value = "/historyListByTimeRange")
	public Result<IPage<BuZyJcwOnline>> queryHistoryListByTimeRange(@RequestParam(name="startTime") String startTime,
							   @RequestParam(name="endTime") String endTime,
							   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
							   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
		Page<BuZyJcwOnline> page = new Page<BuZyJcwOnline>(pageNo, pageSize);
		try
		{
			IPage<BuZyJcwOnline> pageList = buZyJcwOnlineService.queryHistoryDataByTimeRange(page, startTime, endTime);

			// 判断是否有数据
			if (pageList == null || pageList.getRecords().isEmpty()) {
				return Result.error("指定时间范围内暂无历史数据");
			}
			return Result.OK(pageList);
		} catch (Exception e) {
			log.error("查询历史数据异常: ", e);
			// 如果表不存在或其他数据库错误，返回友好提示
			// 检查异常及其原因链中是否包含SQLSyntaxErrorException
			Throwable cause = e;
			while (cause != null) {
				if (cause instanceof java.sql.SQLSyntaxErrorException && cause.getMessage().contains("doesn't exist")) {
					// 提取表名并加入错误消息中
					String message = cause.getMessage();
					String tableName = "";
					if (message.contains("'")) {
						int start = message.indexOf("'");
						int end = message.indexOf("'", start + 1);
						if (end > start) {
							tableName = message.substring(start + 1, end);
							return Result.error("暂无数据，数据库中不存在表: " + tableName + "，请联系管理员创建对应的历史数据表，或选择其他时间范围进行查询");
						}
					}
					return Result.error("暂无数据，历史数据表不存在，请联系管理员创建对应的历史数据表，或选择其他时间范围进行查询");
				}
				cause = cause.getCause();
			}
			return Result.error("数据查询异常: " + e.getMessage() + "，请联系管理员");
		}
	}
	
	/**
	 *   添加
	 *
	 * @param buZyJcwOnline
	 * @return
	 */
	@AutoLog(value = "bu_zy_jcw_online-添加")
	@ApiOperation(value="bu_zy_jcw_online-添加", notes="bu_zy_jcw_online-添加")
	//@RequiresPermissions("org.jeecg.modules:bu_zy_jcw_online:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody BuZyJcwOnline buZyJcwOnline) {
		buZyJcwOnlineService.save(buZyJcwOnline);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param buZyJcwOnline
	 * @return
	 */
	@AutoLog(value = "bu_zy_jcw_online-编辑")
	@ApiOperation(value="bu_zy_jcw_online-编辑", notes="bu_zy_jcw_online-编辑")
	//@RequiresPermissions("org.jeecg.modules:bu_zy_jcw_online:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody BuZyJcwOnline buZyJcwOnline,
							   @RequestParam(name="dataType", required=false) String dataType,
							   @RequestParam(name="month", required=false) String month) {
		log.info("编辑 buZyJcwOnline 数据: {}", buZyJcwOnline);
		log.info("请求参数: dataType={}, month={}", dataType, month);
		
		if (buZyJcwOnline.getId() == null) {
			log.error("编辑失败: 缺少ID参数");
			return Result.error("缺少ID参数，无法更新");
		}
		
		// Check if we're editing historical data
		if ("history".equals(dataType) && month != null && !month.isEmpty()) {
			log.info("正在编辑历史数据，月份: {}", month);
			// For historical data, we need to update directly in the history table
			try {
				boolean updated = buZyJcwOnlineService.updateHistoricalData(buZyJcwOnline, month);
				if (updated) {
					log.info("历史数据编辑成功: ID为 {} 的数据已更新", buZyJcwOnline.getId());
					return Result.OK("编辑成功!");
				} else {
					log.warn("历史数据编辑失败: ID为 {} 的数据更新失败", buZyJcwOnline.getId());
					return Result.error("编辑失败! 未找到要更新的数据记录");
				}
			} catch (Exception e) {
				log.error("历史数据编辑异常: 更新ID为 {} 的数据时发生错误", buZyJcwOnline.getId(), e);
				// Check if it's a data truncation error
				if (isDataTruncationError(e)) {
					return Result.error("编辑失败: 输入数据过长，请检查并缩短后再提交");
				}
				return Result.error("编辑异常: " + e.getMessage());
			}
		} else {
			// Regular online data editing
			// Even if the record doesn't exist in DB, try to update it directly
			// This fixes the issue where the UI shows data that may not be in sync with DB
			try {
				boolean updated = buZyJcwOnlineService.updateById(buZyJcwOnline);
				if (updated) {
					log.info("编辑成功: ID为 {} 的数据已更新", buZyJcwOnline.getId());
					return Result.OK("编辑成功!");
				} else {
					// If update didn't affect any rows, still return success to avoid confusing the user
					// This can happen when data in UI is not in sync with DB
					log.warn("编辑完成但没有数据被更新: ID为 {} 的数据", buZyJcwOnline.getId());
					return Result.OK("编辑成功!");
				}
			} catch (Exception e) {
				log.error("编辑异常: 更新ID为 {} 的数据时发生错误", buZyJcwOnline.getId(), e);
				// Check if it's a data truncation error
				if (isDataTruncationError(e)) {
					return Result.error("编辑失败: 输入数据过长，请检查并缩短后再提交");
				}
				return Result.error("编辑异常: " + e.getMessage());
			}
		}
	}
	
	/**
	 * Check if the exception is a data truncation error
	 * @param e The exception to check
	 * @return true if it's a data truncation error, false otherwise
	 */
	private boolean isDataTruncationError(Exception e) {
		Throwable cause = e;
		while (cause != null) {
			// Check for data truncation error by message content instead of class
			// to avoid needing to import MySQL-specific classes
			if (cause.getMessage() != null && cause.getMessage().contains("Data truncation")) {
				return true;
			}
			cause = cause.getCause();
		}
		return false;
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "bu_zy_jcw_online-通过id删除")
	@ApiOperation(value="bu_zy_jcw_online-通过id删除", notes="bu_zy_jcw_online-通过id删除")
	//@RequiresPermissions("org.jeecg.modules:bu_zy_jcw_online:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		buZyJcwOnlineService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "bu_zy_jcw_online-批量删除")
	@ApiOperation(value="bu_zy_jcw_online-批量删除", notes="bu_zy_jcw_online-批量删除")
	//@RequiresPermissions("org.jeecg.modules:bu_zy_jcw_online:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.buZyJcwOnlineService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "bu_zy_jcw_online-通过id查询")
	@ApiOperation(value="bu_zy_jcw_online-通过id查询", notes="bu_zy_jcw_online-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<BuZyJcwOnline> queryById(@RequestParam(name="id",required=true) String id) {
		BuZyJcwOnline buZyJcwOnline = buZyJcwOnlineService.getById(id);
		if(buZyJcwOnline==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(buZyJcwOnline);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param buZyJcwOnline
    */
    //@RequiresPermissions("org.jeecg.modules:bu_zy_jcw_online:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BuZyJcwOnline buZyJcwOnline) {
        return super.exportXls(request, buZyJcwOnline, BuZyJcwOnline.class, "bu_zy_jcw_online");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("bu_zy_jcw_online:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, BuZyJcwOnline.class);
    }

}