package com.iamberry.wechat.service.giftCard;

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

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

import com.iamberry.wechat.core.entity.PaperBean;
import com.iamberry.wechat.core.entity.admin.ShopSystemRule;
import com.iamberry.wechat.core.entity.giftCard.GiftCardInfo;
import com.iamberry.wechat.core.entity.giftCard.UserMachineInfo;
import com.iamberry.wechat.core.entity.product.ProductColor;
import com.iamberry.wechat.face.giftCard.GiftCardService;
import com.iamberry.wechat.face.mq.EfastOrderService;
import com.iamberry.wechat.service.mapper.AgentMachineMapper;
import com.iamberry.wechat.service.mapper.AgentMapper;
import com.iamberry.wechat.service.mapper.GiftCardMapper;
import com.iamberry.wechat.service.mapper.ProductColorMapper;
import com.iamberry.wechat.service.mapper.SystemMapper;
import com.iamberry.wechat.service.mapper.UserMachineInfoMapper;
import com.iamberry.wechat.core.entity.giftCard.AgentInfo;
import com.iamberry.wechat.core.entity.giftCard.AgentMachine;
import com.iamberry.wechat.core.entity.giftCard.CardCashInfo;
import com.iamberry.wechat.core.entity.giftCard.GiftCardDto;

/**
 * 兑换卡Service实现类
 * @company	深圳爱贝源科技有限公司
 * @website www.iamberry.com
 * @author 	献
 * @tel		18271840547
 * @date	2017年2月16日
 */
@Service
public class GiftCardServiceImpl implements GiftCardService {
	
	@Autowired
	private GiftCardMapper cardMapper;
	
	@Autowired
	private ProductColorMapper colorMapper;
	
	@Autowired
	private UserMachineInfoMapper userMachineInfoMapper;
	
	@Autowired
	private AgentMachineMapper agentMachineMapper;
	
	@Autowired
	private SystemMapper systemMapper;
	
	@Autowired
	private GiftCardService giftCardService;
	
	@Autowired
	private EfastOrderService efastOrderService;
	
	@Autowired
	private AgentMapper agentMapper;

	@Override
	public GiftCardInfo get(String card) {
		// TODO Auto-generated method stub
		return cardMapper.get(card);
	}

