package org.dromara.ems.record.controller;

import cn.hutool.core.util.ObjectUtil;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.ServletUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.ems.common.web.EmsBaseController;
import org.dromara.ems.record.domain.RecordIotenvInstant;
import org.dromara.ems.record.service.IRecordIotenvInstantService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.*;

/**
 * 物联网数据Controller
 *
 * @author zch
 * @date 2025-04-28
 */
@RestController
@RequiredArgsConstructor

@RequestMapping("/ems/record/recordIotenvInstant")
public class RecordIotenvInstantController extends EmsBaseController
{
    
    private final IRecordIotenvInstantService recordIotenvInstantService;

    /**
     * 查询物联网数据列表
     */
    @GetMapping("/list")
    public TableDataInfo list (RecordIotenvInstant recordIotenvInstant)throws ParseException
    {
        Integer pageNum = parsePageInt("pageNum", 1);
        Integer pageSize = parsePageInt("pageSize", 10);
        return recordIotenvInstantService.selectRecordIotenvInstantListWithPage(recordIotenvInstant,pageNum,pageSize);
    }


    /**
     * 导出物联网数据列表（支持按日期分表查询、多设备批量导出、动态列导出）
     * 导出逻辑已迁移到ServiceImpl，支持大数据量导出
     */
    @Log(title = "物联网数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RecordIotenvInstant recordIotenvInstant) throws ParseException
    {
        // 校验时间范围参数
        Map<String, Object> params = recordIotenvInstant.getParams();
        if (params == null || params.get("beginRecordTime") == null || params.get("endRecordTime") == null) {
            throw new ServiceException("导出失败：请选择记录时间范围");
        }

        // 解析设备类型参数（用于动态导出列和数据过滤）
        Set<Integer> monitorTypes = parseMonitorTypes(params);
        
        // 解析振动参数（振动设备可选择导出单个参数）
        String vibrationParam = params.get("vibrationParam") != null ? params.get("vibrationParam").toString() : null;

        // 调试日志：输出解析的参数
        logger.info("导出参数 - monitorTypes原始值: {}, 解析后: {}, vibrationParam: {}", 
            params.get("monitorTypes"), monitorTypes, vibrationParam);

        // 调用Service层方法查询并过滤数据（支持大数据量导出，无数量限制）
        List<RecordIotenvInstant> list = recordIotenvInstantService.selectRecordIotenvInstantListForExportWithFilter(recordIotenvInstant, monitorTypes, vibrationParam);

        logger.info("导出列策略暂按全字段导出执行，monitorTypes: {}, vibrationParam: {}", monitorTypes, vibrationParam);
        ExcelUtil.exportExcel(list, "物联网数据", RecordIotenvInstant.class, response);
    }

    /**
     * 解析设备类型参数
     */
    private Set<Integer> parseMonitorTypes(Map<String, Object> params) {
        Set<Integer> types = new HashSet<>();
        Object monitorTypesObj = params.get("monitorTypes");
        if (monitorTypesObj != null && ObjectUtil.isNotEmpty(monitorTypesObj.toString())) {
            String[] typeStrs = monitorTypesObj.toString().split(",");
            for (String typeStr : typeStrs) {
                try {
                    types.add(Integer.parseInt(typeStr.trim()));
                } catch (NumberFormatException ignored) {
                }
            }
        }
        return types;
    }

    /**
     * 获取物联网数据详细信息
     */
    @GetMapping(value = "/{objid}")
    public R<?> getInfo(@PathVariable("objid") Long objid)
    {
        return success(recordIotenvInstantService.selectRecordIotenvInstantByObjid(objid));
    }

    /**
     * 新增物联网数据
     */
    @Log(title = "物联网数据", businessType = BusinessType.INSERT)
    @PostMapping
    public R<?> add(@RequestBody RecordIotenvInstant recordIotenvInstant)
    {
        return toAjax(recordIotenvInstantService.insertRecordIotenvInstant(recordIotenvInstant));
    }

    /**
     * 修改物联网数据
     */
    @Log(title = "物联网数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public R<?> edit(@RequestBody RecordIotenvInstant recordIotenvInstant)
    {
        return toAjax(recordIotenvInstantService.updateRecordIotenvInstant(recordIotenvInstant));
    }

    /**
     * 删除物联网数据
     */
    @Log(title = "物联网数据", businessType = BusinessType.DELETE)
	@DeleteMapping("/{objids}")
    public R<?> remove(@PathVariable Long[] objids)
    {
        return toAjax(recordIotenvInstantService.deleteRecordIotenvInstantByObjids(objids));
    }

    @GetMapping("/getRecordIotenvInstantList")
    public R<?> getRecordIotenvInstantList (RecordIotenvInstant recordIotenvInstant)throws ParseException
    {
        List<RecordIotenvInstant> recordIotenvInstants = recordIotenvInstantService.selectRecordIotenvInstantList(recordIotenvInstant);
        return success(recordIotenvInstants);
    }

    /**
     * 获取所有设备的最新数据（用于首页展示）
     */
    @GetMapping("/getLatestRecords")
    public R<?> getLatestRecords()
    {
        try {
            List<RecordIotenvInstant> latestRecords = recordIotenvInstantService.selectRecordList(new RecordIotenvInstant());
            return success(latestRecords);
        } catch (Exception e) {
            logger.error("获取设备最新数据失败", e);
            return error("获取设备最新数据失败：" + e.getMessage());
        }
    }

    /**
     * 根据父节点ID获取子设备的最新数据
     */
    @GetMapping("/getLatestRecordsByParentId/{parentId}")
    public R<?> getLatestRecordsByParentId(@PathVariable("parentId") Long parentId)
    {
        try {
            List<RecordIotenvInstant> latestRecords = recordIotenvInstantService.selectRecordListByParentId(parentId);
            return success(latestRecords);
        } catch (Exception e) {
            logger.error("根据父节点ID获取设备最新数据失败，parentId: " + parentId, e);
            return error("获取设备最新数据失败：" + e.getMessage());
        }
    }

    private Integer parsePageInt(String parameterName, Integer defaultValue) {
        String value = ServletUtils.getParameter(parameterName);
        if (ObjectUtil.isEmpty(value)) {
            return defaultValue;
        }
        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException ignored) {
            // 兼容旧前端分页参数偶发脏值，避免直接把分表查询接口打挂。
            return defaultValue;
        }
    }
}
