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

import com.ssj.bean.sys.cardinfo.domain.Card;
import com.ssj.bean.sys.cardinfo.domain.CardAward;
import com.ssj.bean.sys.cardinfo.domain.CardAwardLog;
import com.ssj.bean.weixin.message.custom.Text;
import com.ssj.bean.weixin.message.custom.TextCustom;
import com.ssj.dao.sys.cardinfo.dao.CardDao;
import com.ssj.dao.sys.cardinfo.dao.CardQueryDao;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.persistence.DynamicSpecifications;
import com.ssj.framework.core.persistence.SearchFilter;
import com.ssj.framework.core.security.manager.TokenManager;
import com.ssj.framework.core.util.SystemResourceLocator;
import com.ssj.framework.weixin.util.NewsUtil;
import com.ssj.service.sys.cardinfo.service.CardAwardService;
import com.ssj.service.sys.cardinfo.service.CardService;
import com.ssj.service.weixin.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
@Service
@Transactional
public class CardServiceImpl extends BaseServiceImpl<Card, String> implements CardService {
	@Autowired
    private CardDao cardDao;
	
	@Autowired
	private CardQueryDao cardQueryDao;
	
	
	@Autowired
	private UserService userService;
	
	
	@Autowired
	private CardAwardService cardAwardService;
	@Autowired
	private TokenManager tokenManager ;
	
	
	@Override
	public PagingAndSortingRepository<Card, String> getDao() {
		return cardDao;
	}
	@Override
	public Page<Card> findByPage(Map<String, Object> params, Pageable sp) {
		 Map<String, SearchFilter> filters = SearchFilter.parse(params);
	     Specification<Card> specification = DynamicSpecifications.bySearchFilter(filters.values(), Card.class);
	     return cardDao.findAll(specification, sp);
	}
	@Override
	public Page<Map<String, Object>> findBylist(Map<String, Object> searchParams, Pageable pageable) {
		return cardQueryDao.findByPage(searchParams, pageable);
	}
	@Override
	public void generatingSncode(String id) {
	    Integer cardi= cardDao.deleteCardAward(id);
	    if(cardi==0){
	    	Map<String,Object> map = cardQueryDao.getCardByIdAward(id);
	    	List<CardAward> list  =new  ArrayList<CardAward>();
	    	Object code=map.get("sn_code");
	    	if(code==null){ code="";}
	    	CardAward  carAward = null;
	    	Object c_num_one = map.get("c_num_one");
	    	if(c_num_one !=null&&!"".equals(c_num_one)){
	    		String c_name_one = map.get("c_name_one") !=null ? (String) map.get("c_name_one") :null;
	    		int num_one=Integer.parseInt(c_num_one.toString());
	    		for (int i = 0; i < num_one; i++) {
	    			carAward  =new  CardAward();
	    			carAward.setSnCode(code+ DateHelper.getOrderNo(5));
	    			carAward.setAwardPlace(1);//奖品类型
	    			carAward.setAwardType(c_name_one);//中奖实物
	    			carAward.setAwardStatus(0);//0 未开奖 
	    			carAward.setCardId(id);
	    			list.add(carAward);
				}
	    	}
	    	Object c_num_two = map.get("c_num_two");
	    	if(c_num_two !=null&&!"".equals(c_num_two)){
	    		int num_two=Integer.parseInt(c_num_two.toString());
	    		String c_name_two = map.get("c_name_two") !=null ? (String) map.get("c_name_two") :null;
	    		for (int i = 0; i < num_two; i++) {
	    			carAward  =new  CardAward();
	    			carAward.setSnCode(code+DateHelper.getOrderNo(5));
	    			carAward.setAwardPlace(2);//奖品类型
	    			carAward.setAwardType(c_name_two);//中奖实物
	    			carAward.setAwardStatus(0);//0 未开奖 
	    			carAward.setCardId(id);
	    			list.add(carAward);
	    		}
	    	}
	    	Object c_num_three = map.get("c_num_three");
	    	if(c_num_three !=null&&!"".equals(c_num_three)){
	    		int num_three=Integer.parseInt(c_num_three.toString());
	    		String c_name_three = map.get("c_name_three") !=null ? (String) map.get("c_name_three") :null;
	    		for (int i = 0; i < num_three; i++) {
	    			carAward  =new  CardAward();
	    			carAward.setSnCode(code+DateHelper.getOrderNo(5));
	    			carAward.setAwardPlace(3);//奖品类型
	    			carAward.setAwardType(c_name_three);//中奖实物
	    			carAward.setAwardStatus(0);//0 未开奖 
	    			carAward.setCardId(id);
	    			list.add(carAward);
	    		}
	    	}
	    	Object c_num_four = map.get("c_num_four");
	    	if(c_num_four !=null&&!"".equals(c_num_four)){
	    		int num_four=Integer.parseInt(c_num_four.toString());
	    		String c_name_four = map.get("c_name_four") !=null ? (String) map.get("c_name_four") :null;
	    		for (int i = 0; i < num_four; i++) {
	    			carAward  =new  CardAward();
	    			carAward.setSnCode(code+DateHelper.getOrderNo(5));
	    			carAward.setAwardPlace(4);//奖品类型
	    			carAward.setAwardType(c_name_four);//中奖实物
	    			carAward.setAwardStatus(0);//0 未开奖 
	    			carAward.setCardId(id);
	    			list.add(carAward);
	    		}
	    	}
	    	Object c_num_five = map.get("c_num_five");
	    	if(c_num_five !=null&&!"".equals(c_num_five)){
	    		int num_five=Integer.parseInt(c_num_five.toString());
	    		String c_name_five = map.get("c_name_five") !=null ? (String) map.get("c_name_five") :null;
	    		for (int i = 0; i < num_five; i++) {
	    			carAward  =new  CardAward();
	    			carAward.setSnCode(code+DateHelper.getOrderNo(5));
	    			carAward.setAwardPlace(5);//奖品类型
	    			carAward.setAwardType(c_name_five);//中奖实物
	    			carAward.setAwardStatus(0);//0 未开奖 
	    			carAward.setCardId(id);
	    			list.add(carAward);
	    		}
	    	}
	    	Object c_num_six = map.get("c_num_six");
	    	if(c_num_six !=null&&!"".equals(c_num_six)){
	    		int num_six=Integer.parseInt(c_num_six.toString());
	    		String c_name_six = map.get("c_name_six") !=null ? (String) map.get("c_name_six") :null;
	    		for (int i = 0; i < num_six; i++) {
	    			carAward  =new  CardAward();
	    			carAward.setSnCode(code+DateHelper.getOrderNo(5));
	    			carAward.setAwardPlace(6);//奖品类型
	    			carAward.setAwardType(c_name_six);//中奖实物
	    			carAward.setAwardStatus(0);//0 未开奖 
	    			carAward.setCardId(id);
	    			list.add(carAward);
	    		}
	    	}
	    	cardQueryDao.batchInsertCardAward(list);
	    }
		
	}
	@Override
	public Page<Map<String, Object>> findCardAward(
			Map<String, Object> searchParams, Pageable pageable) {
		return cardQueryDao.findCardAward(searchParams, pageable);
	}
	@Override
	public void deleteCardAndCardAward(String id) {
		cardDao.deleteCardAward(id);
		this.delete(id);
	}
	@Override
	public Integer getCountCardAward(String cardId) {
		return cardDao.getCountCardAward(cardId);
	}
	@Override
	public boolean getPrizeByPercent(Card card) {
		Integer count=cardDao.getCountCardAward(card.getId());
		if(count==0)return false;
		int players =  card.getExpectedNumber();//抽奖人数
		int percent =  card.getPercent();//百分比
		 Random random = new Random();
		    int rate = players * percent / 100;
		    int randomCode = random.nextInt(players) + 1;

		   if ((randomCode > 0) && (randomCode <= rate)) {
		      return true;
		  }
		    
		return false;
	}
	@Override
	public void saveCardAwardLog(CardAwardLog cardAwardLog) {
		List<CardAwardLog>  list  =new  ArrayList<CardAwardLog>();
		list.add(cardAwardLog);
		cardQueryDao.saveCardAwardLog(list);
	}
	@Override
	public int getPlayStatus(Card card, String userId) {
		
		if(2==card.getPlayStatus()){
			//感谢您的参与，该活动已经结束。
			return 2;
		}else if(0==card.getPlayStatus()){
			//感谢您的关注，该活动还没有开始。
			return 1;
		}else {
			 Date today = new Date();
			 if (today.before(card.getStartTime())){
				 //感谢您的关注，该活动还没有开始。
				 return 1;
			 } 
			 if (today.after(card.getEndTime())){
				 //感谢您的关注，该活动已经结束。。
				 return 2;
			 } 
			 
			//每人最多允许抽奖总次数：
			String time  =DateHelper.format(new Date(), "yyyy-MM-dd");
			String begenTime =time+" 00:00:00";
			String endTime =time+" 23:59:59";
			Integer everyDayCount=cardDao.getCardAwardLog(card.getId(), userId, begenTime, endTime);
			//每人每天最多可玩次数
			Integer  maxTimes = card.getMaxTimes();
			if(everyDayCount>=maxTimes){
				// 感谢您的参与，该活动一天内可参与次数已经用完。
				return 3;
			}
			//每人允许抽奖次数
			Integer userLogCount=cardDao.getCardAwardLog(card.getId(), userId);
			Integer  drawTimes  =  card.getDrawTimes();
			// 感谢您的参与，该活动可参与次数已经全部用完。
			if(userLogCount>=drawTimes)return 4;
			
           /* Integer zjCount= cardDao.getUserZJLog(card.getId(), userId);
            //感谢您的参与，您已经得奖不能重复参与。
            if(zjCount>0) return 5;*/
            
			return 0;
		}
	
	}
	@Override
	public int getPlayStatusLib(Card card, String userId) {
		
		if(2==card.getPlayStatus()){
			//感谢您的参与，该活动已经结束。
			return 2;
		}else if(0==card.getPlayStatus()){
			//感谢您的关注，该活动还没有开始。
			return 1;
		}else {
			Date today = new Date();
			if (today.before(card.getStartTime())){
				//感谢您的关注，该活动还没有开始。
				return 1;
			} 
			if (today.after(card.getEndTime())){
				//感谢您的关注，该活动已经结束。。
				return 2;
			} 
			
			//每人最多允许抽奖总次数：
			String time  =DateHelper.format(new Date(), "yyyy-MM-dd");
			String begenTime =time+" 00:00:00";
			String endTime =time+" 23:59:59";
			Integer everyDayCount=cardDao.getCardAwardLog(card.getId(), userId, begenTime, endTime);
			//每人每天最多可玩次数
			Integer  maxTimes = card.getMaxTimes();
			if(everyDayCount>=maxTimes){
				// 感谢您的参与，该活动一天内可参与次数已经用完。
				return 3;
			}
			//每人允许抽奖次数
			Integer userLogCount=cardDao.getCardAwardLog(card.getId(), userId);
			Integer  drawTimes  =  card.getDrawTimes();
			// 感谢您的参与，该活动可参与次数已经全部用完。
			if(userLogCount>=drawTimes)return 4;
			
			 Integer zjCount= cardDao.getUserZJLog(card.getId(), userId);
            //感谢您的参与，您已经得奖不能重复参与。
            if(zjCount>0) return 5;
			
			return 0;
		}
		
	}
	@Override
	public void pushCustomer(final Map<String,Object> map,final String openId) {
		if(openId!=null){
			  Thread t1 = new Thread(new Runnable() {
		            public void run() {
		            	getjiangpin(map,openId);
		            }
		        });
		        t1.start();
		}
		
	}
	
