package com.iamberry.wechat.handles.coupon;

import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.dubbo.remoting.exchange.ExchangeServer;
import com.iamberry.wechat.core.entity.coupon.Exchange;
import com.iamberry.wechat.face.coupon.ExchangeService;
import com.iamberry.wechat.tools.StrUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.iamberry.wechat.core.entity.PageBean;
import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.WechatUtils;
import com.iamberry.wechat.core.entity.coupon.CouponItem;
import com.iamberry.wechat.core.entity.coupon.CouponItemDto;
import com.iamberry.wechat.core.entity.coupon.CouponType;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.coupon.CouponItemService;
import com.iamberry.wechat.face.coupon.CouponTypeService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.tools.DateTimeUtil;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.ResultInfo;

/**
 * 优惠券类型 前台接口 2016年7月6日
 * @author 穆再兴
 */
@Controller
@RequestMapping("/wechat/coupon")
public class CouponTypeHandler {
	@Autowired
	private CouponTypeService couponTypeService;
	@Autowired
	private CouponItemService couponItemService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private ExchangeService exchangeService;

	private static Logger logger = LoggerFactory.getLogger(CouponTypeHandler.class);
	/**
	 * 领取优惠券的锁
	 */
	private Object lock = new Object();

	/**
	 * 分页查询优惠券类型列表<当前用户可领取的> 2016年7月6日
	 * 
	 * @param pageSize
	 * @param pageNO
	 * @return
	 */
	@RequestMapping("/couponTypeList")
	@ResponseBody
	public ResultMsg getCouponTypeList(
			HttpServletRequest req,
			@RequestParam(value = "pageSize", defaultValue = "6", required = false) Integer pageSize,
			@RequestParam(value = "pageNO", defaultValue = "1", required = false) Integer pageNO) {
		ResultMsg rm = new ResultMsg();
		List<CouponType> typeList = new ArrayList<CouponType>();
		Map<String, Object> map = new HashMap<String, Object>();

		// 去掉已经领取过的
		CouponItemDto couponItemDto = new CouponItemDto();

		Member member = WechatUtils.getUserBySession(req);
		member = memberService.getMemberByUserOpenId(member.getUserOpenid());

		String typeIdStr = req.getParameter("typeId");
		logger.info("----------typeIdStr-----------" + typeIdStr);
		if (typeIdStr.indexOf("?") > -1) {
			typeIdStr = StringUtils.split(typeIdStr, "?")[0];
		}
		int couponTypeId = Integer.parseInt(typeIdStr);

		// 如果当前用户来自金牌会员，并且优惠券的ID为400元，那么屏蔽
		int templateId = systemService.selectOneShopRuleById(114).getRuleNum()
				.intValue();
		if (member.getTemplateId() == templateId) {
			map.put("typeList", typeList);
			rm.setData(map);
			rm.setStatus(true);
			rm.setResultCode(ResultInfo.SUCCESSCODE);
			rm.setMessage(NameUtils.getConfig("SUCCESSINFO"));
			return rm;
		}

		CouponType couponType = couponTypeService
				.getCouponTypeById(couponTypeId);
		typeList.add(couponType);

		couponItemDto.setUseropenid(member.getUserOpenid());
		List<CouponItemDto> itemList = couponItemService
				.getCouponItemDtoList(couponItemDto);
		Iterator<CouponType> it = typeList.iterator();
		while (it.hasNext()) {
			CouponType cType = (CouponType) it.next();
			Date now = new Date();
			// 券已过期
			if (cType.getCouponEndDate() != null
					&& cType.getCouponEndDate().before(now)) {
				it.remove();
				continue;
			}
			// 券已领完
			if (cType.getCouponRemainingNum() != null
					&& cType.getCouponRemainingNum().intValue() < 1) {
				it.remove();
				continue;
			}
			// 券使用条件为必须关注时，用户没关注则返回
			if (cType.getCouponIsConcern() != null
					&& cType.getCouponIsConcern().intValue() == 1
					&& member.getUserStatus() != null
					&& member.getUserStatus().intValue() != 2) {
				it.remove();
				continue;
			}
			// 当前用户已领取
			for (CouponItemDto cItem : itemList) {
				if (cType.getCouponId() != null
						&& cItem.getCouponId() != null
						&& cType.getCouponId().intValue() == cItem
								.getCouponId().intValue()) {
					it.remove();
					break;
				}
			}
		}

		map.put("typeList", typeList);
		rm.setData(map);
		rm.setStatus(true);
		rm.setResultCode(ResultInfo.SUCCESSCODE);
		rm.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		return rm;
	}

