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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zsElectric.boot.charging.entity.ThirdPartyEquipmentPricePolicy;
import com.zsElectric.boot.charging.entity.ThirdPartyPolicyInfo;
import com.zsElectric.boot.charging.mapper.ThirdPartyEquipmentPricePolicyMapper;
import com.zsElectric.boot.charging.mapper.ThirdPartyPolicyInfoMapper;
import com.zsElectric.boot.charging.service.ThirdPartyPricePolicyDataService;
import com.zsElectric.boot.charging.vo.ChargingPricePolicyVO;
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.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 第三方价格策略数据存储服务实现
 *
 * @author system
 * @since 2025-12-12
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ThirdPartyPricePolicyDataServiceImpl implements ThirdPartyPricePolicyDataService {

    private final ThirdPartyEquipmentPricePolicyMapper pricePolicyMapper;
    private final ThirdPartyPolicyInfoMapper policyInfoMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void savePricePolicyInfo(ChargingPricePolicyVO pricePolicyVO) {
        if (pricePolicyVO == null) {
            log.warn("价格策略信息为空，跳过存储");
            return;
        }

        try {
            // 查询最新的价格策略记录
            ThirdPartyEquipmentPricePolicy latestPolicy = getLatestPricePolicy(
                    pricePolicyVO.getEquipBizSeq(), 
                    pricePolicyVO.getConnectorID()
            );

            // 如果数据完全相同，不做任何操作
            if (latestPolicy != null && isPolicySame(latestPolicy, pricePolicyVO)) {
                log.info("价格策略数据未发生变化，跳过保存 - equipBizSeq: {}, connectorId: {}", 
                        pricePolicyVO.getEquipBizSeq(), pricePolicyVO.getConnectorID());
                return;
            }

            // 数据发生变化，插入新记录
            Long policyId = insertNewPricePolicy(pricePolicyVO);

            // 保存价格策略明细
            if (!CollectionUtils.isEmpty(pricePolicyVO.getPolicyInfos())) {
                for (ChargingPricePolicyVO.PolicyInfo policyInfo : pricePolicyVO.getPolicyInfos()) {
                    savePolicyInfoDetail(policyInfo, policyId);
                }
            }

            log.info("价格策略信息保存成功(新增记录) - equipBizSeq: {}, connectorId: {}, policyId: {}", 
                    pricePolicyVO.getEquipBizSeq(), pricePolicyVO.getConnectorID(), policyId);

        } catch (Exception e) {
            log.error("保存价格策略信息失败 - equipBizSeq: {}, connectorId: {}", 
                    pricePolicyVO.getEquipBizSeq(), pricePolicyVO.getConnectorID(), e);
            throw new RuntimeException("保存价格策略信息失败", e);
        }
    }

    /**
     * 获取最新的价格策略记录
     */
    private ThirdPartyEquipmentPricePolicy getLatestPricePolicy(String equipBizSeq, String connectorId) {
        List<ThirdPartyEquipmentPricePolicy> policies = pricePolicyMapper.selectList(
                Wrappers.<ThirdPartyEquipmentPricePolicy>lambdaQuery()
                        .eq(ThirdPartyEquipmentPricePolicy::getEquipBizSeq, equipBizSeq)
                        .eq(ThirdPartyEquipmentPricePolicy::getConnectorId, connectorId)
                        .orderByDesc(ThirdPartyEquipmentPricePolicy::getCreateTime)
                        .last("LIMIT 1")
        );
        
        return CollectionUtils.isEmpty(policies) ? null : policies.get(0);
    }

    /**
     * 判断价格策略是否相同（比较主表和明细表）
     */
    private boolean isPolicySame(ThirdPartyEquipmentPricePolicy latestPolicy, ChargingPricePolicyVO newPolicy) {
        // 比较主表字段
        if (!Objects.equals(latestPolicy.getSuccStat(), newPolicy.getSuccStat()) ||
            !Objects.equals(latestPolicy.getFailReason(), newPolicy.getFailReason()) ||
            !Objects.equals(latestPolicy.getSumPeriod(), newPolicy.getSumPeriod())) {
            return false;
        }

        // 查询明细表数据
        List<ThirdPartyPolicyInfo> existingDetails = policyInfoMapper.selectList(
                Wrappers.<ThirdPartyPolicyInfo>lambdaQuery()
                        .eq(ThirdPartyPolicyInfo::getPricePolicyId, latestPolicy.getId())
                        .orderBy(true, true, ThirdPartyPolicyInfo::getStartTime)
        );

        // 比较明细表
        return isPolicyDetailsSame(existingDetails, newPolicy.getPolicyInfos());
    }

    /**
     * 比较价格策略明细是否相同
     */
    private boolean isPolicyDetailsSame(List<ThirdPartyPolicyInfo> existingDetails, 
                                        List<ChargingPricePolicyVO.PolicyInfo> newDetails) {
        if (CollectionUtils.isEmpty(existingDetails) && CollectionUtils.isEmpty(newDetails)) {
            return true;
        }
        
        if (CollectionUtils.isEmpty(existingDetails) || CollectionUtils.isEmpty(newDetails)) {
            return false;
        }
        
        if (existingDetails.size() != newDetails.size()) {
            return false;
        }

        // 按 StartTime 排序后比较
        List<ChargingPricePolicyVO.PolicyInfo> sortedNewDetails = newDetails.stream()
                .sorted(Comparator.comparing(ChargingPricePolicyVO.PolicyInfo::getStartTime))
                .collect(Collectors.toList());

        for (int i = 0; i < existingDetails.size(); i++) {
            ThirdPartyPolicyInfo existing = existingDetails.get(i);
            ChargingPricePolicyVO.PolicyInfo newDetail = sortedNewDetails.get(i);

            if (!Objects.equals(existing.getStartTime(), newDetail.getStartTime()) ||
                !isBigDecimalEqual(existing.getElecPrice(), newDetail.getElecPrice()) ||
                !isBigDecimalEqual(existing.getServicePrice(), newDetail.getServicePrice()) ||
                !Objects.equals(existing.getPeriodFlag(), newDetail.getPeriodFlag())) {
                return false;
            }
        }

        return true;
    }

    /**
     * 比较 BigDecimal 是否相等（处理 null 情况）
     */
    private boolean isBigDecimalEqual(BigDecimal a, BigDecimal b) {
        if (a == null && b == null) {
            return true;
        }
        if (a == null || b == null) {
            return false;
        }
        return a.compareTo(b) == 0;
    }

    /**
     * 插入新的价格策略记录
     */
    private Long insertNewPricePolicy(ChargingPricePolicyVO pricePolicyVO) {
        ThirdPartyEquipmentPricePolicy entity = new ThirdPartyEquipmentPricePolicy();
        
        // 设置字段值
        entity.setEquipBizSeq(pricePolicyVO.getEquipBizSeq());
        entity.setConnectorId(pricePolicyVO.getConnectorID());
        entity.setSuccStat(pricePolicyVO.getSuccStat());
        entity.setFailReason(pricePolicyVO.getFailReason());
        entity.setSumPeriod(pricePolicyVO.getSumPeriod());
        entity.setCreateTime(LocalDateTime.now());

        // 插入新记录
        pricePolicyMapper.insert(entity);

        return entity.getId();
    }

    /**
     * 保存价格策略明细
     */
    private void savePolicyInfoDetail(ChargingPricePolicyVO.PolicyInfo policyInfo, Long policyId) {
        ThirdPartyPolicyInfo entity = new ThirdPartyPolicyInfo();
        entity.setPricePolicyId(policyId);
        entity.setStartTime(policyInfo.getStartTime());
        entity.setElecPrice(policyInfo.getElecPrice());
        entity.setServicePrice(policyInfo.getServicePrice());
        entity.setPeriodFlag(policyInfo.getPeriodFlag());
        entity.setCreateTime(LocalDateTime.now());

        policyInfoMapper.insert(entity);
    }
}
