package com.zsElectric.boot.charging.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zsElectric.boot.charging.entity.*;
import com.zsElectric.boot.charging.mapper.ThirdPartyConnectorInfoMapper;
import com.zsElectric.boot.charging.mapper.ThirdPartyEquipmentInfoMapper;
import com.zsElectric.boot.charging.mapper.ThirdPartyStationInfoMapper;
import com.zsElectric.boot.charging.service.ThirdPartyStationDataService;
import com.zsElectric.boot.charging.vo.QueryStationsInfoVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;

/**
 * 第三方充电站数据存储服务实现
 *
 * @author system
 * @since 2025-12-11
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ThirdPartyStationDataServiceImpl implements ThirdPartyStationDataService {

    private final ThirdPartyStationInfoMapper stationInfoMapper;
    private final ThirdPartyEquipmentInfoMapper equipmentInfoMapper;
    private final ThirdPartyConnectorInfoMapper connectorInfoMapper;
    private final ObjectMapper objectMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveStationsInfo(QueryStationsInfoVO queryStationsInfoVO) {
        if (queryStationsInfoVO == null || CollectionUtils.isEmpty(queryStationsInfoVO.getStationInfos())) {
            log.warn("充电站信息为空，跳过存储");
            return;
        }

        List<StationInfo> stationInfos = queryStationsInfoVO.getStationInfos();
        log.info("开始保存充电站信息，总数: {}", stationInfos.size());

        for (StationInfo stationInfo : stationInfos) {
            try {
                // 保存充电站信息
                saveStationInfo(stationInfo);

                // 保存设备信息
                if (!CollectionUtils.isEmpty(stationInfo.getEquipmentInfos())) {
                    for (EquipmentInfo equipmentInfo : stationInfo.getEquipmentInfos()) {
                        saveEquipmentInfo(equipmentInfo, stationInfo.getStationID());

                        // 保存接口信息
                        if (!CollectionUtils.isEmpty(equipmentInfo.getConnectorInfos())) {
                            for (ConnectorInfo connectorInfo : equipmentInfo.getConnectorInfos()) {
                                saveConnectorInfo(connectorInfo, equipmentInfo.getEquipmentID(), stationInfo.getStationID());
                            }
                        }
                    }
                }
            } catch (Exception e) {
                log.error("保存充电站信息失败, stationId: {}", stationInfo.getStationID(), e);
                throw new RuntimeException("保存充电站信息失败: " + stationInfo.getStationID(), e);
            }
        }

        log.info("充电站信息保存完成");
    }

    /**
     * 保存充电站信息
     */
    private void saveStationInfo(StationInfo stationInfo) {
        // 查询是否已存在
        ThirdPartyStationInfo existingStation = stationInfoMapper.selectOne(
                new LambdaQueryWrapper<ThirdPartyStationInfo>()
                        .eq(ThirdPartyStationInfo::getStationId, stationInfo.getStationID())
        );

        ThirdPartyStationInfo entity = new ThirdPartyStationInfo();
        if (existingStation != null) {
            entity.setId(existingStation.getId());
        }

        // 设置字段值
        entity.setStationId(stationInfo.getStationID());
        entity.setOperatorId(stationInfo.getOperatorID());
        entity.setEquipmentOwnerId(stationInfo.getEquipmentOwnerID());
        entity.setStationName(stationInfo.getStationName());
        entity.setCountryCode(stationInfo.getCountryCode());
        entity.setAreaCode(stationInfo.getAreaCode());
        entity.setAddress(stationInfo.getAddress());
        entity.setStationTel(stationInfo.getStationTel());
        entity.setServiceTel(stationInfo.getServiceTel());
        entity.setStationType(stationInfo.getStationType());
        entity.setStationStatus(stationInfo.getStationStatus());
        entity.setParkNums(stationInfo.getParkNums());
        
        // 处理经纬度
        if (stationInfo.getStationLng() != null) {
            entity.setStationLng(BigDecimal.valueOf(stationInfo.getStationLng()));
        }
        if (stationInfo.getStationLat() != null) {
            entity.setStationLat(BigDecimal.valueOf(stationInfo.getStationLat()));
        }
        
        entity.setSiteGuide(stationInfo.getSiteGuide());
        entity.setConstruction(stationInfo.getConstruction());
        
        // 处理图片列表（转JSON）
        if (!CollectionUtils.isEmpty(stationInfo.getPictures())) {
            try {
                entity.setPictures(objectMapper.writeValueAsString(stationInfo.getPictures()));
            } catch (JsonProcessingException e) {
                log.warn("图片列表转JSON失败", e);
            }
        }
        
        entity.setBusineHours(stationInfo.getBusineHours());
        
        // 处理费用（字符串转BigDecimal）
        if (stationInfo.getElectricityFee() != null) {
            try {
                entity.setElectricityFee(new BigDecimal(stationInfo.getElectricityFee()));
            } catch (NumberFormatException e) {
                log.warn("电费转换失败: {}", stationInfo.getElectricityFee(), e);
            }
        }
        if (stationInfo.getServiceFee() != null) {
            try {
                entity.setServiceFee(new BigDecimal(stationInfo.getServiceFee()));
            } catch (NumberFormatException e) {
                log.warn("服务费转换失败: {}", stationInfo.getServiceFee(), e);
            }
        }
        
        entity.setParkFee(stationInfo.getParkFee());
        entity.setPayment(stationInfo.getPayment());
        entity.setSupportOrder(stationInfo.getSupportOrder());
        entity.setRemark(stationInfo.getRemark());

        // 插入或更新
        if (existingStation == null) {
            stationInfoMapper.insert(entity);
        } else {
            stationInfoMapper.updateById(entity);
        }
    }

    /**
     * 保存充电设备信息
     */
    private void saveEquipmentInfo(EquipmentInfo equipmentInfo, String stationId) {
        // 查询是否已存在
        ThirdPartyEquipmentInfo existingEquipment = equipmentInfoMapper.selectOne(
                new LambdaQueryWrapper<ThirdPartyEquipmentInfo>()
                        .eq(ThirdPartyEquipmentInfo::getEquipmentId, equipmentInfo.getEquipmentID())
        );

        ThirdPartyEquipmentInfo entity = new ThirdPartyEquipmentInfo();
        if (existingEquipment != null) {
            entity.setId(existingEquipment.getId());
        }

        // 设置字段值
        entity.setEquipmentId(equipmentInfo.getEquipmentID());
        entity.setStationId(stationId);
        entity.setManufacturerId(equipmentInfo.getManufacturerID());
        entity.setManufacturerName(equipmentInfo.getManufacturerName());
        entity.setEquipmentModel(equipmentInfo.getEquipmentModel());
        entity.setProductionDate(equipmentInfo.getProductionDate());
        entity.setEquipmentType(equipmentInfo.getEquipmentType());
        
        // 处理经纬度
        if (equipmentInfo.getEquipmentLng() != null) {
            entity.setEquipmentLng(BigDecimal.valueOf(equipmentInfo.getEquipmentLng()));
        }
        if (equipmentInfo.getEquipmentLat() != null) {
            entity.setEquipmentLat(BigDecimal.valueOf(equipmentInfo.getEquipmentLat()));
        }
        
        // 处理功率
        if (equipmentInfo.getPower() != null) {
            entity.setPower(BigDecimal.valueOf(equipmentInfo.getPower()));
        }
        
        entity.setEquipmentName(equipmentInfo.getEquipmentName());

        // 插入或更新
        if (existingEquipment == null) {
            equipmentInfoMapper.insert(entity);
        } else {
            equipmentInfoMapper.updateById(entity);
        }
    }

    /**
     * 保存充电接口信息
     */
    private void saveConnectorInfo(ConnectorInfo connectorInfo, String equipmentId, String stationId) {
        // 查询是否已存在
        ThirdPartyConnectorInfo existingConnector = connectorInfoMapper.selectOne(
                new LambdaQueryWrapper<ThirdPartyConnectorInfo>()
                        .eq(ThirdPartyConnectorInfo::getConnectorId, connectorInfo.getConnectorID())
        );

        ThirdPartyConnectorInfo entity = new ThirdPartyConnectorInfo();
        if (existingConnector != null) {
            entity.setId(existingConnector.getId());
        }

        // 设置字段值
        entity.setConnectorId(connectorInfo.getConnectorID());
        entity.setEquipmentId(equipmentId);
        entity.setStationId(stationId);
        entity.setConnectorName(connectorInfo.getConnectorName());
        entity.setConnectorType(connectorInfo.getConnectorType());
        entity.setVoltageUpperLimits(connectorInfo.getVoltageUpperLimits());
        entity.setVoltageLowerLimits(connectorInfo.getVoltageLowerLimits());
        entity.setCurrent(connectorInfo.getCurrent());
        
        // 处理功率
        if (connectorInfo.getPower() != null) {
            entity.setPower(BigDecimal.valueOf(connectorInfo.getPower()));
        }
        
        entity.setParkNo(connectorInfo.getParkNo());
        entity.setNationalStandard(connectorInfo.getNationalStandard());

        // 插入或更新
        if (existingConnector == null) {
            connectorInfoMapper.insert(entity);
        } else {
            connectorInfoMapper.updateById(entity);
        }
    }
}
