package cn.iocoder.yudao.module.iot.service.recipedeviceattribute;

import cn.iocoder.yudao.module.iot.service.device.TDengineService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import cn.iocoder.yudao.module.iot.controller.admin.recipedeviceattribute.vo.*;
import cn.iocoder.yudao.module.iot.dal.dataobject.recipedeviceattribute.RecipeDeviceAttributeDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.iot.dal.mysql.recipedeviceattribute.RecipeDeviceAttributeMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.iot.enums.ErrorCodeConstants.*;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils; // 或芋道的CollectionUtils

import java.util.List;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.iot.controller.admin.recipedeviceattribute.vo.RecipeDeviceAttributePageReqVO;
import cn.iocoder.yudao.module.iot.controller.admin.recipedeviceattribute.vo.RecipeDeviceAttributePageRespDTO;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

//import cn.iocoder.yudao.framework.common.util.bean.BeanUtils; // 确保BeanUtils的导入正确

/**
 * 配方配置（关联采集设备模型-点位管理） Service 实现类
 *
 * @author 内蒙必硕
 */
@Service
@Validated
public class RecipeDeviceAttributeServiceImpl implements RecipeDeviceAttributeService {

    @Resource
    private RecipeDeviceAttributeMapper recipeDeviceAttributeMapper;
    @Resource
    private TDengineService tdengineService;



    //        @Override
//    public Long createRecipeDeviceAttribute(RecipeDeviceAttributeSaveReqVO createReqVO) {
//        // 插入
//        RecipeDeviceAttributeDO recipeDeviceAttribute = BeanUtils.toBean(createReqVO, RecipeDeviceAttributeDO.class);
//        recipeDeviceAttributeMapper.insert(recipeDeviceAttribute);
//        // 返回
//        return recipeDeviceAttribute.getId();
//    }
    @Override
    public Boolean createRecipeDeviceAttributeBatch(RecipeDeviceAttributeSaveReqVO createReqVO) {
        // 1. 非空校验：ids集合不能为空
        if (CollectionUtils.isEmpty(createReqVO.getIds())) {
            throw new IllegalArgumentException("批量创建失败：属性ID集合（ids）不能为空");
        }
        // 2. 非空校验：基础字段（如recipe_id）不能为空
        if (createReqVO.getRecipeId() == null) {
            throw new IllegalArgumentException("批量创建失败：配方ID（recipeId）不能为空");
        }

        List<RecipeDeviceAttributeDO> attributeList = createReqVO.getIds().stream()
                .map(attributeId -> {
                    RecipeDeviceAttributeDO attributeDO = BeanUtils.toBean(createReqVO, RecipeDeviceAttributeDO.class);
                    attributeDO.setAttributeId(attributeId);
                    return attributeDO;
                })
                .collect(Collectors.toList());

// 4. 批量插入（调整接收类型）
        Boolean insertSuccess = recipeDeviceAttributeMapper.insertBatch(attributeList);

// 5. 返回是否批量插入成功
        return insertSuccess;
    }

    //    @Override
//    public void updateRecipeDeviceAttribute(RecipeDeviceAttributeSaveReqVO updateReqVO) {
//        // 校验存在
//        validateRecipeDeviceAttributeExists(updateReqVO.getId());
//        // 更新
//        RecipeDeviceAttributeDO updateObj = BeanUtils.toBean(updateReqVO, RecipeDeviceAttributeDO.class);
//        recipeDeviceAttributeMapper.updateById(updateObj);
//    }
    @Override
    @Transactional(rollbackFor = Exception.class) // 事务保证原子性
    public Boolean updateRecipeDeviceAttribute(RecipeDeviceAttributeUpdateReqVO reqVO) {
        // 1. 非空校验：recipeId不能为空（和create保持一致的校验风格）
        if (reqVO.getRecipeId() == null) {
            throw new IllegalArgumentException("更新失败：配方ID（recipeId）不能为空");
        }

        // 步骤1：删除该recipeId下的所有旧记录
        LambdaQueryWrapper<RecipeDeviceAttributeDO> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(RecipeDeviceAttributeDO::getRecipeId, reqVO.getRecipeId());
        recipeDeviceAttributeMapper.delete(deleteWrapper);

        // 步骤2：如果ids不为空，批量创建新记录（复用create的Bean拷贝+流式处理风格）
        Boolean insertSuccess = true; // 默认成功（无ids时直接返回成功）
        if (!CollectionUtils.isEmpty(reqVO.getIds())) {
            List<RecipeDeviceAttributeDO> attributeList = reqVO.getIds().stream()
                    .map(attributeId -> {
                        // 复用create的Bean拷贝逻辑，保持代码风格一致
                        RecipeDeviceAttributeDO attributeDO = BeanUtils.toBean(reqVO, RecipeDeviceAttributeDO.class);
                        attributeDO.setAttributeId(attributeId);
                        return attributeDO;
                    })
                    .collect(Collectors.toList());

            // 复用create的批量插入逻辑，返回插入结果
            insertSuccess = recipeDeviceAttributeMapper.insertBatch(attributeList);
        }

        // 返回最终结果（删除必成功，插入结果决定最终返回值）
        return insertSuccess;
    }

