package com.iamberry.wechat.handles.lease;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.WechatUtils;
import com.iamberry.wechat.core.entity.admin.ShopSystemRule;
import com.iamberry.wechat.core.entity.cart.CartDto;
import com.iamberry.wechat.core.entity.cart.SendPayDto;
import com.iamberry.wechat.core.entity.cart.TempOrderDto;
import com.iamberry.wechat.core.entity.lease.LeaseOrder;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.pay.PayResult;
import com.iamberry.wechat.core.entity.rent.RentApply;
import com.iamberry.wechat.face.cart.CartService;
import com.iamberry.wechat.face.lease.LeaseOrderService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.pay.PayService;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.OrderNOUtil;
import com.iamberry.wechat.tools.ResponseJson;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.tools.ValidatorUtil;

@Controller
@RequestMapping("/wechat/leaseOrder")
public class LeaseOrderHandler {
	
	@Autowired
	private MemberService memberService;
	
	@Autowired
	private ValidatorUtil validatorUtil;
	
	@Autowired
	private CartService cartService;
	
	@Autowired
	private LeaseOrderService leaseOrderService;
	
	@Autowired
	private PayService payService;

	@ResponseBody
	@RequestMapping(value = "/paySaveLeaseOrder", method = RequestMethod.POST)
	public ResultMsg paySaveLeaseOrder(
			TempOrderDto temp,
			HttpServletRequest request) throws Exception {
		
		ResultMsg msg = new ResultMsg();
		msg.setResultCode(ResultInfo.ERRORCODE);
		//当前支付时间
		Date nowDate=new Date();
		
		SendPayDto dto = new SendPayDto();
		dto.setSuccess(false);
		
		Member member = WechatUtils.getUserBySession(request); // 当前用户
		/** 数据格式校验 */
		if (member == null || member.getUserOpenid() == null) {// 校验当前用户信息是否丢失
			msg.setMessage(ResultInfo.loginOutError);
			return msg;
		}
		member=memberService.getMemberByUserId(member.getUserId());
		if (!validatorUtil.validatorObject(temp)) { // 校验订单信息是否输入有误
			msg.setMessage(ResultInfo.paramFormatError);
			return msg;
		}
		if (temp.getOrderUserRemark() != null && !temp.getOrderUserRemark().isEmpty()) {
			Pattern pattern = Pattern.compile("^[\u4e00-\u9fa5_a-zA-Z0-9]+$");
			if (!pattern.matcher(temp.getOrderUserRemark()).find()) {
				msg.setMessage(ResultInfo.paramFormatError);
				return msg;
			}
			if (!(temp.getOrderUserRemark().length() >= 1 && temp.getOrderUserRemark().length() <= 100)) {
				msg.setMessage(ResultInfo.paramFormatError);
				return msg;
			}
		}
		Integer [] cartId = null;
		try {
			cartId = checkCartIdListString(temp.getCartIdStr());
		} catch (Exception e) { // 一旦发生异常，表示错误
			msg.setMessage(ResultInfo.paramFormatError);
			return msg;
		}
		
		List<CartDto> cartDtos = cartService.selectCartItemByListId(cartId);
		if (cartDtos == null || cartDtos.size() <= 0) {// 根据购物车ID，查询数据库中对应的产品信息（ID、产品状态）
			msg.setMessage(ResultInfo.cartEmptyError);
			return msg;
		}
		
		int total = 0; // 需要支付的总额, 单位为分
		LeaseOrder order = new LeaseOrder();
		List<Integer> cartIds = new ArrayList<Integer>();
		ShopSystemRule shopSystemRule = cartService.getReluByRid(210);	//获取租用押金(以分为单位)
		order.setOrderId(OrderNOUtil.createOrderCode(member.getUserId()));
		order.setOrderOpenid(member.getUserOpenid());
		
		
		//计算商品总价
		CartDto cartDto = cartDtos.get(0);
		if (cartDto.getProductStatus() != null && cartDto.getProductStatus().intValue() == 1) {
			cartIds.add(cartDto.getCartId());
			Integer subTotal = cartDto.getCartNum() * cartDto.getProductPrice(); // 小计
			total += subTotal + shopSystemRule.getRuleNum().intValue();
			//因为租用只能选择同一种颜色，所以颜色id只有一个
			//order.setOrderColorId(cartDto.getCartColorId());
			order.setOrderProductId(cartDto.getCartProductId());
			order.setOrderProductDiscount(cartDto.getProductPrice());
			order.setOrderProductPrice(cartDto.getProductDiscount());
			order.setOrderProductPic(cartDto.getProductIntroduceImg());
			//order.setOrderProductColor(cartDto.getProductColor());
		}
		
		order.setOrderAmount(total);
		order.setOrderDeposit(shopSystemRule.getRuleNum().intValue());
		order.setOrderStatus(1);
		order.setOrderRentTel(temp.getOrderAddressMoblie());
		
		
		order.setOrderTransactionDate(nowDate);  //事务时间
		order.setOrderTransactionId("8990"+nowDate.getTime());
		order.setOrderAddressInfo(temp.getOrderAddressInfo()); // 收货地址
		order.setOrderAddressName(temp.getOrderAddressName()); // 收货人
		order.setOrderAddressTel(temp.getOrderAddressMoblie()); // 收入联系方式
		order.setOrderAddressPostnum(temp.getOrderAddressPostNum()); // 物流编号
		order.setOrderUserRemark(temp.getOrderUserRemark()); // 用户备注
		
		boolean flag = false;
		//保存订单信息
		try {
			flag = leaseOrderService.saveLeaseOrder(order, cartIds);
		} catch (Exception e) {
			flag = false;
			System.out.println("====插入订单列表信息失败====");
			msg.setMessage(ResultInfo.paramFormatError);
			return msg;
		}
		
		if (flag) {
			// 发起支付
			PayResult result = payService.requestPay(order.getOrderOpenid(), order.getOrderId(), total, order.getOrderProductName() + "...", NameUtils.getConfig("WECHAT_ORDER_BACK"));
			if (result.isPaySuccess()) {
				dto.setInfo(result.getPayData());
				dto.setSuccess(true);
				dto.setOrderId(order.getOrderOpenid());
			} else {
				dto.setInfo(result.getPayData());
				dto.setOrderId(order.getOrderOpenid());
				msg.setResultCode(ResultInfo.ERRORCODE);
				msg.setMessage(NameUtils.getConfig("ERRORINFO"));
				msg.setData(dto);
				msg.setStatus(false);
				return msg;
			}
		}else{
			msg.setMessage(ResultInfo.paramFormatError);
			return msg;
		}
		
		msg.setResultCode(ResultInfo.SUCCESSCODE);
		msg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		dto.setOrderId(order.getOrderOpenid());
		msg.setData(dto);
		msg.setStatus(true);
		
		return msg;
	}
	
