package com.kym.service.miniapp.impl;

import cn.hutool.core.date.StopWatch;
import com.kym.entity.miniapp.ChargeOrder;
import com.kym.entity.miniapp.User;
import com.kym.entity.miniapp.UserStation;
import com.kym.mapper.miniapp.UserStationMapper;
import com.kym.service.miniapp.ChargeOrderService;
import com.kym.service.miniapp.UserService;
import com.kym.service.miniapp.UserStationService;
import com.kym.service.mybatisplus.MyBaseServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户所属站点表 服务实现类
 * </p>
 *
 * @author skyline
 * @since 2024-08-19
 */
@Service
@Slf4j
public class UserStationServiceImpl extends MyBaseServiceImpl<UserStationMapper, UserStation> implements UserStationService {
    private UserService userService;

    private ChargeOrderService chargeOrderService;

    public UserStationServiceImpl(UserService userService, ChargeOrderService chargeOrderService) {
        this.userService = userService;
        this.chargeOrderService = chargeOrderService;
    }

    @Transactional
    @Override
    public void initUserStation() {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        // 用户id对应手机号映射
//        var userId2MobilePhone = userService.list().stream().collect(Collectors.toMap(User::getId, User::getMobilePhone));
        var userId2MobilePhone = userService.lambdaQuery().select(User::getId, User::getMobilePhone).list().stream().collect(Collectors.toMap(User::getId, User::getMobilePhone));
        // 获取所有完成充电的订单
//        var chargeOrderList = chargeOrderService.lambdaQuery().eq(ChargeOrder::getOrderStatus, ChargeOrder.ORDER_STATUS_成功).list();
        var chargeOrderList = chargeOrderService.lambdaQuery().select(ChargeOrder::getUserId, ChargeOrder::getStationId, ChargeOrder::getTotalPower).list();
        // 将订单按照用户id和站点id分组并计算出每个用户在每个站点下的充电量
        var userStationMap = chargeOrderList.stream()
                .collect(Collectors.groupingBy(chargeOrder -> chargeOrder.getUserId() + ":" + chargeOrder.getStationId(),
                        Collectors.summarizingDouble(ChargeOrder::getTotalPower)));
        var userStationList = new ArrayList<UserStation>();
        userStationMap.forEach((k, v) -> {
            var userId = Long.valueOf(k.split(":")[0]);
            var stationId = k.split(":")[1];
            var userStation = new UserStation().setUserId(userId).setStationId(stationId).setMobilePhone(userId2MobilePhone.get(userId)).setTotalPower(v.getSum());
            userStationList.add(userStation);
        });
        // 批量更新或写入
        replaceBatch(userStationList);
        stopWatch.stop();
        log.info("初始化用户站点表完成，耗时：{}", stopWatch.getTotalTimeSeconds());
    }

    /**
     * 订单结束时更新用户站点数据
     *
     * @param chargeOrder
     */
    @Override
    public void updateUserStation(ChargeOrder chargeOrder) {
        lambdaUpdate().setSql("total_power = total_power + {0}", chargeOrder.getTotalPower())
                .eq(UserStation::getUserId, chargeOrder.getUserId()).eq(UserStation::getStationId, chargeOrder.getStationId())
                .update();
    }


}
