package com.kym.service.impl;

import com.kym.entity.RechargeConfig;
import com.kym.entity.RechargeConfigGroup;
import com.kym.mapper.RechargeConfigGroupMapper;
import com.kym.service.RechargeConfigGroupService;
import com.kym.service.RechargeConfigService;
import com.kym.service.RechargeConfigStationGroupService;
import com.kym.service.mybatisplus.MyBaseServiceImpl;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 充值配置分组服务实现
 *
 * @author skyline
 * @since 2026-05-26
 */
@Service
public class RechargeConfigGroupServiceImpl
        extends MyBaseServiceImpl<RechargeConfigGroupMapper, RechargeConfigGroup>
        implements RechargeConfigGroupService {

    private final RechargeConfigService itemService;
    private final RechargeConfigStationGroupService stationGroupService;

    public RechargeConfigGroupServiceImpl(@Lazy RechargeConfigService itemService,
                                           RechargeConfigStationGroupService stationGroupService) {
        this.itemService = itemService;
        this.stationGroupService = stationGroupService;
    }

    @Override
    public RechargeConfigGroup getByStationId(String stationId) {
        Long groupId = stationGroupService.getGroupIdByStationId(stationId);
        if (groupId != null) {
            return getById(groupId);
        }
        return null;
    }

    @Override
    public RechargeConfigGroup getDefaultGroup() {
        return lambdaQuery().eq(RechargeConfigGroup::getIsDefault, true).one();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RechargeConfigGroup createGroup(RechargeConfigGroup group, List<String> stationIds) {
        save(group);

        // 复制默认分组的配置项
        RechargeConfigGroup defaultGroup = getDefaultGroup();
        if (defaultGroup != null) {
            List<RechargeConfig> defaultItems = itemService.listByGroupId(defaultGroup.getId());
            if (!defaultItems.isEmpty()) {
                var newItems = defaultItems.stream().map(c -> {
                    var item = new RechargeConfig();
                    item.setGroupId(group.getId());
                    item.setRechargeAmount(c.getRechargeAmount());
                    item.setGrantsAmount(c.getGrantsAmount());
                    item.setLabel(c.getLabel());
                    return item;
                }).toList();
                itemService.saveBatch(newItems);
            }
        }

        // 关联站点
        if (stationIds != null) {
            for (String stationId : stationIds) {
                stationGroupService.assignStationToGroup(stationId, group.getId());
            }
        }

        return group;
    }
}