	/**
	 * 用户领取优惠券接口 2016年7月6日
	 * @author 穆再兴
	 * @return
	 */
	@RequestMapping("/getCoupon")
	@ResponseBody
	public ResultMsg getCoupon(HttpServletRequest req,
			@RequestParam(value = "couponId", required = false) Integer couponId) {
		ResultMsg rm = new ResultMsg();
		if (couponId == null) {
			rm.setStatus(false);
			rm.setResultCode(ResultInfo.ERRORCODE);
			rm.setMessage(NameUtils.getConfig("ERRORINFO"));
		}

		Member member = WechatUtils.getUserBySession(req);
		member = memberService.getMemberByUserOpenId(member.getUserOpenid());
		synchronized (lock) {
			CouponType ct = couponTypeService.getCouponTypeById(couponId);
			rm = checkCoupon(member, ct);
			if (rm.isStatus()) {
				rm = getCouponItem(member, ct);
				return rm;
			} else {
				return rm;
			}
		}
	}

	/**
	 * 校验某用户是否符合领取优惠券条件
	 * 
	 * @param member
	 * @param couponType
	 * @return
	 */
	private ResultMsg checkCoupon(Member member, CouponType couponType) {
		ResultMsg rm = new ResultMsg();
		rm.setStatus(false);
		if (member == null || couponType == null) {
			rm.setMessage(NameUtils.getConfig("ERRORINFO"));
			return rm;
		}
		Date now = new Date();
		// 券已过期
		if (couponType.getCouponEndDate() != null
				&& couponType.getCouponEndDate().before(now)) {
			rm.setMessage("本次优惠券领取已结束!");
			return rm;
		}
		// 券已领完
		if (couponType.getCouponRemainingNum() < 1) {
			rm.setMessage("本次优惠券已被抢完,欢迎下次再来~");
			return rm;
		}
		// 券使用条件为必须关注时，用户没关注则返回
		if (couponType.getCouponIsConcern() == 1
				&& member.getUserStatus() != null
				&& member.getUserStatus().intValue() != 2) {
			rm.setMessage("请先关注公众号!");
			return rm;
		}
		// 已经领取过
		CouponItemDto couponItemDto = new CouponItemDto();
		couponItemDto.setCouponId(couponType.getCouponId());
		couponItemDto.setUseropenid(member.getUserOpenid());
		List<CouponItemDto> list = couponItemService
				.getCouponItemDtoList(couponItemDto);
		if (list != null && list.size() >= couponType.getCouponGetLimit()) {
			rm.setMessage("该优惠券您已全部领取,请勿重复领取!");
			return rm;
		}
		// 待加条件：是否必须购买 消费总金额要求（满足这个条件才能领券）
		rm.setStatus(true);
		rm.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		return rm;
	}

	/**
	 * 领取某类型的优惠券 总数量减少 优惠券详情表插入数据
	 * 
	 * @param member
	 * @param couponType
	 * @return
	 */
	private ResultMsg getCouponItem(Member member, CouponType couponType) {
		ResultMsg rm = new ResultMsg();
		rm.setStatus(false);
		rm.setMessage(NameUtils.getConfig("ERRORINFO"));
		// 减少总数
		int i = couponTypeService.updateCouponTypeForItem(couponType
				.getCouponId());

		// 增加单张优惠券
		CouponItem couponItem = new CouponItem();
		couponItem.setCouponItemUseropenid(member.getUserOpenid());
		couponItem.setCouponId(couponType.getCouponId());
		couponItem.setCouponUseStatus(1); // 使用状态:未使用
		Date endDate = DateTimeUtil.addHour(DateTimeUtil.now(),
				couponType.getCouponLimitHours()); // 券的过期时间
		if (endDate.before(couponType.getCouponEndDate())) { // 券的过期时间早于此类型券的截止时间则取券的过期时间
			couponItem.setCouponUseEndDate(endDate);
		} else { // 券的过期时间晚于此类型券的截止时间则取此类型券的截止时间
			couponItem.setCouponUseEndDate(couponType.getCouponEndDate());
		}
		Integer j = couponItemService.insertCouponItem(couponItem);

		if (i > 0 && j != null && j.intValue() > 0) {
			rm.setStatus(true);
			rm.setMessage(NameUtils.getConfig("SUCCESSINFO"));
			rm.setData(couponItem);
		}
		return rm;
	}

