package com.ruoyi.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.Comparator;
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 getMemberRightsValue(Long userId, String cardId,String rightsCode) {
        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 -> rightsCode.equals(item.getRightsCode()))
                    .collect(Collectors.toList());
            return filterRights.get(0).getRemaining();
        }
    }

    /**
     * 根据用户id，卡id，权益编码，更新剩余值
     *
     * @param userId      用户id
     * @param memberCards 卡集合
     * @param rightsCode  权益编码
     * @param deplete     消耗值
     * @author PQZ
     * @date 14:32 2025/4/17
     **/
    @Override
    public void dealMemberRights(Long userId, List<MemberCard> memberCards, String rightsCode, Integer deplete) throws Exception {
        List<String> cardIds = memberCards.stream().map(MemberCard::getCardId).collect(Collectors.toList());
        LambdaQueryWrapper<MemberRights> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(MemberRights::getUserId, userId)
                .in(MemberRights::getCardId, cardIds)
                .eq(MemberRights::getRightsCode, rightsCode);
        try {
            List<MemberRights> rights = list(lambdaQueryWrapper);
            //取出最大值
            if (!rights.isEmpty()) {
                List<MemberRights> maxRights = getRightsValueZeroOrMax(rights);
                MemberRights max = maxRights.get(0);
                if (!("02".equals(max.getRightsType()) && max.getRightsValue() == 0)) {
                    int result = max.getRemaining() - deplete;
                    if (result < 0) {
                        throw new Exception("今日次数已达上限");
                    }
                    max.setRemaining(result);
                    updateById(max);
                }
            } else {
                throw new Exception("未查询到权限");
            }
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }

    }

    /**
     * 取出权益最大值
     * @author PQZ
     * @date 18:03 2025/4/24
     * @param rights {@link MemberRights}
     * @return java.util.List<com.ruoyi.member.domain.MemberRights>
    **/
    private List<MemberRights> getRightsValueZeroOrMax(List<MemberRights> rights) {
        // 先找 rightsValue==0 的数据
        List<MemberRights> zeroList = rights.stream()
                .filter(r -> r.getRightsValue() == 0)
                .collect(Collectors.toList());

        if (!zeroList.isEmpty()) {
            // 有 0 的返回所有 0 的数据
            return zeroList;
        }

        // 没 0，再找最大值
        int max = rights.stream()
                .mapToInt(MemberRights::getRightsValue)
                .max()
                .orElse(Integer.MIN_VALUE);

        return rights.stream()
                .filter(r -> r.getRightsValue() == max)
                .collect(Collectors.toList());
    }

    /**
     * 定时任务重置剩余值
     *
     * @author PQZ
     * @date 10:10 2025/4/22
     **/
    @Override
    public void reset(String rightsCycle) {
        LambdaQueryWrapper<MemberRights> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(MemberRights::getRightsCycle,rightsCycle);
        List<MemberRights> list = list(lambdaQueryWrapper);
        list.forEach(item -> {
            item.setRemaining(item.getRightsValue());
        });
        updateBatchById(list);
    }

}
