package com.iamberry.wechat.handles.probation;

import java.util.List;

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

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
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.ResultMsg;
import com.iamberry.wechat.core.entity.WechatUtils;
import com.iamberry.wechat.core.entity.cart.SendPayDto;
import com.iamberry.wechat.core.entity.drp.PlaceInfo;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.order.ProbationOrder;
import com.iamberry.wechat.core.entity.pay.PayResult;
import com.iamberry.wechat.core.entity.probation.ProbationUserInfo;
import com.iamberry.wechat.core.entity.product.Product;
import com.iamberry.wechat.core.entity.product.ProductType;
import com.iamberry.wechat.core.entity.relationship.DealerRelation;
import com.iamberry.wechat.face.drp.PlaceInfoService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.order.AdminProbationOrderService;
import com.iamberry.wechat.face.pay.PayService;
import com.iamberry.wechat.face.porduct.ProductService;
import com.iamberry.wechat.face.probation.ProbationService;
import com.iamberry.wechat.face.relationship.DealerRelationService;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.utils.SendMessageUtil;


/**
 * 试用功能-前台接口类
 * @author lc
 * @version 1.0
 * @createDate 2016年11月15日16:08:30
 */
@Controller
@RequestMapping("/wechat/probation")
public class ProbationHandler {
	
	@Autowired
	private ProbationService ProbationService;
	
	@Autowired
	private DealerRelationService dealerRelationService;
	
	@Autowired
	private PlaceInfoService placeInfoService;
	
	@Autowired
	private ProductService productService;
	
	@Autowired
	private MemberService memberService;
	
	@Autowired
	private PayService payService;
	
	@Autowired
	private AdminProbationOrderService adminProbationOrderService;
	