	/**
	 * 当前用户各种状态优惠券列表 2016年7月7日
	 * 
	 * @param req
	 * @param pageSize
	 * @param pageNO
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/couponItemList")
	public ResultMsg getCouponItemList(
			HttpServletRequest req,
			@RequestParam(value = "pageSize", defaultValue = "6", required = false) Integer pageSize,
			@RequestParam(value = "pageNO", defaultValue = "1", required = false) Integer pageNO) {
		ResultMsg rm = new ResultMsg(false,  ResultMsg.ERROR, "查询失败!",null);
		List<CouponItemDto> list = new ArrayList<CouponItemDto>();
		Map<String, Object> map = new HashMap<String, Object>();
		String useStatus = req.getParameter("useStatus");
		if (StringUtils.isEmpty(useStatus)) {
			map.put("itemList", list);
			rm.setData(map);
			return rm;
		}
		String openid = "";
		Member member = WechatUtils.getUserBySession(req);
		openid = member.getUserOpenid();

		System.out.println("============查看优惠券页面："+openid+"参数："+useStatus);
		logger.info("============查看优惠券页面："+openid+"参数："+useStatus);

		CouponItemDto cDto = new CouponItemDto();
		cDto.setUseropenid(openid);
//		if ("1".equals(useStatus)) { // 未使用的优惠券
//			cDto.setCouponUseStatus(Integer.parseInt(useStatus));
//			cDto.setBeginDate(new Date());
//		} else if ("2".equals(useStatus)) { // 已使用的优惠券
//			cDto.setCouponUseStatus(Integer.parseInt(useStatus));
//			cDto.setCouponReduce(7); // 加上了订单是待支付 即couponUseStatus是7的优惠券
//		} else if ("3".equals(useStatus)) { // 已过期的优惠券
//			cDto.setEndDate(new Date());
//			cDto.setCouponItemRemark("4"); // 需去掉已经使用的优惠券
//		}
		if ("10".equals(useStatus)) {
			//优惠券
			cDto.setCouponUseStatus(0);
			cDto.setCouponType(10);
			cDto.setBeginDate(new Date());
		}else if("11".equals(useStatus)){
			//兑换券
			cDto.setCouponUseStatus(0);
			cDto.setCouponType(11);
			cDto.setBeginDate(new Date());
		}
		cDto.setPage(new PageBean());
		cDto.getPage().setPageSize(pageSize);
		cDto.getPage().setPageNumber(pageNO);
		list = couponItemService.getCouponItemDtoList(cDto);

		Date now = new Date();
		for (CouponItemDto itemDto : list) { // 为了在全部优惠券页面区分已过期的优惠券，使之不能使用
			itemDto.setCouponItemRemark(ResultInfo.COUPONITEMSTATUS_NORMAL);
			if (itemDto.getCouponUseEndDate() != null
					&& itemDto.getCouponUseEndDate().before(now)) {
				itemDto.setCouponItemRemark(ResultInfo.COUPONITEMSTATUS_PASSED);
			}
			if(itemDto.getCouponType().equals(3)){
				Exchange exchange = new Exchange();
				exchange.setCouponId(itemDto.getCouponId());
				List<Exchange> exchangeList = exchangeService.getExchangeList(exchange);
				if(exchangeList != null && exchangeList.size() > 0){
					itemDto.setExchange(exchangeList.get(0));
				}
			}
		}
		rm = new ResultMsg(true, ResultMsg.SUCCESS, "查询成功!",null);
		map.put("itemList", list);
		rm.setData(map);
		rm.setStatus(true);
		rm.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		return rm;
	}

	/**
	 * 当前用户可领取的优惠券数 2016年7月11日
	 * 
	 * @return
	 */
	@RequestMapping("/getNewCouponType")
	@ResponseBody
	public ResultMsg getCouponTypeCount(HttpServletRequest req) {
		ResultMsg rm = new ResultMsg();
		CouponType ct = new CouponType();
		ct.setPage(new PageBean());
		List<CouponType> typeList = couponTypeService.getCouponTypeList(ct);
		Integer count = couponTypeService.getCouponTypeCount();

		// 去掉已经领取过的
		CouponItemDto couponItemDto = new CouponItemDto();

		Member member = WechatUtils.getUserBySession(req);
		member = memberService.getMemberByUserOpenId(member.getUserOpenid());
		couponItemDto.setUseropenid(member.getUserOpenid());
		List<CouponItemDto> itemList = couponItemService
				.getCouponItemDtoList(couponItemDto);
		Iterator<CouponType> it = typeList.iterator();
		while (it.hasNext()) {
			CouponType cType = (CouponType) it.next();
			Date now = new Date();
			// 券已过期
			if (cType.getCouponEndDate() != null
					&& cType.getCouponEndDate().before(now)) {
				it.remove();
				count--;
				continue;
			}
			// 券已领完
			if (cType.getCouponRemainingNum() < 1) {
				it.remove();
				count--;
				continue;
			}
			// 券使用条件为必须关注时，用户没关注则返回
			if (cType.getCouponIsConcern() == 1
					&& member.getUserStatus() != null
					&& member.getUserStatus().intValue() != 2) {
				it.remove();
				count--;
				continue;
			}
			// 当前用户已领取
			for (CouponItemDto cItem : itemList) {
				if (cType.getCouponId() == cItem.getCouponId()) {
					it.remove();
					count--;
					break;
				}
			}
		}

		rm.setData(count);
		rm.setStatus(true);
		rm.setResultCode(ResultInfo.SUCCESSCODE);
		rm.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		return rm;
	}

