package cn.hnthyy.thmz.service.impl.thmz;

import cn.hnthyy.thmz.entity.thmz.Discount;
import cn.hnthyy.thmz.mapper.thmz.DiscountMapper;
import cn.hnthyy.thmz.service.thmz.DiscountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class DiscountServiceImpl implements DiscountService {
    @SuppressWarnings("all")
    @Autowired
    private DiscountMapper discountMapper;
    /**
     * 缓存
     */
    private Map<String, Discount> map = new HashMap();

    @Override
    public int save(Discount discount) {
        discount.setCreateTime(new Date());
        int num = discountMapper.insert(discount);
        getCacheMap();
        return num;
    }
    @Override
    public void getCacheMap() {
        map.clear();
        List<Discount> discounts= discountMapper.selectDiscountForToday();
        if(discounts!=null && discounts.size()>0){
            StringBuilder sbd = new StringBuilder();
            for (Discount d:discounts){
               if(d.getChargeItemCodes()!=null && d.getChargeItemCodes().length()>0){
                   List<String> list = Arrays.asList(d.getChargeItemCodes().split(","));
                   if(list!=null && list.size()>0){
                       for (String str:list){
                           sbd.append(str).append("-").append(d.getDeptType()).append("-").append(d.getDeptNo());
                           map.put(sbd.toString(),d);
                           sbd.setLength(0);
                       }
                   }
                }
            }
        }
    }

    @Override
    public int modify(Discount discount) {
        discount.setUpdateTime(new Date());
        int num = discountMapper.update(discount);
        getCacheMap();
        return num;
    }

    @Override
    public List<Discount> queryDiscountWithPage(Discount discount) {
        return discountMapper.selectDiscountWithPage(discount);
    }

    @Override
    public Integer queryDiscount(Discount discount) {
        return discountMapper.selectDiscount(discount);
    }

    @Override
    public List<Discount> queryDiscountForToday() {
        return discountMapper.selectDiscountForToday();
    }

    @Override
    public Discount queryById(Long id) {
        return discountMapper.selectById(id);
    }

    @Override
    public int removeById(Long id) {
        int num = discountMapper.deleteById(id);
        getCacheMap();
        return num;
    }

    @Override
    public Discount getDiscountRate(Integer deptType,String deptNo,String chargeItemCode) {
        if(map.size()==0){
            return null;
        }
        StringBuilder sbd = new StringBuilder();
        sbd.append(chargeItemCode).append("-").append(deptType).append("-").append(deptNo);
        return map.get(sbd.toString());
    }


}
