package com.buy507.mall.service.impl;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.buy507.mall.common.util.Constants;
import com.buy507.mall.mapper.DmsDistributionDictionaryMapper;
import com.buy507.mall.mapper.UmsMemberMapper;
import com.buy507.mall.model.DmsDistributionDictionary;
import com.buy507.mall.model.MemberLevel;
import com.buy507.mall.model.UmsMember;
import com.buy507.mall.service.BackendCommonService;
import com.buy507.mall.service.RedisService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

@Service
public class BackendCommonServiceImpl implements BackendCommonService {

	@Autowired
    private RedisService redisService;
	
	@Autowired
	private DmsDistributionDictionaryMapper distributionDictionaryMapper;
	
	@Autowired
	private UmsMemberMapper memberMapper;
	
	/**
	 * 根据name获取分销字典的value
	 * @param name
	 * @return
	 */
	@Override
	public String getDictionaryValue(String name) {
		String gsonStr = redisService.get(Constants.DISTRIBUTION_DICTIONARY);
		List<DmsDistributionDictionary> list = null;
		if(StringUtils.isEmpty(gsonStr)) {
			list = distributionDictionaryMapper.selectAll();
		} else {
			Gson gson = new Gson();
			list = gson.fromJson(gsonStr, new TypeToken<List<DmsDistributionDictionary>>() {}.getType());
		}
		for(DmsDistributionDictionary dictionary : list) {
			if(dictionary.getName().equals(name)) {
				return dictionary.getValue();
			}
		}
		return null;
	}
	
	/**
	 * 获取会员的折扣
	 * @param member
	 * @return
	 */
	@Override
	public BigDecimal getDiscount(Long memberId) {
		UmsMember member = memberMapper.selectByPrimaryKey(memberId);
		if(!MemberLevel.Member.equals(member.getMemberLevel())) {
			double discountDouble = 0d;
			BigDecimal discount = new BigDecimal(0);
    		if(MemberLevel.Consumer.equals(member.getMemberLevel())) {
    			discountDouble = Double.valueOf(getDictionaryValue(Constants.D_CONSUMER_BUY_AGAIN)) / 10;
    			discount = new BigDecimal(discountDouble);
    		} else if(MemberLevel.Partner.equals(member.getMemberLevel())) {
    			discountDouble = Double.valueOf(getDictionaryValue(Constants.D_PARTNER_BUY_AGAIN)) / 10;
    			discount = new BigDecimal(discountDouble);
    		} else {
    			discountDouble = Double.valueOf(getDictionaryValue(Constants.D_DIAMOND_BUY_AGAIN)) / 10;
    			discount = new BigDecimal(discountDouble);
    		}
    		return discount;
		}
    	return null;
	}

}
