package com.buy507.mall.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;

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

import com.buy507.mall.common.api.CommonResult;
import com.buy507.mall.common.util.Constants;
import com.buy507.mall.component.RedisLock;
import com.buy507.mall.dao.OmsOrderDao;
import com.buy507.mall.dao.UmsMemberDao;
import com.buy507.mall.dto.MemberMonthRewardResult;
import com.buy507.mall.mapper.DmsMemberMonthRewardRecordMapper;
import com.buy507.mall.mapper.DmsMemberTradeRecordMapper;
import com.buy507.mall.mapper.UmsMemberMapper;
import com.buy507.mall.model.DmsMemberMonthRewardRecord;
import com.buy507.mall.model.DmsMemberTradeRecord;
import com.buy507.mall.model.ItemType;
import com.buy507.mall.model.MemberLevel;
import com.buy507.mall.model.UmsMember;
import com.buy507.mall.service.BackendCommonService;
import com.buy507.mall.service.UmsMemberMonthRewardService;

@Service
public class UmsMemberMonthRewardServiceImpl implements UmsMemberMonthRewardService {
	
	@Autowired
	private UmsMemberDao memberDao;
	
	@Autowired
	private OmsOrderDao orderDao;
	
	@Autowired
	private BackendCommonService commonService;
	
	@Autowired
	private UmsMemberMapper memberMapper;
	
	@Autowired
	private DmsMemberTradeRecordMapper memberTradeRecordMapper;
	
	@Autowired
	private DmsMemberMonthRewardRecordMapper memberMonthRewardRecordMapper;
	
	@Autowired
    private RedisLock redisLock;
	
	@Autowired
    private ExecutorService executorService;

	@Override
	public List<MemberMonthRewardResult> list(String nickname, Integer month) {
		
		if(month >= 1 && month <= 12) {
			
			//查询选择月份是否已经发放过，如果已经发放，不再发放
			Integer count = memberMonthRewardRecordMapper.selectCountByMonth(month);
			if(count > 0) {
				return null;
			}
			
			List<MemberMonthRewardResult> list = memberDao.selectByMemberLevelAndNickname(MemberLevel.FourDiamond.getValue(), nickname);
			if(list != null && !list.isEmpty()) {
				BigDecimal totalAmount = orderDao.getTotalAmountByMonth(month);
				double percent = Double.valueOf(commonService.getDictionaryValue(Constants.D_FOUR_DIAMOND_PLATFORM_INCOME)) / 100;
				BigDecimal bigDecimal = new BigDecimal(percent);
				BigDecimal zero = new BigDecimal(0);
				int flag = totalAmount.compareTo(zero);
				
				if(flag == 1) {
					BigDecimal platformIncome = totalAmount.multiply(bigDecimal).divide(new BigDecimal(list.size()), 2, BigDecimal.ROUND_HALF_UP);
					for(MemberMonthRewardResult result : list) {
						result.setValue(platformIncome);
					}
					return list;
				}
			}
		}
		
		return null;
	}

	@Override
	public CommonResult<String> computeMonthReward(Integer month) {
		
		//查询选择月份是否已经发放过，如果已经发放，不再发放
		Integer count = memberMonthRewardRecordMapper.selectCountByMonth(month);
		if(count > 0) {
			return CommonResult.failed(month + "月的月度奖励已经发放过了，不能重复发放");
		}
		
		List<MemberMonthRewardResult> list = memberDao.selectByMemberLevelAndNickname(MemberLevel.FourDiamond.getValue(), null);
		if(list != null && !list.isEmpty()) {
			BigDecimal totalAmount = orderDao.getTotalAmountByMonth(month);
			double percent = Double.valueOf(commonService.getDictionaryValue(Constants.D_FOUR_DIAMOND_PLATFORM_INCOME)) / 100;
			BigDecimal bigDecimal = new BigDecimal(percent);
			BigDecimal zero = new BigDecimal(0);
			int flag = totalAmount.compareTo(zero);
			
			if(flag == 1) {
				
				BigDecimal platformIncome = totalAmount.multiply(bigDecimal).divide(new BigDecimal(list.size()), 2, BigDecimal.ROUND_HALF_UP);
				executorService.execute(new Runnable() {
					@Override
					public void run() {
						
						UmsMember member = null;
						DmsMemberTradeRecord tradeRecord = null;
						DmsMemberMonthRewardRecord monthRewardRecord = null;
						for(MemberMonthRewardResult result : list) {
							
							//写入会员交易记录表
							tradeRecord = new DmsMemberTradeRecord();
							tradeRecord.setMemberId(result.getMemberId());
							tradeRecord.setItemType(ItemType.MonthReward); //月度奖励
							tradeRecord.setNote(month + "月份月度奖励");
							tradeRecord.setTitle(month + "月份月度奖励");
							tradeRecord.setValue(platformIncome);
							tradeRecord.setType(0); //收支类型：0->收入；1->支出
							tradeRecord.setCreateTime(new Date());
							memberTradeRecordMapper.insert(tradeRecord);
							
							monthRewardRecord = new DmsMemberMonthRewardRecord();
							monthRewardRecord.setMemberId(result.getMemberId());
							monthRewardRecord.setValue(platformIncome);
							monthRewardRecord.setMonth(month);
							memberMonthRewardRecordMapper.insert(monthRewardRecord);
							
							while(true) {
								long time = System.currentTimeMillis() + RedisLock.TIMEOUT;
								if(redisLock.lock(String.valueOf(result.getMemberId()), String.valueOf(time))) {
									member = memberMapper.selectByPrimaryKey(result.getMemberId());
									member.setBalance(member.getBalance().add(platformIncome));
									memberMapper.updateByPrimaryKey(member);
									redisLock.unlock(String.valueOf(result.getMemberId()), String.valueOf(time));
									break;
								}
							}
							
						}
						
					}
				});
				
			}
		}
		
		return CommonResult.success(null, "发放成功");
	}
	
	
}