	@Autowired
	private SendMessageUtil sendMessageUtil;
	/**
	 * 跳转页面
	 * @author lc
	 * @return
	 */
	@RequestMapping("/{name}")
	public void goOrderList(HttpServletRequest request, HttpServletResponse response,@PathVariable("name") String name) {
		try {
			request.getRequestDispatcher("/WEB-INF/views/wechat/"+name+".html").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 1、用户进入页面，判断用户是否关注，如果没有关注，不允许提交试用申请，并且提示
	 * @return 0 用户不存在，1用户不是门店下线， 2通过
	 */
	@ResponseBody
	@RequestMapping("/getUserInfo")
	public int getUserInfo(HttpServletRequest request) throws Exception {
		
		Member member  = WechatUtils.getUserBySession(request);
		
		//查询...
		Member memberrs = memberService.getMemberByUserOpenId(member.getUserOpenid());
		//身份验证，，门店下的，第一级用户，，才能，申请，享用改方法
		if (memberrs ==null) {
			return 0;
		}
		int resType = memberrs.getUserResType().intValue();
		if(resType != 3){
			return 1;
		}
					
		//用户来源	线下
		DealerRelation dealerrelation= dealerRelationService.getDealerRelationById(memberrs.getUserDealers());
		if (dealerrelation ==null) {
			return 1;
		}
		int Dealerid = 0;
		if(dealerrelation!=null){
			if(dealerrelation.getDealerThird()!=null){ //第三极
				Dealerid = dealerrelation.getDealerThird();
			}else if(dealerrelation.getDealerSecond()!=null){ //第二级
				Dealerid = dealerrelation.getDealerSecond();
			}else if(dealerrelation.getDealerFifth()!=null){ //第一级
				Dealerid = dealerrelation.getDealerFifth();}
		}
		PlaceInfo fatherPlace = placeInfoService.getPlaceInfoById(Dealerid);//分销父节点信息
		if(fatherPlace ==null){ //这里是，门店角色，id
			return 1;
		}
		return 2;
	}
	
	/**
	 * 根据使用订单id，获取订单信息！
	 * @param prouserinfo 试用人实体类
	 * @return ResultMsg
	 */
	@ResponseBody
	@RequestMapping("/getProbationOrderDetail")
	public ResultMsg getProbationOrderDetail(HttpServletRequest request,@RequestParam("orderId") String orderId) throws Exception {
		
		ResultMsg remsg=new ResultMsg();
		WechatUtils.getUserBySession(request);
		
		//查询...
		ProbationOrder probationorder = ProbationService.getProbationOrderDetail(orderId);
		if (probationorder !=null) {
			remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
			remsg.setResultCode(ResultInfo.SUCCESSCODE);
			remsg.setData(probationorder);
			remsg.setStatus(true);
		} else {
			remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setStatus(false);
		}
		return remsg;
	}
	
	/**
	 * 获取产品 信息
	 * @param prouserinfo 试用人实体类
	 * @return ResultMsg
	 */
	@ResponseBody
	@RequestMapping("/getProductList")
	public ResultMsg getProductList(HttpServletRequest request) throws Exception {
		
		ResultMsg remsg=new ResultMsg();
		
		ProductType pt = new ProductType();
		pt.setTypeId(1);
		Product product = new Product();
		product.setProductType(pt);
		
		//查询...
		List<Product> productlist = productService.selectAllProductInfo(product);
		if (productlist == null) {
			remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setStatus(false);
			return remsg;
		}
		/** 不再优惠 */
		/*//减去200金额
		for (int i = 0; i < productlist.size(); i++) {
			Product pro = productlist.get(i);
			pro.setProductDiscount(pro.getProductDiscount()-20000);
			productlist.set(i, pro);
		}*/
		remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		remsg.setResultCode(ResultInfo.SUCCESSCODE);
		remsg.setData(productlist);
		remsg.setStatus(true);
		return remsg;
	}
	
	
	
	/**
	 * 首页添加试用人信息..
	 * @param prouserinfo 试用人实体类
	 * @return ResultMsg
	 */
	@ResponseBody
	@RequestMapping("/addProbationuser")
	public ResultMsg addProbationuser(ProbationUserInfo prouserinfo,
			HttpServletRequest request) throws Exception {
		
		ResultMsg remsg=new ResultMsg();
		//这里经过过滤器，这里就有 值！否者没有
		Member member  = WechatUtils.getUserBySession(request);
		//身份验证，，门店下的，第一级用户，，才能，申请，享用改方法
		int resType = memberService.selectUserResAndIdSByOpenId(member.getUserOpenid()).getUserResType().intValue();
			
		if(resType != 3){
			remsg.setMessage(NameUtils.getConfig("ERRORINFO")+"用户不是..来源于门店");
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setStatus(false);	
			return remsg;
		}
			
		//用户来源	线下
		DealerRelation dealerrelation= dealerRelationService.getDealerRelationById(member.getUserDealers());
		int Dealerid = 0;
		if(dealerrelation!=null){
			if(dealerrelation.getDealerThird()!=null){ //第三极
				Dealerid = dealerrelation.getDealerThird();
			}else if(dealerrelation.getDealerSecond()!=null){ //第二级
				Dealerid = dealerrelation.getDealerSecond();
			}else if(dealerrelation.getDealerFifth()!=null){ //第一级
				Dealerid = dealerrelation.getDealerFifth();}
		}
		PlaceInfo fatherPlace = placeInfoService.getPlaceInfoById(Dealerid);//分销父节点信息
		if(fatherPlace ==null || fatherPlace.getRoleId() != 48){ //这里是，门店角色，id
			remsg.setMessage(NameUtils.getConfig("ERRORINFO")+"用户不是..来源于门店");
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setStatus(false);	
			return remsg;
		}
		
		
		String openId  = member.getUserOpenid();
		prouserinfo.setPuserOpenid(openId);
	
		//添加 是否成功 ！
		int num = ProbationService.addProbationUser(prouserinfo);
		if (num > 0) {
			remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
			remsg.setResultCode(ResultInfo.SUCCESSCODE);
			remsg.setData("");
			remsg.setStatus(true);
		} else {
			remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setStatus(false);
		}
		return remsg;
	}
	
	/**
	 * 试用订单统一支付
	 * 2016年11月17日
	 * mzx
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping("/pay")
	public ResultMsg probationOrderPay(HttpServletRequest request,HttpServletResponse response) throws Exception{
		ResultMsg rm = new ResultMsg();
		rm.setResultCode(ResultInfo.ERRORCODE);

		SendPayDto dto = new SendPayDto();
		dto.setSuccess(false);
		Member member = WechatUtils.getUserBySession(request); // 当前用户
		
		member=memberService.getMemberByUserId(member.getUserId());
		String orderId = request.getParameter("orderId");
		if(StringUtils.isEmpty(orderId)){
			rm.setStatus(false);
			rm.setResultCode("4000");
			rm.setMessage("单号不能为空!");
			return rm;
		}
		ProbationOrder order = new ProbationOrder();
		order.setProbationOrderid(orderId);
		ProbationOrder probationOrder = adminProbationOrderService.getProbationOrderByOrderId(order);
		if(probationOrder == null){
			rm.setStatus(false);
			rm.setResultCode("4001");
			rm.setMessage("该订单不存在!");
			return rm;
		}
		Product product = productService.selectProductByProductId(probationOrder.getProbationProductId());
		PayResult result = payService.requestPay(member.getUserOpenid(), orderId, 
				probationOrder.getProbationYetAmount(), product.getProductName() + "...", NameUtils.getConfig("WECHAT_PROBATION_ORDER_BACK"));
		if (result.isPaySuccess()) {
			dto.setInfo(result.getPayData());
			dto.setSuccess(true);
		} else {
			dto.setInfo(result.getPayData());
			dto.setSuccess(false);
			rm.setResultCode("4002");
			rm.setMessage("支付失败!");
			rm.setData(dto);
			rm.setStatus(false);
			return rm;
		}
		
		dto.setOrderId(orderId);
		rm.setResultCode(ResultInfo.SUCCESSCODE);
		rm.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		rm.setData(dto);
		rm.setStatus(true);
		return rm;
	}

	/**
	 * 根据试用单号获取该订单的状态
	 * 2016年11月17日
	 * mzx
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/check_probation_pay_success")
	public ResultMsg checkProbationPaySuccess(HttpServletRequest req){
		ResultMsg rm = new ResultMsg();
		String orderId = req.getParameter("orderId");
		if(StringUtils.isEmpty(orderId)){
			rm.setStatus(false);
			rm.setResultCode("4000");
			rm.setMessage("单号不能为空!");
		}
		ProbationOrder order = new ProbationOrder();
		order.setProbationOrderid(orderId);
		ProbationOrder probationOrder = adminProbationOrderService.getProbationOrderByOrderId(order);
		if(probationOrder == null){
			rm.setStatus(false);
			rm.setResultCode("4001");
			rm.setMessage("该订单不存在!");
		}else{
			rm.setStatus(true);
			rm.setResultCode(ResultInfo.SUCCESSCODE);
			rm.setMessage(ResultInfo.SUCCESSCODE);
			rm.setData(probationOrder.getProbationStatus());
		}
		return rm;
	}
	/**
	 * 根据使用订单id，取消用户订单
	 * @return ResultMsg
	 */
	@ResponseBody
	@RequestMapping("/userCancelOrder")
	public ResultMsg userCancelOrder(HttpServletRequest request,@RequestParam("orderId") String orderId) throws Exception {
		
		ResultMsg remsg=new ResultMsg();
		WechatUtils.getUserBySession(request);
		
		//查询...
		ProbationOrder probationorder = ProbationService.getProbationOrderDetail(orderId);
		if (probationorder ==null) {
			remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setStatus(false);
			return remsg;
		} 
		ProbationOrder probationOrder = new ProbationOrder();
		probationOrder.setProbationOrderid(orderId);
		probationOrder.setProbationStatus(0);
		if (adminProbationOrderService.updateProbationOrderStatus(probationOrder)) {
			remsg.setStatus(true);
			remsg.setResultCode(ResultInfo.SUCCESSCODE);
			remsg.setMessage(ResultInfo.SUCCESSCODE);
			//推送关闭信息
			try {
				sendMessageUtil.probationShutDown(ResultInfo.PROBATION_FIRST, orderId,"0元","未支付", ResultInfo.PROBATION_REMARK, probationorder.getProbationOpenid(), ResultInfo.TRY_ORDER_DETAIL+"?orderId="+orderId);
			} catch (Exception e) {
				System.out.println("试用订单关闭，消息提示失败！");
			}
			
		}else{
			remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setStatus(false);
		}
		return remsg;
	}
	
}
