package com.kym.service.impl;

import com.github.pagehelper.PageHelper;
import com.kym.common.utils.CommUtil;
import com.kym.entity.common.PageBean;
import com.kym.entity.WashDevice;
import com.kym.entity.WashStation;
import com.kym.entity.queryParams.StationQueryParams;
import com.kym.entity.vo.WashStationVo;
import com.kym.mapper.WashStationMapper;
import com.kym.service.RechargeConfigGroupService;
import com.kym.service.WashDeviceService;
import com.kym.service.WashStationService;
import com.kym.service.cache.KymCache;
import com.kym.service.mybatisplus.MyBaseServiceImpl;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 洗车站点表 服务实现类
 * </p>
 *
 * @author skyline
 * @since 2024-09-11
 */
@Service
public class WashStationServiceImpl extends MyBaseServiceImpl<WashStationMapper, WashStation> implements WashStationService {
    @PostConstruct
    public void init() {
        var list = list();
        KymCache.INSTANCE.putStationId2Name(list.stream().collect(Collectors.toMap(WashStation::getStationId, WashStation::getStationName)));
        KymCache.INSTANCE.putStationId2ParkingQrCodeUrl(list.stream().collect(Collectors.toMap(WashStation::getStationId, WashStation::getParkingQrCode)));
        KymCache.INSTANCE.putStationId2ParkingCouponMinAmount(list.stream().filter(s -> s.getParkingCouponMinAmount() != null).collect(Collectors.toMap(WashStation::getStationId, WashStation::getParkingCouponMinAmount)));
    }

    private final WashDeviceService washDeviceService;
    private final RechargeConfigGroupService rechargeConfigGroupService;

    public WashStationServiceImpl(WashDeviceService washDeviceService, RechargeConfigGroupService rechargeConfigGroupService) {
        this.washDeviceService = washDeviceService;
        this.rechargeConfigGroupService = rechargeConfigGroupService;
    }


    // ====================================================== 运营平台接口 Start ===========================================================

    @Override
    public void add(WashStation station) {
        Long count = lambdaQuery().eq(WashStation::getStationId, station.getStationId()).count();
        CommUtil.asserts(count == 0, "站点已存在");
        save(station);

        // 新站点不自动创建分组，默认使用平台默认分组。管理员可在充值配置中为该站点分配专属分组。
        // 如需自动创建：rechargeConfigGroupService.createGroup(new RechargeConfigGroup(), List.of(station.getStationId()));
    }

    @Override
    public void modify(WashStation station) {
        CommUtil.assertsNonNulls(List.of(station.getStationName(), station.getStationId(), station.getStationType(), station.getId()), "参数异常");
        List<WashStation> list = lambdaQuery().eq(WashStation::getStationName, station.getStationName()).list();
        CommUtil.asserts(list.size() <= 1, "站点信息异常");
        if (list.size() == 1) {
            CommUtil.asserts(list.get(0).getStationName().equalsIgnoreCase(station.getStationName()), "站点已存在");
        }
        updateById(station);
    }

    @Override
    public PageBean<WashStation> list(StationQueryParams query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<WashStation> list = lambdaQuery()
                .like(CommUtil.isNotEmptyAndNull(query.getStationName()), WashStation::getStationName, query.getStationName())
                .like(CommUtil.isNotEmptyAndNull(query.getAddress()), WashStation::getAddress, query.getAddress())
                .eq(CommUtil.isNotEmptyAndNull(query.getStationType()), WashStation::getStationType, query.getStationType())
                .list();
        return new PageBean<>(list);
    }

    @Override
    public WashStation detail(Long id) {
        return getById(id);
    }

    @Override
    public void remove(Long id) {

    }
    // ====================================================== 运营平台接口 Start ===========================================================


    // ====================================================== 小程序接口 Start ===========================================================
    @Override
    public PageBean<WashStationVo> listStationForApp(StationQueryParams params) {
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        var stationList = lambdaQuery()
                .eq(CommUtil.isNotEmptyAndNull(params.getStationId()), WashStation::getStationId, params.getStationId())
                .like(CommUtil.isNotEmptyAndNull(params.getStationName()), WashStation::getStationName, params.getStationName())
                .list();
        // 查询站点下的所有设备，按照站点统计可用设备数量
        var res = washDeviceService.lambdaQuery().in(WashDevice::getStationId, stationList.stream().map(WashStation::getStationId).toList())
                .eq(WashDevice::getState, WashDevice.STATE_空闲)
                .list().stream().collect(Collectors.groupingBy(WashDevice::getStationId, Collectors.counting()));
        var voList = stationList.stream().map(station -> {
            var vo = new WashStationVo();
            BeanUtils.copyProperties(station, vo);
            vo.setIdleParkingNum(Math.toIntExact(res.getOrDefault(station.getStationId(), 0L)));
            return vo;
        }).toList();
        return new PageBean<>(voList);

    }

    // ====================================================== 小程序接口 End ===========================================================

}
