package com.iamberry.wechat.service.cart;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.iamberry.app.tool.log.RatFWLogger;
import com.iamberry.wechat.core.entity.eo.GiftPool;
import com.iamberry.wechat.core.entity.eo.ItemGift;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.product.ProductColor;
import com.iamberry.wechat.core.entity.product.ProductFittings;
import com.iamberry.wechat.core.entity.product.SalesUserGift;
import com.iamberry.wechat.face.eo.GiftPoolService;
import com.iamberry.wechat.face.eo.ItemGiftService;
import com.iamberry.wechat.face.ism.IntegralLogService;
import com.iamberry.wechat.face.order.AdminOrderService;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.tools.SendMessageUtil;
import org.apache.commons.lang.StringUtils;
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.cart.CartDto;
import com.iamberry.wechat.core.entity.cart.ShopOrderAndItemDto;
import com.iamberry.wechat.core.entity.cart.ShopOrderItemDto;
import com.iamberry.wechat.core.entity.cart.ShopSalesOrderDto;
import com.iamberry.wechat.core.entity.coupon.CouponItem;
import com.iamberry.wechat.core.entity.coupon.CouponType;
import com.iamberry.wechat.core.entity.mq.MQMessage;
import com.iamberry.wechat.core.entity.order.Order;
import com.iamberry.wechat.core.entity.order.OrderItem;
import com.iamberry.wechat.face.cart.CartService;
import com.iamberry.wechat.face.cart.ProductInfoService;
import com.iamberry.wechat.face.coupon.CouponItemService;
import com.iamberry.wechat.face.coupon.CouponTypeService;
import com.iamberry.wechat.face.member.CashLogService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.reback.RebackServices;
import com.iamberry.wechat.service.cart.dao.CartDao;
import com.iamberry.wechat.service.order.dao.AdminOrderDao;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CartServiceImpl implements CartService {

	@Autowired
	private CartDao cartDao;
	
	@Autowired
	private AdminOrderDao adminOrderDao;
	@Autowired
	private MemberService memberService;
	@Autowired
	CouponItemService couponItemService;
	@Autowired
	CouponTypeService couponTypeService;
	@Autowired
	CashLogService cashLogService;
	@Autowired
	private RebackServices rebackServices;
	@Autowired
	ProductInfoService productInfoService;
	@Autowired
	private AdminOrderService adminOrderService;
	@Autowired
	private RatFWLogger logger;
	@Autowired
	private SendMessageUtil sendMessageUtil;
	@Autowired
	private GiftPoolService giftPoolService;
	@Autowired
	private ItemGiftService itemGiftService;
	@Autowired
	private IntegralLogService integralLogService;
	
	
	@Override
	public List<CartDto> selectCartByOpenId(String openId) {
		// TODO Auto-generated method stub
		return cartDao.selectCartByOpenId(openId);
	}

	@Override
	public Integer getCartNumByCartOpenId(String openId) {
		// TODO Auto-generated method stub
		return cartDao.getCartNumByCartOpenId(openId);
	}

	@Override
	public Integer updateCartByOpenId(CartDto cartDto) {
		// TODO Auto-generated method stub
		return cartDao.updateCartByOpenId(cartDto);
	}

	@Override
	public Integer getCartNumByOpenId(CartDto cartDto) {
		// TODO Auto-generated method stub
		return cartDao.getCartNumByOpenId(cartDto);
	}

	@Override
	public CartDto getCartByCartProductId(CartDto cartDto) {
		// TODO Auto-generated method stub
		return cartDao.getCartByCartProductId(cartDto);
	}

	@Override
	public Integer addProductToCart(CartDto cartDto) {
		// TODO Auto-generated method stub

		//根据颜色id获取商品id
		if(cartDto.getCartIsSource() == 1){ //商品来源   1：产品颜色表   2：配件表
			ProductColor productColor = new ProductColor();
			productColor.setColorId(cartDto.getCartColorId());
			productColor = productInfoService.getProductColor(productColor);
			if (productColor == null) {
				return 0;
			}
			cartDto.setCartProductId(productColor.getColorProductId());
		}else{
			ProductFittings productFittings = new ProductFittings();
			productFittings.setFittingsId(cartDto.getCartColorId());
			productFittings = productInfoService.getProductFittings(productFittings);
			if(productFittings == null){
				return 0;
			}
		}
		Integer num = cartDao.addProductToCart(cartDto);
		if (num > 0) {
			return cartDto.getCartId();
		} else {
			return num;
		}
	}

	@Override
	public Integer deleteCartByCartId(CartDto cartDto) {
		// TODO Auto-generated method stub
		return cartDao.deleteCartByCartId(cartDto);
	}

	@Override
	public List<ShopOrderAndItemDto> selectShopOrder(PaperBean paperBean) {
		// TODO Auto-generated method stub
		return cartDao.selectShopOrder(paperBean);
	}

	@Override
	public List<ShopOrderItemDto> selectShopOrderItem(String itemSalesOrderid) {
		// TODO Auto-generated method stub
		return cartDao.selectShopOrderItem(itemSalesOrderid);
	}

	@Override
	public ShopSalesOrderDto getShopOrderByOrderId(String salesOrderId,
			String salesOpenId) {
		// TODO Auto-generated method stub
		return cartDao.getShopOrderByOrderId(salesOrderId, salesOpenId);
	}

	@Override
	public List<CartDto> selectCartItemByListId(Integer[] carts) {
		// TODO Auto-generated method stub
		return cartDao.selectCartItemByListId(carts);
	}

	@Override
	public List<CartDto> listCartByIds(Integer[] carts) {
		return cartDao.listCartByIds(carts);
	}

	@Override
	public CartDto selectCartProductColor(CartDto cartDto) {
		return cartDao.selectCartProductColor(cartDto);
	}

	@Override
	public CartDto getCartProductFitting(CartDto cartDto) {
		return cartDao.getCartProductFitting(cartDto);
	}

	@Override
	@Transactional
	public boolean addOrderAndSaveOrderItem(Order order, List<OrderItem> items, List<Integer> cartIds) throws Exception {
		// TODO Auto-generated method stub
		int count = cartDao.insertOrderInfo(order);
		if (count < 1) {
			throw new RuntimeException("添加订单失败");
		}
		for (OrderItem oi: items) {
			count = cartDao.save(oi);
			if (count < 1) {
				throw new RuntimeException("添加订单项失败");
			}

			if(oi.getItemGiftList() != null && oi.getItemGiftList().size() > 0){
				for (ItemGift ig : oi.getItemGiftList()) {
					ig.setItemId(oi.getItemId());

					GiftPool giftPool = new GiftPool();
					giftPool.setGiftPoolId(ig.getGiftPoolId());
					giftPool.setGiftPoolStock(ig.getItemGiftNum());
					count = giftPoolService.updateStock(giftPool);
					if (count < 1) {
						throw new RuntimeException("修改订单项关联赠品库存失败");
					}
				}

				count = itemGiftService.saveList(oi.getItemGiftList());
				if (count < 1) {
					throw new RuntimeException("添加订单项赠品失败");
				}
			}
		}

		//订单结算使用积分
		if(order.getSalesIntegralNum() > 0){
			count = integralLogService.muOrderChangIntegra(order);
			if (count < 1) {
				throw new RuntimeException("积分使用失败");
			}
		}

		// 删除购物车项目
		cartDao.deleteBatchCartListById(cartIds);
		return true;
	}

	@Override
	public Integer updateOrderStatus(Order order) {
		// TODO Auto-generated method stub
		return cartDao.updateOrderStatus(order);
	}

	@Override
	public Integer selectOrderStatusByOrderId(String orderId) {
		// TODO Auto-generated method stub
		return cartDao.selectOrderStatusByOrderId(orderId);
	}

	@Override
	public ShopSalesOrderDto getOpenIdAndStatus(String salesOrderid) {
		// TODO Auto-generated method stub
		return cartDao.getOpenIdAndStatus(salesOrderid);
	}

	@Override
	public Integer updateOrderByOrderId(Order order) {
		// TODO Auto-generated method stub
		return cartDao.updateOrderByOrderId(order);
	}

	@Override
	public Order selectOrderInfoById(Order order) {
		// TODO Auto-generated method stub
		return cartDao.selectOrderInfoById(order);
	}

	@Override
	public Integer getOrderNumByOpenId(PaperBean paperBean) {
		// TODO Auto-generated method stub
		return cartDao.getOrderNumByOpenId(paperBean);
	}

	@Override
	public ShopSystemRule getReluByRid(Integer rId) {
		// TODO Auto-generated method stub
		return adminOrderDao.getReluByRid(rId);
	}
	
	/**
	 * 根据单号查询该订单的产品总数 
	 * 2016年5月18日
	 * @param orderid
	 * @return
	 */
	public Integer getItemNumByOrderId(String orderid){
		return cartDao.getItemNumByOrderId(orderid);
	}
	
	/**
	 * 用于支付后的修改优惠券状态 及其订单状态状态的回调函数
	 * @author 欧阳明
	 * @return
	 * 
	 */
	public Boolean supdateStateByOrderId(MQMessage QMessage){
		Order order=new Order();
		order.setSalesOrderid(QMessage.getServiceToMessage());
		order=cartDao.selectOrderInfoById(order);
		productInfoService.updateProductNumList(QMessage.getServiceToMessage());
		//添加到返利表
		return rebackServices.loadSingleOrderReward(order)>0;
	}

	@Override
	public CouponType getCouponReduceByItemId(CouponItem couponItem) {
		// TODO Auto-generated method stub
		return cartDao.getCouponReduceByItemId(couponItem);
	}

	@Override
	public List<ShopSalesOrderDto> getOrderList(
			ShopSalesOrderDto shopSalesOrderDto) {
		// TODO Auto-generated method stub
		return cartDao.getOrderList(shopSalesOrderDto);
	}
	
	public Order getOrderRecentAddress(String openid){
		return cartDao.getRecentOrderAddress(openid);
	}

	@Override
	public List<SalesUserGift> listGift(Integer cartColorId) {
		return cartDao.listGift(cartColorId);
	}

	@Override
	public List<SalesUserGift> listSelectGift(SalesUserGift gift) {
		return cartDao.listSelectGift(gift);
	}

	@Override
	public Integer updateSendWarnNum(Order order) {
		return cartDao.updateSendWarnNum(order);
	}

	@Override
	public CartDto getCartByOpenId(CartDto cartDto) {
		return cartDao.getCartByOpenId(cartDto);
	}

	@Override
	public Map<String, Object> updateOrderStatus(String orderId, Integer status, String remark, int operation) {
		Map<String, Object> map = new HashMap<String, Object>();
		String txtOpera = getOrderOperation(operation);//获取操作信息
		boolean flag = false;
		StringBuilder msg = new StringBuilder();
		Order order = new Order();
		order.setSalesOrderid(orderId);
		order.setOldStatus(status);
		if (StringUtils.isNotEmpty(remark)) {
			order.setSalesReturnDes(remark);
		}
		switch (status) {	//通过原始订单状态分配可执行的操作
			case 1: //待支付
				if (operation == 1) {	//取消订单
					order.setSalesStatus(0);	//订单取消
					//修改订单状态
					int num = cartDao.updateOrderByOrder(order);
					if (num > 0) {
						flag = true;
					}
				} else {
					msg.append("该订单不支持");
					msg.append(txtOpera);
					msg.append("操作,请重新确认!");
				}
				break;
			case 2:	//已支付待发货
				if (operation == 2) {	//申请退款
					order.setSalesStatus(3);	//退款申请中
					//修改订单状态
					int num = cartDao.updateOrderByOrder(order);
					if (num > 0) {
						//推送微信发货消息
						//给用户发送消息-已发货的通知
						DecimalFormat df=new DecimalFormat("0.00");
						Order order2 = adminOrderService.selectOrderStatusByOrderId(order.getSalesOrderid());
						String payMoney = df.format((float)order2.getSalesYetAmount()/100) + "元";
						//获取当前订单订单项
						List<OrderItem> itemList = adminOrderService.getShopOrderItemByOrderId(order.getSalesOrderid());
						try {
							sendMessageUtil.orderApplyRefund(
									"尊敬的用户，我们已收到您的退款申请，我们正在积极处理：",
									payMoney,
									itemList.get(0).getItemProductName(),
									order.getSalesOrderid(),
									remark,	//退款备注
									ResultInfo.sendRemark1,
									order2.getSalesOpenid(),
									ResultInfo.ORDER_DETAIL+order.getSalesOrderid()
							);
						} catch (Exception e) {
							logger.info("订单号："+ orderId +"的订单驳回退款，发送微信消息失败!");
						}
						flag = true;
					}
				} else {
					msg.append("该订单不支持");
					msg.append(txtOpera);
					msg.append("操作,请重新确认!");
				}
				break;
			case 3:	//退款申请中
				if (operation == 3) {	//取消退款
					order.setSalesStatus(2);	//已支付，待发货
					//修改订单状态
					int num = cartDao.updateOrderByOrder(order);
					if (num > 0) {
						flag = true;
					}
				} else {
					msg.append("该订单不支持");
					msg.append(txtOpera);
					msg.append("操作,请重新确认!");
				}
				break;
			case 5:	//已发货
				if (operation == 4) {	//申请退货
					order.setSalesStatus(6);	//申请退货中
					//修改订单状态
					int num = cartDao.updateOrderByOrder(order);
					if (num > 0) {
						DecimalFormat df=new DecimalFormat("0.00");
						Order order2 = adminOrderService.selectOrderStatusByOrderId(order.getSalesOrderid());
						//获取当前订单订单项
						List<OrderItem> itemList = adminOrderService.getShopOrderItemByOrderId(orderId);
						String payMoney = df.format((float)order2.getSalesYetAmount()/100) + "元";
						int productNum = 0;
						for (OrderItem item : itemList) {
							productNum += item.getItemNum();
						}
						try {
							sendMessageUtil.orderApplyReturn(
									"尊敬的用户，已收到您的【退货申请】",
									orderId,
									orderId,
									itemList.get(0).getItemProductName(),
									productNum+"件",
									payMoney,
									ResultInfo.returnRemark,
									order2.getSalesOpenid(),
									ResultInfo.ORDER_DETAIL+orderId
							);
						} catch (Exception e) {
							logger.info("订单号："+ orderId +"的订单申请退货，发送微信消息失败!");
						}


						flag = true;
					}
				} else if (operation == 7) {	//申请换货
					order.setSalesStatus(11);	//申请换货中
					//修改订单状态
					int num = cartDao.updateOrderByOrder(order);
					if (num > 0) {
						Order order2 = adminOrderService.selectOrderStatusByOrderId(orderId);
						//获取当前订单订单项
						List<OrderItem> itemList = adminOrderService.getShopOrderItemByOrderId(orderId);
						try {
							sendMessageUtil.orderApplyBarter(
									"尊敬的用户，已收到您的【换货申请】，我们正在确认换货信息。",
									orderId,
									itemList.get(0).getItemProductName(),
									ResultInfo.exchangeRemark,
									order2.getSalesOpenid(),
									ResultInfo.ORDER_DETAIL+orderId
							);
						} catch (Exception e) {
							logger.info("订单号："+ orderId +"的订单申请换货，发送微信消息失败!");
						}

						flag = true;
					}
				} else {
					msg.append("该订单不支持");
					msg.append(txtOpera);
					msg.append("操作,请重新确认!");
				}
				break;
			case 6:	//申请退货中
				if (operation == 5) {	//取消申请退货
					order.setSalesStatus(5);	//已发货
					//修改订单状态
					int num = cartDao.updateOrderByOrder(order);
					if (num > 0) {
						flag = true;
					}
				} else {
					msg.append("该订单不支持");
					msg.append(txtOpera);
					msg.append("操作,请重新确认!");
				}
				break;
			case 7:	//退货中
				if (operation == 6) {	//取消退货
					order.setSalesStatus(5);	//已发货
					//修改订单状态
					int num = cartDao.updateOrderByOrder(order);
					if (num > 0) {
						flag = true;
					}
				} else {
					msg.append("该订单不支持");
					msg.append(txtOpera);
					msg.append("操作,请重新确认!");
				}
				break;
			case 11:	//申请换货中
				if (operation == 8) {	//取消换货
					order.setSalesStatus(5);	//已发货
					//修改订单状态
					int num = cartDao.updateOrderByOrder(order);
					if (num > 0) {
						flag = true;
					}
				} else {
					msg.append("该订单不支持");
					msg.append(txtOpera);
					msg.append("操作,请重新确认!");
				}
				break;
			default:
				msg.append("该订单不支持");
				msg.append(txtOpera);
				msg.append("操作,请重新确认!");
				break;
		}
		map.put("flag",flag);
		map.put("msg",msg);
		return map;
	}

	/**
	 * 获取用户对订单的操作
	 * @param operation
	 * @return
	 */
	public String getOrderOperation(int operation) {
		String txtOpera = "";
		switch (operation) {
			case 1:txtOpera = "取消订单";break;
			case 2:txtOpera = "申请退款";break;
			case 3:txtOpera = "取消退款";break;
			case 4:txtOpera = "申请退货";break;
			case 5:txtOpera = "取消申请退货";break;
			case 6:txtOpera = "取消退货";break;
			case 7:txtOpera = "申请换货";break;
			case 8:txtOpera = "取消换货";break;
			default:txtOpera = "取消订单";break;
		}
		return txtOpera;
	}
}
