package com.dayou.service.impl;

import com.dayou.common.BaseEntity;
import com.dayou.entity.BrokerageMarketerRatio;
import com.dayou.exception.ErrorCode;
import com.dayou.mapper.BrokerageMarketerRatioMapper;
import com.dayou.service.IBrokerageMarketerRatioService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dayou.vo.MarketerRatioVO;
import com.google.common.cache.LoadingCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import java.math.BigDecimal;
import java.util.List;
import java.util.regex.Pattern;

import static com.dayou.common.Constants.MATH_REGULAR;

/**
 * <p>
 * 项目提成比例（市场人员） 服务实现类
 * </p>
 *
 * @author wucl
 * @since 2023-03-03
 */
@Service
public class BrokerageMarketerRatioServiceImpl extends ServiceImpl<BrokerageMarketerRatioMapper, BrokerageMarketerRatio> implements IBrokerageMarketerRatioService {

    @Autowired
    private LoadingCache<String,BigDecimal> marketerRatioCache;

    @Autowired
    private BrokerageMarketerRatioMapper brokerageMarketerRatioMapper;

    @Override
    @SuppressWarnings("unchecked")
    public Page<MarketerRatioVO> selectPage(Page page, BrokerageMarketerRatio brokerageMarketerRatio){
        Page<MarketerRatioVO> xPage = brokerageMarketerRatioMapper.xPage(page,brokerageMarketerRatio);
        return xPage;
    }


    @Override
    public BrokerageMarketerRatio detail(Long id){
        return this.getById(id);
    }

    @Override
    public Boolean add(BrokerageMarketerRatio brokerageMarketerRatio){
        return  this.save(brokerageMarketerRatio);
    }

    @Override
    public Boolean update(BrokerageMarketerRatio brokerageMarketerRatio){
        boolean b = this.saveOrUpdate(brokerageMarketerRatio);
        this.cacheMarketerRatio();
        return b;
    }

    @Override
    public Boolean delete(Long id){
        //逻辑删除
        return this.removeById(id);
    }

    @Override
    public void cacheMarketerRatio(){
        List<BrokerageMarketerRatio> list = this.list(new LambdaQueryWrapper<BrokerageMarketerRatio>()
                .eq(BaseEntity::getDeleted, Boolean.FALSE).isNotNull(BrokerageMarketerRatio::getRatio));
        list.stream().forEach(x->{
            marketerRatioCache.put(x.mergeKey(),x.getRatio());
        });
    }
}
