package com.iamberry.wechat.handles.drp;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

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.ResponseBody;

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.admin.ShopSystemRule;
import com.iamberry.wechat.core.entity.drp.EasyPage;
import com.iamberry.wechat.core.entity.drp.PlaceInfo;
import com.iamberry.wechat.core.entity.drp.PlaceOrder;
import com.iamberry.wechat.core.entity.pay.PayResult;
import com.iamberry.wechat.core.entity.product.Product;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.cart.ProductInfoService;
import com.iamberry.wechat.face.drp.PlaceInfoService;
import com.iamberry.wechat.face.drp.PlaceOrderService;
import com.iamberry.wechat.face.pay.PayService;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.tools.ValidationResult;
import com.iamberry.wechat.tools.ValidationUtils;


/**
 * @description 
 * @author 欧阳明
 * @date 2016-4-20
 */
@Controller
@RequestMapping("/wechat/placeOrder")
public class PlaceOrderHandler {

	@Autowired
	private PlaceOrderService  placeOrderService;
	@Autowired
	private WechatUtils wechatUtils;
	@Autowired
	private PayService payService;
	@Autowired
	private ProductInfoService productInfoService;
	@Autowired
	private PlaceInfoService  placeInfoService;
	@Autowired
	private SystemService  systemService;
	@Autowired
	private RatFWLogger logger;
	/**
	 * 获取订单页面
	 * @param placeOrder
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/getOrderPaper")
	public ResultMsg getOrderPaper(HttpServletRequest request) throws Exception{
		ResultMsg resultMsg=getSuccessResult();
		//int productId=Integer.valueOf(request.getParameter("productId"));
		int productId=systemService.selectOneShopRuleById(25).getRuleNum().intValue();
		String openid=getOpenid(request);//request.getParameter("openid");
		if(openid==null || openid.equals("")){
			resultMsg.setMessage(ResultInfo.paramFormatError);
			resultMsg.setStatus(false);
			return resultMsg;
		}
	    PlaceInfo pinfo=placeInfoService.getPlaceInfoByOpenId(openid);
	  
	    //只有顶级分销商才有订货功能
	    if(pinfo.getSupperId()!=pinfo.getId()){
	    	resultMsg.setMessage(ResultInfo.drpBookAthorNoEnough);
			resultMsg.setStatus(false);
			resultMsg.setResultCode("500");
			return resultMsg;
	    }
	    
	    HashMap map=new HashMap();
	    map.put("user", pinfo);
	    map.put("product", placeOrderService.getOrderPaper(productId));
	    
		resultMsg.setData(map);
		return resultMsg;
	}
	
	/**
	 * 提交分销订单
	 * @param placeOrder
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/submitOrder")
	public ResultMsg  submitOrder(PlaceOrder placeOrder,HttpServletRequest request) throws Exception{
		ResultMsg remsg=new ResultMsg();
		
		//对象效验
		ValidationResult result =ValidationUtils.validateEntity(placeOrder);
		if(result.isHasErrors()){
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setMessage(ResultInfo.ERRORINFO);
			remsg.setData(result.getErrorMsgList());
			remsg.setStatus(false);
			return remsg;
		}

		//计算订单总金额
		ShopSystemRule sr=systemService.selectOneShopRuleById(20);
		placeOrder.setYetAmount(sr.getRuleNum().intValue()*placeOrder.getProductNumber());
		placeOrder.setAmount(sr.getRuleNum().intValue()*placeOrder.getProductNumber());
		
		//String openid=placeOrder.getOpenid();
		placeOrder.setCreateDate(new Date());
		String openid=getOpenid(request);
		if(openid==null || openid.equals("")){
			remsg.setMessage(ResultInfo.paramFormatError);
			remsg.setStatus(false);
			return remsg;
		}
		placeOrder.setOpenid(openid);
		PlaceInfo placeInfo=placeInfoService.getPlaceInfoByOpenId(openid);
		placeOrder.setPlaceInfoId(placeInfo.getId());
		placeOrder=placeOrderService.submitOrder(placeOrder, placeInfo.getId());
		
		Product product=productInfoService.getProductByProductId(placeOrder.getProductId());
		logger.info("====================获取product产品");
		//这里需要调用其他的逻辑支付逻辑进行处理
		//PayResult result2 = payService.requestPay(openid, placeOrder.getId(), placeOrder.getYetAmount(), product.getProductName() + "...", NameUtils.WECHAT_DRP_BACK);
		//测试使用的
		PayResult result2 = payService.requestPay(openid, placeOrder.getId(), placeOrder.getYetAmount(), product.getProductName() + "...", NameUtils.WECHAT_DRP_BACK);
		if (result2.isPaySuccess()) {
			remsg.setResultCode(ResultInfo.SUCCESSCODE);
			remsg.setMessage(ResultInfo.SUCCESSINFO);
			remsg.setStatus(true);
			
			Map<String, String> map = new HashMap<String, String>();
			map.put("payData", result2.getPayData());
			map.put("placeOrder", placeOrder.getId());
			remsg.setData(map);
			logger.info("====================支付成功！");
		} else {
			remsg.setData("placeOrderId:"+placeOrder.getId());
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setMessage(ResultInfo.ERRORINFO);
			remsg.setStatus(false);
			logger.info("====================支付失败！");
		}
		
		return remsg;
		
	}
	
	/**
	 * 支付成功，返回订单信息
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/successOrder")
	public ResultMsg successOrder(String id){
		ResultMsg msg=getSuccessResult();
		PlaceOrder placeOrder=placeOrderService.getOrderPaperById(id);
		msg.setData(placeOrder);
      return msg;
	}
	/**
	 * 支付未付款的订单
	 * @param placeOrder
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/payOrder")
	public ResultMsg  payOrder(PlaceOrder placeOrder,HttpServletRequest request) throws Exception{
		ResultMsg remsg=new ResultMsg();
		String openid=getOpenid(request);//placeOrder.getOpenid();
		if(openid==null || openid.equals("")){
			remsg.setMessage(ResultInfo.paramFormatError);
			remsg.setStatus(false);
			return remsg;
		}
		placeOrder=placeOrderService.getOrderPaperById(placeOrder.getId());
		placeOrder.setOpenid(openid);
        
		
		Product product=productInfoService.getProductByProductId(placeOrder.getProductId());
		//这里需要调用其他的逻辑支付逻辑进行处理
		PayResult result = payService.requestPay(openid, placeOrder.getId(), placeOrder.getYetAmount(), product.getProductName() + "...", NameUtils.WECHAT_DRP_BACK);
		if (result.isPaySuccess()) {
			remsg.setResultCode(ResultInfo.SUCCESSCODE);
			remsg.setMessage(result.getPayData());
			remsg.setData(placeOrder);
			remsg.setStatus(true);
		} else {
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setMessage(result.getPayData());
			remsg.setStatus(false);
		}
		return remsg;
	}
	
	
	/**
	 * 查询订单列表(已付，未付，发货)
	 * @param placeOrder
	 * placeOrder 作为一个查询条件 已付的status为2；未付的为1；发货的为3；
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/searchOrderList")
	public ResultMsg  SearchOrder(PlaceOrder placeOrder){
		ResultMsg resultMsg=getSuccessResult();
	    resultMsg.setData(placeOrderService.getSearchPaidOrder(placeOrder));
	    return resultMsg;
	}
			
	/**
	 * 查询订单列表(已付，未付，发货) 分页的下一页
	 * @param placeOrder
	 * @param request
	 *  page参数必须带condition PlaceOrder 作为一个查询条件 已付的status为2；未付的为1；发货的为3；
	 *  Page参数必须设置页码pageNumber，每页大小pageSize，默认每页展示6个数据
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/searchOrderPageList")
	public ResultMsg  SearchOrderPage(EasyPage easyPage,HttpServletRequest request) throws Exception{
		ResultMsg resultMsg=getSuccessResult();
		PlaceOrder placeOrder=new PlaceOrder(); 
		placeOrder.setStatus(easyPage.getStatus());
		String openid=getOpenid(request);    //easyPage.getOpenid();
		if(openid==null || openid.equals("")){
			resultMsg.setMessage(ResultInfo.paramFormatError);
			return resultMsg;
		}
		
		placeOrder.setOpenid(openid);
		
		PageBean page=new PageBean();
		page.setPageNumber(easyPage.getPageNumber());
		page.setPageSize(easyPage.getPageSize());
		placeOrder.setPage(page);
		
		resultMsg.setData(placeOrderService.getSearchPaidOrderNext(placeOrder));
		return resultMsg;
	}		
	
	//返回处理结果
	public ResultMsg getSuccessResult(){
		ResultMsg remsg=new ResultMsg();
		remsg.setResultCode(ResultInfo.SUCCESSCODE);
		remsg.setMessage(ResultInfo.SUCCESSINFO);
		remsg.setStatus(true);
		return remsg;
	}
	//获取openid
	public String getOpenid(HttpServletRequest request){
		try {
			return wechatUtils.getUserBySession(request).getUserOpenid();
		} catch (Exception e) {
			e.printStackTrace();
			return "oaH_GwHQSHd2-KxQpihr_b9Y9lOc";
		}
	}

}
