package com.github.wxiaoqi.security.admin.biz;

import com.ace.cache.annotation.Cache;
import com.ace.cache.annotation.CacheClear;
import com.github.wxiaoqi.security.admin.entity.BaseUserMemberLevel;
import com.github.wxiaoqi.security.admin.mapper.BaseUserMemberLevelMapper;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.exception.BaseException;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author keliii
 */
@Service
public class UserMemberLevelBiz extends BaseBiz<BaseUserMemberLevelMapper,BaseUserMemberLevel> {


    @Transactional
    @Cache(key="member")
    public List<BaseUserMemberLevel> getLevesls() {
        Example example=new Example(BaseUserMemberLevel.class);
        example.createCriteria().andEqualTo("isdel",0);
        example.setOrderByClause(" level asc ");
        return  mapper.selectByExample(example);
    }

    public BaseUserMemberLevel getLevel(Integer level) {
        Example example=new Example(BaseUserMemberLevel.class);
        example.createCriteria().andEqualTo("isdel",0).andEqualTo("level",level);
        List<BaseUserMemberLevel> list=mapper.selectByExample(example);
        if (list.size()>0){
              return  list.get(0);
        }
        return null;
    }

    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Map<Integer, BaseUserMemberLevel> getUserMemberLevelAndUserMemberMapByLevels(List<Integer> levels){
       List<BaseUserMemberLevel> baseUserMemberLevels = mapper.selectUserMembersLevelByLevels(levels);
        Map<Integer,BaseUserMemberLevel> levelAndDiscountMap = null;
       if (CollectionUtils.isNotEmpty(baseUserMemberLevels)){
           levelAndDiscountMap = baseUserMemberLevels.stream().collect(Collectors.toMap(BaseUserMemberLevel::getLevel, Function.identity()));
       }
       return levelAndDiscountMap;
    }

    @CacheClear(key = "member")
    public void updateMemberBaseInfo(BaseUserMemberLevel baseUserMemberLevel) {
        int affectRows = mapper.updateByPrimaryKeySelective(baseUserMemberLevel);
        if (affectRows==0){
            throw new BaseException("更新会员等级失败");
        }
    }
}