	private void getjiangpin(Map<String,Object> map,String openId){
		String cardId = (String) map.get("id");
		String id=userService.findUserById(openId);
		CardAward  cardAward=cardAwardService.findByUserIdAndCardId(id, cardId);
		TextCustom textCustom  =new TextCustom();
		textCustom.setMsgtype("text");
		textCustom.setTouser(openId);
		Text text = new  Text();
		String url=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/hd/game_"+cardId+".html";
		if(cardAward!=null){
			StringBuffer sb  =new StringBuffer("亲，您中奖啦！明天还可以继续玩哦！\n\n");
			sb.append("您的奖品是:").append(cardAward.getAwardType()).append("\n兑换码是:").append(cardAward.getSnCode());
			sb.append("\n\n赶紧联系对错小育（duicuoxy）兑奖吧！");
			sb.append("\n\n点击【<a href=\""+url+"\">活动详情</a>】烤箱天天等您来抽！");
			text.setContent(sb.toString());
		}else{
			text.setContent("亲，您离烤箱就差一小步了！\n\n点击【<a href=\""+url+"\">活动详情</a>】参与抽奖，烤箱天天等您来拿！");
		}
		textCustom.setText(text);
		NewsUtil.send(tokenManager.getSSJAccessToken(), textCustom);
		
	}
	@Override
	public  Map<String,Object> getCardByKeyword(String keyword){
		List<Map<String, Object>> list  = cardQueryDao.getCardByKeyword(keyword);
		return list!=null&& list.size()>0 ? list.get(0):new HashMap<String, Object>();
	}
	@Override
	public List<Map<String, Object>> getWinning(String cardId) {
		return cardQueryDao.getWinning(cardId);
	}
	@Override
	public Page<Map<String, Object>> findAwardLog(
			Map<String, Object> searchParams, Pageable pageable) {
		
		return cardQueryDao.findAwardLog(searchParams, pageable);
	}
	@Override
	public Integer getUserZJLog(String cardId, String userId) {
		return cardDao.getUserZJLog(cardId, userId);
	}
	@Override
	public synchronized CardAward getCardAwardRand(String cardId, Integer count) {
		List<Integer> list =new ArrayList<Integer>();
		list.add(6);
		if(count==0){
			list.add(3);
		}else if(count==1){
			list.add(5);
		}else if(count==2){
			list.add(4);
		}
		CardAward  cardAward = cardAwardService.getCardAwardListByCardIdPracelimit(cardId, list);    
		return cardAward;
	}
	@Override
	public List<Map<String, Object>> zhongjiang(Map<String, Object> searchParams) {
		return cardQueryDao.zhongjiang(searchParams);
	}
	@Override
	public List<Map<String, Object>> exportCJlog(
			Map<String, Object> searchParams) {
		return cardQueryDao.exportCJlog(searchParams);
	}
	
	@Override
	public Integer getCardAwardLog(String cardId,String userId,String begenTime,String endTime){
		Integer everyDayCount=cardDao.getCardAwardLog(cardId, userId, begenTime, endTime);
	    return everyDayCount;
	}

}
