package com.iamberry.wechat.handles.coupon;

import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.iamberry.app.tool.util.Result;
import com.iamberry.wechat.face.coupon.WelfareService;
import com.iamberry.wechat.tools.StrUtils;
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 org.apache.commons.lang.StringUtils;
import com.iamberry.app.tool.log.RatFWLogger;
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.drp.PlaceInfo;
import com.iamberry.wechat.core.entity.drp.PlaceRoleInfo;
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.drp.DrpRoleInfoService;
import com.iamberry.wechat.face.drp.PlaceInfoService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.qrcode.TemporaryQrcodeService;
import com.iamberry.wechat.face.relationship.DealerRelationService;
import com.iamberry.wechat.tools.DateTimeUtil;
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 WechatUtils wechatUtils;
	@Autowired
	private MemberService memberService;
	@Autowired
	private SystemService systemService;
	
	private final 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();
		CouponType ct = new CouponType();
		ct.setPage(new PageBean());
		ct.getPage().setPageSize(pageSize);
		ct.getPage().setPageNumber(pageNO);
		List<CouponType> typeList = new ArrayList<CouponType>();
		PlaceInfo placeInfo = new PlaceInfo();
		PlaceRoleInfo placeRoleInfo = new PlaceRoleInfo();
		Map<String, Object> map = new HashMap<String, Object>();
		
		//去掉已经领取过的
		CouponItemDto couponItemDto = new CouponItemDto();
		try {
			Member member = WechatUtils.getUserBySession(req);
			if(member == null){
				rm.setMessage(ResultInfo.loginOutError);
				return rm;
			}
			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(ResultInfo.SUCCESSINFO);
				return rm;
			}
			typeList = couponTypeService.getCouponTypeList(ct);
			couponItemDto.setUseropenid(member.getUserOpenid());
			List<CouponItemDto> itemList = couponItemService.getCouponItemDtoList(couponItemDto);
			int couponIdWith40 = systemService.selectOneShopRuleById(105).getRuleNum().intValue();
			Iterator 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() < 1){
					it.remove();
					continue;
				}
				//券使用条件为必须关注时，用户没关注则返回
				if(cType.getCouponIsConcern() != null && cType.getCouponIsConcern().intValue() == 1 
						&& member.getUserStatus() != null && member.getUserStatus().intValue() != 2){
					it.remove();
					continue;
				}
				//当前用户是自己关注时，则不能领取40元优惠券 其他新添加的可以领取
				if(member.getUserStatus() != null && member.getUserStatus() == 2 && member.getUserResType() != null && member.getUserResType() == 1){
					if(cType.getCouponId() == null || cType.getCouponId() == couponIdWith40) {
						it.remove();
						continue;
					}
				}
				//当前用户已领取
				for (CouponItemDto cItem : itemList) {
					if(cType.getCouponId() != null && cItem.getCouponId() != null
							&& cType.getCouponId().intValue() == cItem.getCouponId().intValue()){
						it.remove();
						break;
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}

		map.put("typeList", typeList);
		rm.setData(map);
		rm.setStatus(true);
		rm.setResultCode(ResultInfo.SUCCESSCODE);
		rm.setMessage(ResultInfo.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(ResultInfo.ERRORINFO);
		}
		try {
			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;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		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(ResultInfo.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() != 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(ResultInfo.SUCCESSINFO);
		return rm;
	}
	
	/**
	 * 领取某类型的优惠券 总数量减少 优惠券详情表插入数据
	 * @param member
	 * @param couponType
	 * @return
	 */
	private ResultMsg getCouponItem(Member member,CouponType couponType){
		ResultMsg rm = new ResultMsg();
		rm.setStatus(false);
		rm.setMessage(ResultInfo.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 > 0){
			rm.setStatus(true);
			rm.setMessage(ResultInfo.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();
		String useStatus = req.getParameter("useStatus");
		if(StringUtils.isEmpty(useStatus)){
			useStatus = "-1";
		}
		String openid = "";
		try {
			Member member = WechatUtils.getUserBySession(req);
			openid = member.getUserOpenid();
		} catch (Exception e) {
			e.printStackTrace();
		}
		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);
		} else if("3".equals(useStatus)){
			cDto.setEndDate(new Date());
			cDto.setCouponItemRemark("4");
		}

		cDto.setCouponIsGive(1);
		cDto.setPage(new PageBean());
		cDto.getPage().setPageSize(pageSize);
		cDto.getPage().setPageNumber(pageNO);
		cDto.getPage().initRecordBegin();
		cDto.setBeginDate(new Date());
		List<CouponItemDto> 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);
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("itemList", list);
		rm.setData(map);
		rm.setStatus(true);
		rm.setMessage(ResultInfo.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();
		try {
			Member member = WechatUtils.getUserBySession(req);
			member = memberService.getMemberByUserOpenId(member.getUserOpenid());
			couponItemDto.setUseropenid(member.getUserOpenid());
			List<CouponItemDto> itemList = couponItemService.getCouponItemDtoList(couponItemDto);
			Iterator 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() != 2){
					it.remove();
					count--;
					continue;
				}
				//当前用户已领取
				for (CouponItemDto cItem : itemList) {
					if(cType.getCouponId().intValue() == cItem.getCouponId()){
						it.remove();
						count--;
						break;
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
				
		rm.setData(count);
		rm.setStatus(true);
		rm.setResultCode(ResultInfo.SUCCESSCODE);
		rm.setMessage(ResultInfo.SUCCESSINFO);
		return rm;
	}

	/**
	 *  以旧换新 - 是否领取过了
	 * 用户领取优惠券接口
	 * @return
	 */
	@RequestMapping("/isRecCouRen")
	@ResponseBody
	public ResultMsg isRecCouRen(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("未查询到该优惠券！");
		}

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

		CouponItemDto couponItemDto = new CouponItemDto();
		couponItemDto.setCouponId(couponId);
		couponItemDto.setUseropenid(member.getUserOpenid());
		List<CouponItemDto> couponItemDtoList = couponItemService.getCouponItemDtoList(couponItemDto);
		if(couponItemDtoList != null && couponItemDtoList.size() > 0){
			rm.setStatus(true);
			rm.setData(couponItemDtoList.size());
			rm.setMessage("查询成功");
		}else{
			rm.setStatus(false);
			rm.setResultCode(ResultInfo.ERRORCODE);
			rm.setMessage("查询失败！请重试或在微信公众号咨询客服");
		}
		return rm;
	}

	/**
	 *  以旧换新
	 * 用户领取优惠券接口
	 * @return
	 */
	@RequestMapping("/recCouRen")
	@ResponseBody
	public ResultMsg recCouRen(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("未查询到该优惠券！");
		}

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

		try {
			synchronized (lock) {
				CouponType couponType = couponTypeService.getCouponTypeById(couponId);
				rm = checkCoupon(member, couponType);
				if(rm.isStatus()){
					//减少总数
					int i = couponTypeService.updateCouponTypeForItem(couponType.getCouponId());
					//增加单张优惠券
					CouponItem couponItem = new CouponItem();
					couponItem.setCouponItemUseropenid(member.getUserOpenid());
					couponItem.setCouponId(couponType.getCouponId());
					couponItem.setCouponUseStatus(1);
					Calendar calendar = Calendar.getInstance();
					calendar.set(2019,3,18);
					calendar.set(Calendar.HOUR_OF_DAY,23);
					calendar.set(Calendar.MINUTE,59);
					calendar.set(Calendar.SECOND,58);
					couponItem.setCouponUseEndDate(calendar.getTime());

					Integer j = couponItemService.insertCouponItem(couponItem);

					rm.setStatus(true);
					rm.setResultCode(ResultInfo.SUCCESSCODE);
					rm.setMessage("领取成功！");
					return rm;
				}else{
					return rm;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		rm.setStatus(false);
		rm.setResultCode(ResultInfo.ERRORCODE);
		rm.setMessage("领取失败！请重试或在微信公众号咨询客服");
		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);
		calendar.add(Calendar.DATE,couponType.getCouponGetDays());
		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;
			}
		}
	}

}