    @Override
    public void deleteRecipeDeviceAttribute(Long id) {
        // 校验存在
        validateRecipeDeviceAttributeExists(id);
        // 删除
        recipeDeviceAttributeMapper.deleteById(id);
    }

    private void validateRecipeDeviceAttributeExists(Long id) {
        if (recipeDeviceAttributeMapper.selectById(id) == null) {
            throw exception(RECIPE_DEVICE_ATTRIBUTE_NOT_EXISTS);
        }
    }

    @Override
    public RecipeDeviceAttributeDO getRecipeDeviceAttribute(Long id) {
        return recipeDeviceAttributeMapper.selectById(id);
    }

    @Override
    public PageResult<RecipeDeviceAttributeDO> getRecipeDeviceAttributePage(RecipeDeviceAttributePageReqVO pageReqVO) {
        return recipeDeviceAttributeMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<RecipeDeviceAttributePageRespDTO> selectPageWithAttribute(RecipeDeviceAttributePageReqVO reqVO) {
        return recipeDeviceAttributeMapper.selectPageWithAttributeWrap(reqVO);
    }

    @Override
    public List<RecipeDeviceAttributePageRespDTO> getList(RecipeDeviceAttributePageReqVO reqVO) {
        return recipeDeviceAttributeMapper.getList(reqVO);


    }


    //    @Override
//    public List<Map<String, Object>> operationAnalysisDetails(Long deviceId, String collectionStartTime, String collectionEndTime) {
//        // 1. 入参校验：仅校验deviceId
//        if (deviceId == null) {
//            throw exception(DEVICE_ID_DOES_NOT_EXIST);
//        }
//
//        List<Map<String, Object>> resultList = new ArrayList<>();
//
//        try {
//            // 2. 获取设备数据列表（按时间倒序）
//            List<Map<String, Object>> deviceDataList = tdengineService.getstDeviceDataOrderByTimeDesc(
//                    deviceId, collectionStartTime, collectionEndTime);
//
//            // 3. 遍历每个时间点的数据
//            for (Map<String, Object> deviceData : deviceDataList) {
//                String queryDataJson = (String) deviceData.get("queryData");
//                Timestamp timestamp = (Timestamp) deviceData.get("timestamp");
//
//                // 时间格式化（保持原有格式）
//                SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
//                String formattedTime = sdf.format(timestamp);
//
//                // 仅处理有效数据（JSON非空 + 时间戳非空）
//                if (StringUtils.isNotBlank(queryDataJson) && timestamp != null) {
//                    // 解析JSON为结构化数据
//                    List<Map<String, Object>> dataList = new ObjectMapper().readValue(
//                            queryDataJson,
//                            new TypeReference<List<Map<String, Object>>>() {}
//                    );
//
//                    // 按属性类型分组（保留LinkedHashMap保证顺序）
//                    Map<String, List<Map<String, Object>>> groupedData = new LinkedHashMap<>();
//                    for (Map<String, Object> data : dataList) {
//                        // 移除modelId过滤逻辑，处理所有数据
//                        String attributeTypeName = "其他";
//                        String typeStr = (String) data.get("attributeType");
//                        if (typeStr != null) {
//                            try {
//                                attributeTypeName = typeStr;
//                            } catch (Exception e) {
//                                attributeTypeName = "未知";
//                            }
//                        }
//
//                        // 简化数据结构（仅保留核心字段）
//                        Map<String, Object> simplifiedData = new HashMap<>();
//                        simplifiedData.put("addressValue", data.get("addressValue"));
//                        simplifiedData.put("attributeName", data.get("attributeName"));
//
//                        // 按属性类型分组存储
//                        groupedData.computeIfAbsent(attributeTypeName, k -> new ArrayList<>()).add(simplifiedData);
//                    }
//
//                    // 构建当前时间点的最终数据
//                    Map<String, Object> timePointData = new LinkedHashMap<>();
//                    // 添加分组后的属性数据
//                    for (Map.Entry<String, List<Map<String, Object>>> entry : groupedData.entrySet()) {
//                        timePointData.put(entry.getKey(), entry.getValue());
//                    }
//                    // 添加格式化的采集时间
//                    timePointData.put("collectTime", formattedTime);
//
//                    resultList.add(timePointData);
//                }
//            }
//        } catch (Exception e) {
//            throw new RuntimeException("处理设备数据时发生异常", e);
//        }
//
//        return resultList;
//    }
    @Override
    public Map<String, List<Map<String, Object>>> singleDevice(Long deviceId) throws JsonProcessingException {

        Map<String, List<Map<String, Object>>> resultMap = new LinkedHashMap<>();

        try {
            // 1. 获取设备数据列表
            List<Map<String, Object>> deviceDataList = tdengineService.getNewestDeviceDataOrderByTimeDesc(deviceId);
            // 3. 遍历并处理
            for (Map<String, Object> deviceData : deviceDataList) {
                String queryDataJson = (String) deviceData.get("queryData");

                if (StringUtils.isNotBlank(queryDataJson)) {
                    // 使用TypeReference解析为List<Map>而不是具体的DO对象
                    List<Map<String, Object>> dataList = new ObjectMapper().readValue(
                            queryDataJson,
                            new TypeReference<List<Map<String, Object>>>() {}
                    );

                    for (Map<String, Object> data : dataList) {
                        // 获取属性类型名称
                        String attributeTypeName = "其他";
                        String typeStr = (String) data.get("attributeType");
                        if (typeStr != null) {
                            try {
                                attributeTypeName = typeStr;
                            } catch (Exception e) {
                                attributeTypeName = "未知";
                            }
                        }

                        // 提取需要的字段
                        Map<String, Object> simplifiedData = new HashMap<>();
                        simplifiedData.put("addressValue", data.get("addressValue"));
                        simplifiedData.put("attributeName", data.get("attributeName"));

                        resultMap
                                .computeIfAbsent(attributeTypeName, k -> new ArrayList<>())
                                .add(simplifiedData);
                    }
                }
            }

        } catch (Exception e) {
            System.out.println("处理设备数据时发生异常: " + e.getMessage());
        }

        return resultMap;
    }


    @Override
    public List<RecipeDeviceAttributeDO> getByRecipeId(Long recipeId) {
        if (recipeId == null) {
            return Collections.emptyList();
        }
        return recipeDeviceAttributeMapper.selectByRecipeId(recipeId);
    }

    @Override
    public Map<String, String> getDeviceContactModelAttr(Long attributeId) {
        Map<String, String> resultMap = new HashMap<>(2);
        if (attributeId == null) {
            resultMap.put("attributeName", "");
            resultMap.put("dataUnit", "");
            return resultMap;
        }
        // 查询设备触点模型记录
//        Map<String, String> modelMap = deviceContactModelMapper.selectAttributeNameAndUnitById(attributeId);
//        if (modelMap == null) {
//            resultMap.put("attributeName", "");
//            resultMap.put("dataUnit", "");
//            return resultMap;
//        }
//        // 封装返回结果
//        resultMap.put("attributeName", modelMap.getOrDefault("attribute_name", ""));
//        resultMap.put("dataUnit", modelMap.getOrDefault("data_unit", ""));
        return resultMap;
    }

}