	/**
	 * 分页查询优惠券类型列表<当前用户可领取的> 2016年7月6日
	 * 
	 * @param pageSize
	 * @param pageNO
	 * @return
	 */
	@RequestMapping("/get_coupon_type")
	@ResponseBody
	public ResultMsg getCouponTypeById(HttpServletRequest req) {
		ResultMsg rm = new ResultMsg();

		List<CouponType> typeList = new ArrayList<CouponType>();
		Map<String, Object> map = new HashMap<String, Object>();

		// 去掉已经领取过的
		CouponItemDto couponItemDto = new CouponItemDto();

		Member member = WechatUtils.getUserBySession(req);
		member = memberService.getMemberByUserOpenId(member.getUserOpenid());

		// 如果该用户直接上级是门店或是母婴店，则不能领取优惠券
		if (member.getUserResType() == 3) {
			map.put("typeList", typeList);
			rm.setData(map);
			rm.setStatus(true);
			rm.setResultCode(ResultInfo.SUCCESSCODE);
			rm.setMessage(NameUtils.getConfig("SUCCESSINFO"));
			return rm;
		}

		int couponTypeId = Integer.parseInt(req.getParameter("typeId"));

		CouponType couponType = couponTypeService
				.getCouponTypeById(couponTypeId);
		typeList.add(couponType);

		couponItemDto.setUseropenid(member.getUserOpenid());
		List<CouponItemDto> itemList = couponItemService
				.getCouponItemDtoList(couponItemDto);
		Iterator<CouponType> it = typeList.iterator();
		while (it.hasNext()) {
			CouponType cType = (CouponType) it.next();
			Date now = new Date();
			// 券已过期
			if (cType.getCouponEndDate() != null
					&& cType.getCouponEndDate().before(now)) {
				it.remove();
				continue;
			}
			// 券已领完
			if (cType.getCouponRemainingNum() != null
					&& cType.getCouponRemainingNum().intValue() < 1) {
				it.remove();
				continue;
			}
			// 券使用条件为必须关注时，用户没关注则返回
			if (cType.getCouponIsConcern() != null
					&& cType.getCouponIsConcern().intValue() == 1
					&& member.getUserStatus() != null
					&& member.getUserStatus().intValue() != 2) {
				it.remove();
				continue;
			}
			// 当前用户已领取
			for (CouponItemDto cItem : itemList) {
				if (cType.getCouponId() != null
						&& cItem.getCouponId() != null
						&& cType.getCouponId().intValue() == cItem
								.getCouponId().intValue()) {
					it.remove();
					break;
				}
			}
		}

		map.put("typeList", typeList);
		rm.setData(map);
		rm.setStatus(true);
		rm.setResultCode(ResultInfo.SUCCESSCODE);
		rm.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		return rm;
	}

