package com.ssj.service.sys.award.service.impl;

import com.ssj.bean.sys.award.domain.*;
import com.ssj.bean.sys.fx.domain.Merchant;
import com.ssj.dao.sys.award.dao.AwardActivityDao;
import com.ssj.dao.sys.award.dao.AwardQueryDao;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.service.conch.conch.service.HomeworkRankingService;
import com.ssj.service.sys.award.service.*;
import com.ssj.service.sys.fx.service.MerchantService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class AwardActivityServiceImpl extends BaseServiceImpl<AwardActivity, String> implements AwardActivityService {
	
	@Autowired
	private AwardActivityDao  awardActivityDao;

	@Autowired
	private AwardQueryDao  queryDao;
	
	@Autowired
	private  AwardStockService awardStockService;
	
	@Autowired
	private  AwardConsumeService awardConsumeService;
	
	@Autowired
	private  AwardSncodeService awardSncodeService;
	
	@Autowired
	private  AwardMaterialService awardMaterialService;
	
	@Autowired
	private  MerchantService merchantService;
	
	@Autowired
	private  HomeworkRankingService homeworkRankingService; 
	
	@Autowired
	private  AwardActivityLogService awardActivityLogService; 
	
	
	@Override
	public PagingAndSortingRepository<AwardActivity, String> getDao() {
		return awardActivityDao;
	}

	@Override
	public Page<Map<String, Object>> findAwardActivityBylist(Map<String, Object> searchParams, Pageable pageable) {
		return queryDao.findAwardActivityBylist(searchParams, pageable);
	}

	//发布活动，同时扣除商户下的库存。
	@Override
	public boolean createAwardActivityAndAwardStock(AwardActivity awardActivity) {
		List<AwardStock> awardStocks=new ArrayList<AwardStock>();
		List<AwardConsume> awardConsumes=new ArrayList<AwardConsume>();
		
		if(StringUtils.isNotEmpty(awardActivity.getLevel1MaterialId())) {
			AwardStock awardStock=awardStockService.getAwardStockByMaterialId(awardActivity.getMerchantId(), awardActivity.getLevel1MaterialId());
			if(awardStock==null || awardStock.getStockNumber()<awardActivity.getLevel1Num()) {
				return false;
			}
			awardStock.setStockNumber(awardStock.getStockNumber()-awardActivity.getLevel1Num());
			awardStock.setUseNumber(awardStock.getUseNumber()+awardActivity.getLevel1Num());
			awardStocks.add(awardStock);
			
			AwardConsume awardConsume=new AwardConsume();
			awardConsume.setFromMerchantId(awardActivity.getMerchantId());
			awardConsume.setToMerchantId(null);
			awardConsume.setAwardMaterialId(awardActivity.getLevel1MaterialId());
			awardConsume.setNumber(awardActivity.getLevel1Num());
			awardConsume.setType(3);
			awardConsume.setRemarks("创建活动消耗");
			awardConsumes.add(awardConsume);
			
		}
		
		
		if(StringUtils.isNotEmpty(awardActivity.getLevel2MaterialId())) {
			AwardStock awardStock=awardStockService.getAwardStockByMaterialId(awardActivity.getMerchantId(), awardActivity.getLevel2MaterialId());
			if(awardStock==null || awardStock.getStockNumber()<awardActivity.getLevel2Num()) {
				return false;
			}
			awardStock.setStockNumber(awardStock.getStockNumber()-awardActivity.getLevel2Num());
			awardStock.setUseNumber(awardStock.getUseNumber()+awardActivity.getLevel2Num());
			awardStocks.add(awardStock);
			
			
			AwardConsume awardConsume=new AwardConsume();
			awardConsume.setFromMerchantId(awardActivity.getMerchantId());
			awardConsume.setToMerchantId(null);
			awardConsume.setAwardMaterialId(awardActivity.getLevel2MaterialId());
			awardConsume.setNumber(awardActivity.getLevel2Num());
			awardConsume.setType(3);
			awardConsume.setRemarks("创建活动消耗");
			awardConsumes.add(awardConsume);
		}
		
		if(StringUtils.isNotEmpty(awardActivity.getLevel3MaterialId())) {
			AwardStock awardStock=awardStockService.getAwardStockByMaterialId(awardActivity.getMerchantId(), awardActivity.getLevel3MaterialId());
			if(awardStock==null || awardStock.getStockNumber()<awardActivity.getLevel3Num()) {
				return false;
			}
			awardStock.setStockNumber(awardStock.getStockNumber()-awardActivity.getLevel3Num());
			awardStock.setUseNumber(awardStock.getUseNumber()+awardActivity.getLevel3Num());
			awardStocks.add(awardStock);
			
			AwardConsume awardConsume=new AwardConsume();
			awardConsume.setFromMerchantId(awardActivity.getMerchantId());
			awardConsume.setToMerchantId(null);
			awardConsume.setAwardMaterialId(awardActivity.getLevel3MaterialId());
			awardConsume.setNumber(awardActivity.getLevel3Num());
			awardConsume.setType(3);
			awardConsume.setRemarks("创建活动消耗");
			awardConsumes.add(awardConsume);
		}
		
		awardActivity.setUpdateTime(new Date());
		awardActivity=this.save(awardActivity);
		awardStockService.save(awardStocks);
		awardConsumeService.saveAwardConsumeLog(awardConsumes);
		
		//直接发布的活动，直接生成奖品code列表
		if(1==awardActivity.getStatus()) {
			awardSncodeService.createAwardSncodeByCode(awardActivity);
		}
		return true;
	}

	@Override
	public AwardActivity getAwardActivityByMerchantId(String merchantId, Integer status) {
		return awardActivityDao.getAwardActivityByMerchantId(merchantId, status);
	}

	@Override
	public synchronized boolean updateAwardActivityByStatus(AwardActivity awardActivity, Integer status) {
		switch (status) {
			case 0://取消活动
				awardSncodeService.cleanAwardSncodeByCode(awardActivity);
				break;
			case 1://发布活动
				awardSncodeService.createAwardSncodeByCode(awardActivity);
				break;
			case 2://审核中
				
				break;
			case 3://审核不通过
				awardSncodeService.cleanAwardSncodeByCode(awardActivity);
				break;
			default:
				break;
		}
		awardActivity.setStatus(status);
		awardActivity.setUpdateTime(new Date());
		this.save(awardActivity);
		return false;
	}

	@Override
	public Map<String, Object> getAwardActivityMapByMerchantId(String merchantId, Integer status) {
		List<Map<String, Object>> list=queryDao.getAwardActivityMapByMerchantId(merchantId, status);
		return (list!=null && list.size()>0) ? list.get(0) : null;
	}

	@Override
	public Integer exchangeAwardActivityByMaterialId(String userId,String vipId, String materialId) {
		//兑换状态：1：兑换成功，2：积分不够，3：奖品库存不够
		Integer status=3;
		// # 查出vipId的积分
        Integer integral=homeworkRankingService.searchIntegralByVipId(vipId);

        Merchant merchant=merchantService.getDefaultMerchantByVipId(vipId);
        if(merchant!=null) {//绑定的商户
        	AwardActivity awardActivity=this.getAwardActivityByMerchantId(merchant.getId(), 1);
        	if(awardActivity!=null) {
        		
        		//查物资的兑换积分
        		AwardMaterial awardMaterial=awardMaterialService.getById(materialId);
        		//2：积分不够
                if(integral<awardMaterial.getExchangeIntegral()) {
                	status=2;
                	return status;
                }
        		
                //查询奖码库存
        		List<AwardSncode> awardSncodes=awardSncodeService.findAwardSncodeByAwardMaterialId(awardActivity.getId(), materialId,0);
        		//3：奖品库存不够
                if(awardSncodes==null || awardSncodes.size()<=0) {
                	status=3;
                	return status;
                }
                
                //随机查一条奖码
                AwardSncode awardSncode=awardSncodeService.randomAwardSncodeByActivityIdAndMaterialId(awardActivity.getId(),materialId);
                if(awardSncode==null) {//3：奖品库存不够
                	status=3;
                	return status;
                }
                awardSncode.setUserId(userId);
                awardSncode.setVipId(vipId);
                awardSncode.setStatus(3);
                awardSncode.setType(2);
                awardSncode.setDrawTime(new Date());
                awardSncode.setUpdateTime(new Date());
                awardSncodeService.save(awardSncode);//更新奖码状态
                
                //清除redis中该奖品的信息
                awardSncodeService.cleanAwardSncodeResisByCode(awardActivity.getId(), awardSncode.getSnCode());
               
                //减量积分
                homeworkRankingService.saveRankIntegral(vipId, -awardMaterial.getExchangeIntegral(), 10, awardSncode.getSnCode());
                
                //保存活动记录
                try {
                	AwardActivityLog log=new AwardActivityLog();
                	log.setAwardActivityId(awardActivity.getId());
                	log.setUserId(userId);
            		log.setVipId(vipId);
                	log.setCreateTime(new Date());
                	if(awardSncode!=null) {
                		log.setAwardMaterialId(awardSncode.getAwardMaterialId());
                		log.setSnCode(awardSncode.getSnCode());
                		log.setStatus(2);
                	}
                	awardActivityLogService.save(log);
            	} catch (Exception e) {
            		e.printStackTrace();
    			}
                status=1;
        	}
        }
		return status;
	}


}