	@Override
	public Map<String,Object> salesCard(GiftCardInfo cardInfo, UserMachineInfo machineInfo, AgentInfo agentInfo) throws Exception {
		Map<String,Object> map = new HashMap<String,Object>();
		// 修改礼品卡状态
		cardInfo.setCardPassword(cardInfo.getCardPassword().toUpperCase());
		cardInfo.setCardUseDate(new Date());
		cardInfo.setCardStatus(1);			// 只有未兑换的礼品卡才能兑换
		if (cardMapper.update(cardInfo) < 1) {
			// 礼品卡已经被兑换
			map.put("status", "-1");
			map.put("target", "0");
			return map;
		}

		// 添加兑换信息
		machineInfo.setUserMachineOpenId(agentInfo.getAgentOpenId());
		if (userMachineInfoMapper.add(setUserMachineInfoFromColorInfoTo(machineInfo, machineInfo.getUserMachineColorId(), cardInfo.getCardId())) <= 0) {
			throw new RuntimeException();
		}
		
		//兑换成功后将付费代理商表统计售出礼品卡数量加1
		if (agentMapper.updateAgentCardSum(agentInfo) <= 0) {
			throw new RuntimeException();
		}
		
		// 推送百胜
		try {
			efastOrderService.giftCard(machineInfo.getUserMachineAddressInfo(), "DH00000000" + machineInfo.getUserMachineId(), machineInfo.getUserMachineColorId()
					, machineInfo.getUserMachineAddressName(), machineInfo.getUserMachineAddressTel(), machineInfo.getUserMachineOpenId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return presentMachineAndClearAgentCardNum(agentInfo);
	}
	
	/**
	 * 将产品颜色信息填入用户兑换机器记录中
	 * 2017年3月31日
	 * @author muzx
	 * @param userMachine
	 * @param colorId
	 * @param cardId
	 * @return
	 */
	private UserMachineInfo setUserMachineInfoFromColorInfoTo(UserMachineInfo userMachine, int colorId, int cardId) {
	    ProductColor color = colorMapper.selectProductColorById(colorId);
        if (color == null) {
            throw new RuntimeException();
        }
        userMachine.setUserMachineColorName(color.getColorName());
        userMachine.setUserMachine69code(color.getColor69Code());
        userMachine.setUserMachineCreateDate(new Date());
        userMachine.setUserMachineProductId(color.getColorProductId()); // 产品id
        userMachine.setUserMachineProductName(color.getColorProductName());
        userMachine.setUserMachineStatus(1); // 待发货
        userMachine.setUserMachineTel(userMachine.getUserMachineAddressTel());
        userMachine.setUserMachineCardId(cardId);
	    return userMachine;
	}
	
	/**
	 * 判断该代理商卖出礼品卡总数是否等于需要赠送机器数，如果相等，则赠送一台机器并将代理商统计礼品卡数量重置为0
	 * @time 2017年3月31日
	 * @author muzx
	 * @return 若符合条件并赠送成功则返回true，否则返回false
	 */
	private Map<String,Object> presentMachineAndClearAgentCardNum(AgentInfo agentInfo) throws Exception{
	    Map<String,Object> map = new HashMap<String,Object>();
	    ShopSystemRule shopSystemRule =  systemMapper.selectOneShopRuleById(225);
        if (agentInfo.getAgentIsHudredAgent() == 0 && 
                agentInfo.getAgentCardSum() + 1 >=  shopSystemRule.getRuleNum().intValue()) {
            //将代理商统计礼品卡数量重置为0
            if (agentMapper.updateAgentCardSumZero(agentInfo) <= 0) {
                throw new RuntimeException();
            }
            //赠送一台机器
            AgentMachine agentMachine = new AgentMachine();
            agentMachine.setAgentMachineOpenId(agentInfo.getAgentOpenId());
            agentMachine.setAgentMachineType(3);       //售出8台机器赠送一台
            agentMachine.setAgentMachineStatus(1);
            agentMachine.setAgentMachineRemark("售出一定数量后赠送的机器");
            if (agentMachineMapper.insertAgentMachine(agentMachine) <= 0) {
                throw new RuntimeException();
            }
            map.put("status", "1");
            map.put("target", "1");
            map.put("agentMachineId", agentMachine.getAgentMachineId());
        } else {
            map.put("status", "1");
            map.put("target", "0");
        }
	    return map;
	}
	/**
	 * 批量添加礼品卡信息和赠送的机器物流信息
	 * @param request
	 * @param agentMachine
	 * @return
	 * @throws Exception
	 */
	@Override
	public boolean saveCardAndMachine(int rechargeType, String openId, Integer userMachineId, Integer referrerMachineId) throws Exception {
		//从规则表中获取生成礼品卡的数量
		ShopSystemRule shopSystemRule =  systemMapper.selectOneShopRuleById(222);
		int cardNum = shopSystemRule.getRuleNum().intValue();
		if(rechargeType == 2){
		    shopSystemRule =  systemMapper.selectOneShopRuleById(229);
	        cardNum = shopSystemRule.getRuleNum().intValue();
		}
		List<GiftCardInfo> cardList = new ArrayList<GiftCardInfo>();
		int i = 0;
		while (i < cardNum) {
			//产生7位数随机密码
			String code = this.getPassward(7, 6);
			int num = this.selectCardByPassward(code);
			//判断该密码是否存在，如果存在，则不计入总数，重新生成，如果存在，则添加到List中
			if (num == 0) {
				GiftCardInfo card = new GiftCardInfo();
				card.setCardOpenId(openId);
				card.setCardPassword(code);
				card.setCardStatus(1);
				cardList.add(card);
				i++;
			}
		}
		//添加礼品卡信息和赠送的机器信息
		int num = giftCardService.insertCardAndMachine(cardList, userMachineId, referrerMachineId);
		
		if (num > 0) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 随机生成一个密码
	 * @param len 密码总长度
	 * @param numLen 需要生成数字的总长度
	 * @return
	 */
	public String getPassward(int len,int numLen) {
		StringBuilder sb = new StringBuilder(len);
		Random rnd = new Random();
		int num = 0;
		//除了数字以外的字母的总长度
		if (len >= numLen) {
			num = len - numLen;
		}
		if (num > 0) {
			String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
			int j = 0;
			while (j < num) {
				//生成一个随机的大写字母
				String letter = String.valueOf(chars.charAt((int)(Math.random() * 26)));
				//该大写字母不能是O,I,L等字母，如果是O,I,L则继续生成并且不添加进sb字符串中
				if (!"O".equals(letter) &&  !"I".equals(letter) && !"L".equals(letter)) {
					sb.append(letter);
					j++;
				}
			}
		}
		for (int i = 0; i < numLen; i++)
			sb.append("0123456789".charAt(rnd.nextInt("0123456789".length())));
		return sb.toString();
	}
	

	@Override
	public boolean saveCardList(String openId, int cardNum) {
		// TODO Auto-generated method stub
		List<GiftCardInfo> cardList = new ArrayList<GiftCardInfo>();
		int i = 0;
		while (i < cardNum) {
			//产生7位数随机密码
			String code = this.getPassward(7, 6);
			int num = this.selectCardByPassward(code);
			//判断该密码是否存在，如果存在，则不计入总数，重新生成，如果存在，则添加到List中
			if (num == 0) {
				GiftCardInfo card = new GiftCardInfo();
				card.setCardOpenId(openId);
				card.setCardPassword(code);
				card.setCardStatus(1);
				cardList.add(card);
				i++;
			}
		}
		//批量添加礼品卡信息
		int num = cardMapper.insertGiftCardList(cardList);
		if (num > 0) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Integer insertCardAndMachine(List<GiftCardInfo> cardList,
			Integer userMachineId, Integer referrerMachineId) {
		// TODO Auto-generated method stub
		
		AgentMachine agentMachine = new AgentMachine();
		agentMachine.setAgentMachineId(userMachineId);
		agentMachine.setAgentMachineStatus(2);
		//批量添加礼品卡信息
		Integer num = cardMapper.insertGiftCardList(cardList);
		//给代理商添加赠送机器信息
		Integer sum = agentMachineMapper.updateAgentMachine(agentMachine);
		Integer count = null;
		//如果referrerOpenid不为空，则表示有推荐人
		if (referrerMachineId != null) {
			AgentMachine machine = new AgentMachine();
			machine.setAgentMachineStatus(1);
			machine.setAgentMachineId(referrerMachineId);
			//给推荐人添加赠送机器信息
			count = agentMachineMapper.updateAgentMachine(machine);
		}
		if (num > 0 && sum > 0 && ((count != null && count > 0) || count == null)) {
			return 1;
		} else {
			return 0;
		}
	}

	@Override
	public Integer selectCardByPassward(String cardPassword) {
		// TODO Auto-generated method stub
		return cardMapper.selectCardByPassward(cardPassword);
	}

	@Override
	public GiftCardDto selectCardInfo(GiftCardDto giftCardDto) {
		// TODO Auto-generated method stub
		return cardMapper.selectCardInfo(giftCardDto);
	}

	@Override
	public Integer updateCardStatus(GiftCardDto giftCardDto) {
		// TODO Auto-generated method stub
		return cardMapper.updateCardStatus(giftCardDto);
	}

	@Override
	public boolean applyCash(GiftCardDto giftCardDto, CardCashInfo cardCashInfo) {
		// TODO Auto-generated method stub
		Integer num = cardMapper.updateCardStatus(giftCardDto);
		Integer sum = cardMapper.insertCardCash(cardCashInfo);
		if (num > 0 && sum > 0) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public List<CardCashInfo> selectCardCashList(CardCashInfo cardCashInfo) {
		// TODO Auto-generated method stub
		return cardMapper.selectCardCashList(cardCashInfo);
	}

	@Override
	public Integer selectCardCashCount(CardCashInfo cardCashInfo) {
		// TODO Auto-generated method stub
		int count = cardMapper.selectCardCashCount(cardCashInfo);
		return	count = count % cardCashInfo.getPage().getPageSize() == 0? count/cardCashInfo.getPage().getPageSize():(count/cardCashInfo.getPage().getPageSize())+1;
	}

	@Override
	public Integer updateCardCashStatus(CardCashInfo cardCashInfo) {
		// TODO Auto-generated method stub
		return cardMapper.updateCardCashStatus(cardCashInfo);
	}

	@Override
	public List<GiftCardDto> selectCardList(GiftCardDto giftCardDto) {
		// TODO Auto-generated method stub
		List<GiftCardDto> cardList =  cardMapper.selectCardList(giftCardDto);
		return cardList;
	}

	@Override
	public List<ProductColor> getColor(Integer productId) {
		// TODO Auto-generated method stub
		return colorMapper.getColor(productId);
	}

	@Override
	public List<UserMachineInfo> list(String openid) {
		// TODO Auto-generated method stub
		return userMachineInfoMapper.list(openid);
	}

	@Override
	public List<UserMachineInfo> page(int pageNO, int pageSize) {
		PaperBean bean = new PaperBean();
		bean.setPaperData(pageNO, pageSize);
		return userMachineInfoMapper.page(bean.getMinNum(), bean.getMaxNum());
	}

	@Override
	public int count() {
		// TODO Auto-generated method stub
		return userMachineInfoMapper.count();
	}

	@Override
	public int update(UserMachineInfo info) {
		// TODO Auto-generated method stub
		return userMachineInfoMapper.update(info);
	}

    @Override
    public int countCard(GiftCardDto giftCardDto) {
        return cardMapper.countCard(giftCardDto);
    }
}