	/**
	 * 校验当前用户是否符合使用优惠券条件
	 * 
	 * @return
	 */
	@RequestMapping("/checkCurrentPreferential")
	@ResponseBody
	private ResultMsg checkCurrentPreferential(HttpServletRequest req) {
		ResultMsg rm = new ResultMsg();
		Member member = WechatUtils.getUserBySession(req);
		rm.setStatus(false);
		rm.setMessage("当前用户非金牌会员下线");
		// 查询金牌会员模板id
		int templateId = systemService.selectOneShopRuleById(114).getRuleNum()
				.intValue();
		// 查询用户信息
		Member user = memberService.getMemberByUserOpenId(member
				.getUserOpenid());
		if (user == null) {
			rm.setMessage(ResultInfo.loginOutError);
			rm.setStatus(false);
			return rm;
		}
		// 判断是否为金牌会员下线，如果是，则以优惠价显示，如果不是则按原价显示
		if (user.getUserDealers() != null && user.getTemplateId() != null
				&& templateId == user.getTemplateId().intValue()
				&& user.getUserResType() == 3) {
			rm.setMessage(NameUtils.getConfig("SUCCESSINFO"));
			rm.setStatus(true);
		}
		return rm;
	}

	/**
	 * 用户领取优惠券接口
	 * @return
	 */
	@RequestMapping("/receive_coupon_end")
	@ResponseBody
	public ResultMsg myReceiveCouponEnd(HttpServletRequest req,@RequestParam(value = "couponId", required = false) Integer couponId) {
		ResultMsg rm = new ResultMsg();
		Member member = WechatUtils.getUserBySession(req);
		member = memberService.getMemberByUserOpenId(member.getUserOpenid());

		CouponType couponType = couponTypeService.getCouponTypeById(couponId);
		Date date = new Date();
		if(!date.before(couponType.getCouponEndDate())){
			rm.setStatus(false);
			rm.setMessage("该券已过期！");
			return rm;
		}

		CouponItemDto couponItemDto = new CouponItemDto();
		couponItemDto.setUseropenid(member.getUserOpenid());
		couponItemDto.setCouponId(couponId);
		List<CouponItemDto> couponItemDtoList = couponItemService.getCouponItemDtoList(couponItemDto);
		if(couponItemDtoList != null && couponItemDtoList.size() >= couponType.getCouponGetLimit()){
			rm.setStatus(false);
			rm.setMessage("已经领取过该优惠券了！");
			return rm;
		}

		Calendar calendar = Calendar.getInstance();
		calendar.set(2019,10,11,23,59,57);
		synchronized (lock) {
			//创建优惠券
			CouponItem couponItem = new CouponItem();
			String uuidStr = StrUtils.getUUID();
			couponItem.setCouponItemId(uuidStr);
			couponItem.setCouponItemUseropenid(member.getUserOpenid());
			couponItem.setCouponId(couponType.getCouponId());
			couponItem.setCouponReceiveDate(new Date());
			couponItem.setCouponUseEndDate(calendar.getTime());
			couponItem.setCouponUseStatus(1);
			couponItem.setCouponItemRemark(couponType.getCouponRemark());
			Integer flag = couponItemService.insertCouponItem(couponItem);
			if(flag < 1){
				rm.setStatus(false);
				rm.setMessage("领取优惠券失败！");
				return rm;
			}else{
				rm.setStatus(false);
				rm.setMessage("领取成功！");
				return rm;
			}
		}
	}
}
