package com.kym.service.miniapp.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kym.entity.miniapp.Account;
import com.kym.entity.miniapp.UserCoupon;
import com.kym.entity.miniapp.UserRechargeRights;
import com.kym.entity.miniapp.vo.UserRightsAndCouponsVo;
import com.kym.mapper.miniapp.AccountMapper;
import com.kym.service.miniapp.AccountService;
import com.kym.service.miniapp.UserCouponService;
import com.kym.service.miniapp.UserRechargeRightsService;
import com.kym.service.mybatisplus.MyBaseServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户账户表 服务实现类
 * </p>
 *
 * @author skyline
 * @since 2023-08-07
 */
@Service
@DS("db-miniapp")
public class AccountServiceImpl extends MyBaseServiceImpl<AccountMapper, Account> implements AccountService {

    private final UserRechargeRightsService userRechargeRightsService;

    private final UserCouponService userCouponService;

    public AccountServiceImpl(UserRechargeRightsService userRechargeRightsService, UserCouponService userCouponService) {
        this.userRechargeRightsService = userRechargeRightsService;
        this.userCouponService = userCouponService;
    }

    @Override
    public Account getAccountByUserId(Long userId) {
        return lambdaQuery().eq(Account::getUserId, userId).one();
    }

    /**
     * 获取用户权益和优惠券
     *
     * @return
     */
    @Override
    public UserRightsAndCouponsVo listRightsAndCoupons() {
        var vo = new UserRightsAndCouponsVo();
        var userId = StpUtil.getLoginIdAsLong();
        vo.setUserId(userId);

        // 当前用户的充电权益（含已失效）
        var userRechargeRight = userRechargeRightsService.lambdaQuery()
                .eq(UserRechargeRights::getUserId, userId)
                .orderByDesc(UserRechargeRights::getStatus)
                .orderByAsc(UserRechargeRights::getEndTime)
                .list();
        vo.setUserRechargeRightsList(userRechargeRight);

        // 当前用户的优惠券列表（含已失效）
        var usesrCouponList = userCouponService.lambdaQuery()
                .eq(UserCoupon::getUserId, userId)
                .orderByDesc(UserCoupon::getStatus)
                .orderByAsc(UserCoupon::getUsageStatus)
                .orderByAsc(UserCoupon::getEndTime)
                .list();
        vo.setUserCouponList(usesrCouponList);

        return vo;
    }

    @Override
    public UserRightsAndCouponsVo listStationAvailableRightsAndCoupons(String stationId) {
        var vo = new UserRightsAndCouponsVo();
        var userId = StpUtil.getLoginIdAsLong();
        vo.setUserId(userId);
        // 当前用户有效的充电权益
        var userRechargeRights = userRechargeRightsService.listStationAvailableRights(Map.of("userId", userId, "stationId", stationId));
        vo.setUserRechargeRightsList(userRechargeRights);

        // 当前用户有效的优惠券列表
        var userCouponList = userCouponService.listStationAvailableCoupons(Map.of("userId", userId, "stationId", stationId));
        vo.setUserCouponList(userCouponList);
        return vo;
    }

    /**
     * 批量处理用户权益的优惠金额
     *
     * @param userRechargeRightsList
     */
    @Transactional
    @Override
    public void batchHandleDiscountAmount(List<UserRechargeRights> userRechargeRightsList) {
        var accountList = lambdaQuery().in(Account::getUserId, userRechargeRightsList.stream().map(UserRechargeRights::getUserId).toList()).list();
        accountList.forEach(account ->
                account.setDiscountAmount(account.getDiscountAmount() - userRechargeRightsList.stream().filter(userRechargeRights -> userRechargeRights.getUserId().equals(account.getUserId())).mapToInt(UserRechargeRights::getDiscountAmount).sum()));
        updateBatchByQueryWrapper(accountList, account -> new QueryWrapper<Account>().eq("user_id", account.getUserId()));
    }


}
