package com.ruoyi.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.base.vo.CardRightsVO;
import com.ruoyi.common.config.DlRightsConfig;
import com.ruoyi.member.domain.MemberCard;
import com.ruoyi.member.domain.MemberRights;
import com.ruoyi.member.mapper.MemberRightsMapper;
import com.ruoyi.member.service.IMemberRightsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 会员权益(定时任务重置剩余值)，用户id、会员卡id、权益对应1Service业务层处理
 *
 * @author pqz
 * @date 2025-03-17
 */
@Service
public class MemberRightsServiceImpl extends ServiceImpl<MemberRightsMapper, MemberRights> implements IMemberRightsService {
    @Autowired
    private MemberRightsMapper memberRightsMapper;
    @Autowired
    private DlRightsConfig dlRightsConfig;


    /**
     * 处理会员权益
     *
     * @param userId 用户表id
     * @param rights 权益
     * @author PQZ
     * @date 15:45 2025/3/27
     **/
    @Override
    public void dealRights(Long userId, String userType, List<CardRightsVO> rights) {
        List<MemberRights> saveList = new ArrayList<>();
        rights.forEach(item -> {
            MemberRights memberRights = new MemberRights();
            memberRights.setUserId(userId);
            memberRights.setUserType(userType);
            memberRights.setCardId(item.getCardId());
            memberRights.setRightsCode(item.getCode());
            memberRights.setRightsType(item.getRightsType());
            memberRights.setRightsCycle(item.getRightsCycle());
            memberRights.setRightsValue(item.getRightsValue());
            memberRights.setRemaining(item.getRightsValue());
            saveList.add(memberRights);
        });
        saveBatch(saveList);
    }

    /**
     * 查询报名上限
     *
     * @param userId 用户id
     * @param cardId 卡id
     * @return java.lang.Integer
     * @author PQZ
     * @date 17:15 2025/3/31
     **/
    @Override
    public Integer getReport(Long userId, String cardId) {
        LambdaQueryWrapper<MemberRights> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper
                .eq(MemberRights::getUserId,userId)
                .eq(MemberRights::getCardId,cardId);
        List<MemberRights> rights = list(lambdaQueryWrapper);
        if (rights.isEmpty()){
            return dlRightsConfig.getReport();
        } else {
            List<MemberRights> filterRights = rights.stream()
                    .filter(item -> "report".equals(item.getRightsCode()))
                    .collect(Collectors.toList());
            return filterRights.get(0).getRemaining();
        }
    }
}
