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

import com.ace.cache.annotation.Cache;
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 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.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,Integer> getUserMemberLevelAndDisCountMapByLevels(List<Integer> levels){
       List<BaseUserMemberLevel> baseUserMemberLevels = mapper.selectUserMembersLevelByLevels(levels);
        Map<Integer,Integer> levelAndDiscountMap = null;
       if (CollectionUtils.isNotEmpty(baseUserMemberLevels)){
           levelAndDiscountMap = baseUserMemberLevels.stream().collect(Collectors.toMap(BaseUserMemberLevel::getLevel,BaseUserMemberLevel::getDiscount));
       }
       return levelAndDiscountMap;
    }
}