	/**
	 * 校验一个购物车字符串
	 * @param cartIds 购物车ID字符串
	 * @param cartId 接受数据数组
	 * @return
	 * @throws Exception 
	 */
	public Integer[] checkCartIdListString(String cartIds) throws Exception {
		if (cartIds == null) {
			throw new Exception(ResultInfo.paramFormatError);
		}
		cartIds.trim();
		// split 购物车ID
		String [] cartList = cartIds.split("-");
		if (cartList == null || cartList.length <= 0) {
			throw new Exception(ResultInfo.paramFormatError);
		}
		// 转化 String 类型的购物车ID集合 --> Integer 类型的购物车集合
		Integer[] cartIntList = new Integer[cartList.length];
		for (int i = 0; i < cartList.length; i++) {
			String string = cartList[i];
			try {
				cartIntList[i] = Integer.parseInt(string);
			} catch (Exception e) {
				throw new Exception(ResultInfo.paramFormatError);
			}
		}
		if (cartIntList.length <= 0) {
			throw new Exception(ResultInfo.paramFormatError);
		}
		return cartIntList;
	}
	
	/**
	 * 获取租赁订单详情
	 */
	@RequestMapping(value = "/selectLeaseOrderInfo", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg selectLeaseOrderInfo(
			HttpServletRequest request, HttpServletResponse response){
		ResultMsg remsg = new ResultMsg();
		Member member = WechatUtils.getUserBySession(request); // 当前用户
		// 校验数据
		if (member.getUserOpenid() == null || "".equals(member.getUserOpenid())) {
			remsg.setStatus(false);
			return remsg;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		//查询产品信息
		List<LeaseOrder> leaseOrder = leaseOrderService.selectLeaseOrderInfo(member.getUserOpenid());
		map.put("leaseOrder", leaseOrder);
		remsg.setData(map);
		return remsg;
	}
	
	/**
	 * 获取租赁订单详情
	 */
	@RequestMapping(value = "/updateLeaseOrderStatus", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg updateLeaseOrderStatus(
			HttpServletRequest request, HttpServletResponse response,LeaseOrder leaseOrder){
		ResultMsg remsg = new ResultMsg();
		// 校验数据
		if (leaseOrder == null) {
			remsg.setStatus(false);
			return remsg;
		}
		if (leaseOrder.getOrderId() == null || "".equals(leaseOrder.getOrderId())) {
			remsg.setStatus(false);
			return remsg;
		}
		//修改产品信息
		Integer msg = leaseOrderService.updateLeaseOrderStatus(leaseOrder);
		if(msg>0){
			remsg.setStatus(true);
		}else{
			remsg.setStatus(false);
		}
		
		return remsg;
	}
	
	@ResponseBody
	@RequestMapping("/apply")
	public ResponseJson applyRent(RentApply apply, HttpServletRequest request) {
		apply.setApplyOpenid(WechatUtils.getUserBySession(request).getUserOpenid());
		Integer res = leaseOrderService.addApply(apply);
		if (res == null || res <= 0) {
			return new ResponseJson(200, "APPLY_ERROR", 500);
		}
		// 地址为非深圳的，支付全款
		boolean isFull = true;
		if (apply.getApplyAddr().startsWith("广东省-深圳市")) {
			isFull = false;
		}
		int payMoney = 0;
		if (isFull) {
			if (apply.getApplyTime() == 1) {
				payMoney = 159900;
			} else {
				payMoney = 149900;
			}
		} else {
			payMoney = 9900;
		}
		payMoney = 1;
		// 发起支付
		String orderId = "DJ00000000" + res;
		PayResult requestPay = payService.requestPay(WechatUtils.getUserBySession(request).getUserOpenid(), orderId, payMoney, "【美国watero】 净饮水一体机定金", 
				"http://w.iamberry.com/watero/callback/rent_appply");
		if (!requestPay.isPaySuccess()) {
			return new ResponseJson(200, "APPLY_ERROR", 500);
		}
		return new ResponseJson(200, "SUCCESS", 200).addResponseKeyValue(requestPay.getPayData());
	}
}
