package com.yeejoin.amos.boot.module.jg.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yeejoin.amos.boot.module.jg.api.entity.JgInstallationNotice;
import com.yeejoin.amos.boot.module.jg.api.entity.JgRegistrationHistory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用于业务变更过程中的历史数据处理的service层
 */
@Slf4j
@Service
public class DataHandlerServiceImpl {

    @Resource
    private ObjectMapper objectMapper;

    @Autowired
    private JgRegistrationHistoryServiceImpl registrationHistoryService;

    @Autowired
    private JgInstallationNoticeServiceImpl installationNoticeService;


    @Transactional(rollbackFor = Exception.class)
    public Boolean deviceListInFormWithInstallNotice() {
        List<JgInstallationNotice> noticeList = installationNoticeService.list(new LambdaQueryWrapper<JgInstallationNotice>()
                .eq(JgInstallationNotice::getEquCategoryCode, "8300"));

        List<JgRegistrationHistory> jgRegistrationHistories = noticeList.stream()
                .map(notice -> {
                    JgRegistrationHistory history = getRegistrationHistory(String.valueOf(notice.getSequenceNbr()));
                    if (history == null) return null;
                    try {
                        Map<String, Object> hisData = objectMapper.readValue(
                                history.getChangeData(),
                                new TypeReference<Map<String, Object>>() {
                                }
                        );
                        // 获取设备列表并处理每个设备信息
                        List<Map<String, Object>> deviceList = objectMapper.readValue(
                                objectMapper.writeValueAsString(hisData.get("deviceList")),
                                new TypeReference<ArrayList<Map<String, Object>>>() {
                                }
                        );
                        deviceList.forEach(device -> {
                            String record = String.valueOf(device.get("record"));
                            Map<String, Object> pipelineEquInfo = installationNoticeService.getBaseMapper().getPipelineEquInfoByRecord(record);
                            device.putAll(pipelineEquInfo);
                        });
                        // 更新处理后的数据回到 history 对象
                        hisData.put("deviceList", deviceList);
                        history.setChangeData(objectMapper.writeValueAsString(hisData)); // 更新 changeData 字段
                    } catch (Exception e) {
                        log.error("JSON 数据处理失败!", e);
                        throw new RuntimeException(e.getMessage());
                    }
                    return history;
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        // 批量更新历史表数据
        registrationHistoryService.updateBatchById(jgRegistrationHistories);
        return Boolean.TRUE;
    }

    // 辅助方法：根据 DocumentId 获取历史记录
    private JgRegistrationHistory getRegistrationHistory(String documentId) {
        return registrationHistoryService.getBaseMapper().selectOne(
                new QueryWrapper<JgRegistrationHistory>().lambda()
                        .eq(JgRegistrationHistory::getCurrentDocumentId, documentId)
                        .eq(JgRegistrationHistory::getIsDelete, false)
        );
    }
}
