package com.iamberry.wechat.handles.pay;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;

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

import org.apache.commons.lang3.StringUtils;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.iamberry.app.tool.log.RatFWLogger;
import com.iamberry.app.verify.ValidateUtil;
import com.iamberry.wechat.core.entity.CommonDto;
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.giftCard.AgentMachine;
import com.iamberry.wechat.core.entity.giftCard.AgentPayLogs;
import com.iamberry.wechat.core.entity.giftCard.GiftCardPayCode;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.pay.PayResult;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.cart.CartService;
import com.iamberry.wechat.face.giftCard.AgentMachineService;
import com.iamberry.wechat.face.giftCard.AgentService;
import com.iamberry.wechat.face.giftCard.GiftCardPayCodeService;
import com.iamberry.wechat.face.giftCard.GiftCardService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.mq.EfastOrderService;
import com.iamberry.wechat.face.pay.PayService;
import com.iamberry.wechat.tools.DateTimeUtil;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.tools.StrUtils;
import com.iamberry.wechat.sendMsg.SendMessageUtil;


/**
 * @author 何秀刚<br>
 * Class Description: 发起微信支付Handler,凡是发起微信支付的URL，必须在本类发起，否则支付异常;<br>
 * 	不允许使用/pay/xx/yy ，理应使用/pay/xx?zz=yy 替换<br>
 * Create Date:2016年4月19日<br>
 * Update Date:2016年4月19日<br>
 */
@Controller
@RequestMapping("/pay")
public class RequestWechatPayHandler {
	@Autowired
	private CartService cartService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private PayService payService;
	@Autowired
	private AgentService agentService;
	@Autowired
	private AgentMachineService agentMachineService;
	@Autowired
	private GiftCardPayCodeService payCodeService;
    @Autowired
    private EfastOrderService efastOrderService;
    @Autowired
    private GiftCardService cardService;
	@Autowired
	private SystemService systemService;
	@Autowired
    private SendMessageUtil sendMessageUtil;
	@Autowired
	private RatFWLogger logger;
	private Object lock = new Object();
	/**
	 * 购物车针对购物项，结算
	 * @param cartIds 需要结算的购物车ID，参数示例:1-2-3-4、1-
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/settlement", method = RequestMethod.GET)
	public ModelAndView settlement(
			@RequestParam("cartId") String cartIds, HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:" + NameUtils.getConfig("WECHAT_SHOP_INDEX")); // 回到购物车页面
		// 用户信息
		//WechatUtils.getUserBySession(request);
		// 清空数据
		//request.getSession().removeAttribute("cartIds");
		
		if ((cartIds == null || cartIds.isEmpty()))
			return mv;
			//response.sendRedirect(NameUtils.getConfig("WECHAT_SHOP_INDEX"));
		// split 购物车ID
		String [] cartList = cartIds.split("-");
		if (cartList == null || cartList.length <= 0) {
			//response.sendRedirect(NameUtils.getConfig("WECHAT_SHOP_INDEX"));
			return mv;
		}
		// 转化 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) {
				//response.sendRedirect(NameUtils.getConfig("WECHAT_SHOP_INDEX"));
				return mv;
			}
		}
		if (cartIntList.length <= 0) {
			//response.sendRedirect(NameUtils.getConfig("WECHAT_SHOP_INDEX"));
			return mv;
		}
		// 根据购物车ID，查询数据库中对应的产品信息（ID、产品状态）
		List<CartDto> cartDtos = cartService.selectCartItemByListId(cartIntList);
		if (cartDtos == null || cartDtos.size() <= 0) {
			//response.sendRedirect(NameUtils.getConfig("WECHAT_SHOP_INDEX"));
			return mv;
		}
		// 判断当前提交的购物车ID，有多少产品在售
		int sum = 0;
		for (CartDto cartDto : cartDtos) {
			if (cartDto.getProductStatus() != null && cartDto.getProductStatus().intValue() == 1)
				sum++;
		}
		if (sum <= 0) {
			//response.sendRedirect(NameUtils.getConfig("WECHAT_SHOP_INDEX"));
			return mv;
		}
		mv.setViewName("forward:" + NameUtils.getConfig("WECHAT_SHOP_ORDER_PAY")); // 支付页面
		//response.sendRedirect(NameUtils.getConfig("WECHAT_SHOP_ORDER_PAY") + "?cartId="+cartIds);
		return mv;
	}
	
	/**
	 * 去订单详情页面
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping("/goOrderInfo")
	public void goOrderInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher(NameUtils.getConfig("WECHAT_SHOP_ORDER_GOORDERINFO")).forward(request, response);
	}
	
	/**
	 * 进入订单列表页面
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping("/goOrderList")
	public void goOrderList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher(NameUtils.getConfig("WECHAT_SHOP_ORDER_GOORDERLIST")).forward(request, response);
	}
	
	/**
	 * 付费代理统一支付
	 * 单号格式：AOID000_ + 支付记录id + "_" + 代理商物流记录id + ("_" + 推荐人物流记录id)<若无推荐人则无此项>
	 * 2016年11月17日
	 * mzx
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping("/pay_agent")
	public ResultMsg probationOrderPay(
			HttpServletRequest request,
			HttpServletResponse response,
			AgentMachine agentMachine) 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());
		
		//判断当前用户是否有支付成功的记录
        List<AgentPayLogs> AgentPayLogs = agentService.selectPayLogHasByOpenid(member.getUserOpenid());
        if(AgentPayLogs != null && AgentPayLogs.size() > 0){
            dto.setInfo("您已经是代理商,无须再次申请!");
            dto.setSuccess(false);
            rm.setResultCode("4004");
            rm.setMessage("您已经是代理商,无须再次申请!");
            rm.setData(dto);
            rm.setStatus(false);
            return rm;
        }
		
		String userName = request.getParameter("userName");
		String userTel = request.getParameter("userTel");
		String payPassword = request.getParameter("payPassword");
		GiftCardPayCode payCode = new GiftCardPayCode();      //抵扣密码
		if(StringUtils.isNotEmpty(payPassword)){
            payCode.setCodePassword(payPassword);
            payCode = payCodeService.getPayCodeByIdOrPassword(payCode);
		}
		CommonDto commonDto = new CommonDto();
		commonDto.setStr1(userName);
		commonDto.setStr2(userTel);
		//1.添加付费代理信息<没有则添加,有则不变> 2.添加支付记录 3.添加付费代理赠送机器信息 
		String orderId = agentService.insertAgentInfoAndAgentPayLogAndAgentMachine(commonDto, member, agentMachine);
		logger.info(this, "orderId--->>" + orderId);
		//单号格式：AOID_ + 支付记录id + "_" + 代理商物流记录id
        String[] ids = StrUtils.strToArr(orderId, "_");
        String payId = ids[1];      //支付记录id
        Integer agentId1 = Integer.parseInt(ids[2]);   //代理商物流记录id 
        
		//支付码支付 或 统一支付
		if(StringUtils.isNotEmpty(payPassword)){     //有抵扣密码，则抵扣金额
            if(payCode != null && payCode.getCodeStatus() == 1){        //正确的抵扣密码
                logger.info(this, "用户：" + member.getUserOpenid() + ",抵扣密码-->>" + payCode.getCodePassword()
                                        + ",推荐人：" + payCode.getCodeReferrerOpenid());
                
                //1. 修改支付记录状态为已支付       2. 修改付费代理商表中的推荐人       3. 插入推荐人物流信息      4. 修改支付密码的使用状态和使用人      返回推荐人赠送记录id
                String agentMachineId = agentService.updatePayLogStatusAndReferrerAndPayCodeStatus(payId, member.getUserOpenid(), payCode);
                cardService.saveCardAndMachine(1, member.getUserOpenid(), agentId1, Integer.parseInt(agentMachineId));
                try {
                    //推送百胜
                    efastOrderService.giftCard(agentMachine.getAgentMachineAddressInfo(), "ZS11111111" + agentId1, agentMachine.getAgentMachineColorId(),
                            agentMachine.getAgentMachineAddressName(), agentMachine.getAgentMachineAddressTel(), agentMachine.getAgentMachineOpenId());
                } catch (Exception e) {
                    logger.info(this, "ZS11111111" + agentId1 + "推送百胜失败!");
                    e.printStackTrace();
                }
                //有推荐人 则推荐人推送消息
                if(StringUtils.isNotEmpty(agentMachineId)){
                    try {
                        if (StringUtils.isNotEmpty(payCode.getCodeReferrerOpenid())) {
                            sendMessageUtil.prizeReceivePush(
                                    "您好，您成功推荐一位代理商，详情为:", 
                                    URLDecoder.decode(member.getUserNickname(), "UTF-8"),
                                    "Watero水时代", 
                                    "***", 
                                    DateTimeUtil.format(new Date()), 
                                    "美国watero净饮水一体机一台",
                                    "请点击完善收货地址并领取奖励。",
                                    payCode.getCodeReferrerOpenid(), 
                                    ResultInfo.AGENT_REFERRER_MACHINE_PAGE+"?agentMachineId=" + agentMachineId
                                    );
                        }
                    } catch (Exception e) {
                        logger.info(this, member.getUserOpenid() + "给推荐人" + payCode.getCodeReferrerOpenid() + "推送消息失败！");
                        e.printStackTrace();
                    }
                }
                dto.setInfo("恭喜您抵扣成功!");
                dto.setSuccess(true);
            }else{      //错误的抵扣密码
                dto.setInfo("您输入的抵扣密码不正确或已经被使用!");
                dto.setSuccess(false);
                rm.setResultCode("4003");
                rm.setMessage("您输入的抵扣密码不正确或已经被使用!");
                rm.setData(dto);
                rm.setStatus(false);
                return rm;
            }
		}else{        //没有抵扣密码，则微信支付
		    //从规则表中获取:付费代理商支付金额
	        ShopSystemRule shopSystemRule =  systemService.selectOneShopRuleById(224);
	        int money = shopSystemRule.getRuleNum().intValue();
            PayResult result = payService.requestPay(member.getUserOpenid(), orderId, 
                    money, "美国Watero净饮水一体机" + "...", NameUtils.getConfig("WECHAT_AGENT_ORDER_BACK"));
            logger.info(this,"支付结果--->>" + result.getPayData());
            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;
	}
	
	
	/**
	 * 付费代理续费统一支付 单号格式：AOID000_ + 支付记录id + "_" + 代理商物流记录id 
	 * 2017年3月1日15:45:25
	 *  LJK
	 * 
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/pay_agent_renewal")
	public synchronized ResultMsg probationRenewalPay(HttpServletRequest request,
			HttpServletResponse response, AgentMachine agentMachine)
			throws Exception {
		ResultMsg rm = new ResultMsg();
		rm.setResultCode(ResultInfo.ERRORCODE);
		rm.setStatus(false);
		Member member = WechatUtils.getUserBySession(request); // 当前用户
		//修改当前代理商姓名电话 
		String agentNickname = request.getParameter("agentNickname");
		String agentTel = request.getParameter("agentTel");
		String payPassword = request.getParameter("payPassword");

		// 收货信息校验
        if (!ValidateUtil.checkMobile(agentMachine.getAgentMachineAddressTel())
                || !ValidateUtil.checkLength(
                        agentMachine.getAgentMachineAddressName(), 10)
                || !ValidateUtil.checkLength(
                        agentMachine.getAgentMachineAddressInfo(), 100)) {
            rm.setMessage("收货地址信息有误!");
            return rm;
        }
        agentMachine.setAgentMachineOpenId(member.getUserOpenid());
        return agentService.toPayAgain(agentMachine, agentNickname, agentTel, payPassword);
//		AgentInfo agentInfo = new AgentInfo();
//		agentInfo.setAgentNickname(agentNickname);
//		agentInfo.setAgentTel(agentTel);
//		agentInfo.setAgentOpenId(member.getUserOpenid());
//		agentService.updateAgentInfoByOpenId(agentInfo);
		
//		// 获取抵扣密码
//		GiftCardPayCode payCode = new GiftCardPayCode(); // 抵扣密码
//		if (StringUtils.isNotEmpty(payPassword)) {
//			payCode.setCodePassword(payPassword);
//			payCode = payCodeService.getPayCodeByIdOrPassword(payCode);
//		}
//		AgentPayLogs payLog = null;
//		Integer payId = 0;
//		synchronized (lock) {
//			payLog = new AgentPayLogs();
//			payLog.setPayOpenId(member.getUserOpenid());
//			payLog.setPayStatus(1);
//			// 从规则表中获取生成礼品卡的数量
//			ShopSystemRule shopSystemRule = systemService
//					.selectOneShopRuleById(222);
//			int cardNum = shopSystemRule.getRuleNum().intValue();
//			payLog.setPayGiftCardNum(cardNum);
//			// 从规则表中获取:付费代理商支付金额
//			ShopSystemRule shopSystemRule1 = systemService
//					.selectOneShopRuleById(224);
//			int money = shopSystemRule1.getRuleNum().intValue();
//			payLog.setPayMoney(money);
//			payLog.setPayCreateDate(new Date());
//			payId = agentService.insertAgentPayLog(payLog);
//		}
//		agentMachine.setAgentMachineOpenId(member.getUserOpenid());
//		String idStr = agentMachineService.addAgentLogisticsMachine(agentMachine);
//		String orderId = "AOID_" + payId + "_" + idStr;
//		System.out.println("orderId----------------" + orderId);
//		// 支付码支付 或 统一支付
//		if (StringUtils.isNotEmpty(payPassword)) { // 有抵扣密码，则抵扣金额
//			if (payCode != null && payCode.getCodeStatus() == 1) { // 正确的抵扣密码
//				logger.info(this, "用户：" + member.getUserOpenid() + "抵扣密码-->>" + payCode.getCodePassword());
//				// 1. 修改支付记录状态为已支付  2.修改支付密码的使用状态和使用人 
//				agentService.updatePayLogStatus(String.valueOf(payId), member.getUserOpenid(), payCode);
//				cardService.saveCardAndMachine(member.getUserOpenid(), Integer.parseInt(idStr), null);
//				try {
//					// 推送百胜
//					efastOrderService.giftCard(
//							agentMachine.getAgentMachineAddressInfo(),
//							"ZS11111111" + idStr,
//							agentMachine.getAgentMachineColorId(),
//							agentMachine.getAgentMachineAddressName(),
//							agentMachine.getAgentMachineAddressTel(),
//							agentMachine.getAgentMachineOpenId());
//				} catch (Exception e) {
//					logger.info(this, "ZS11111111" + idStr + "推送百胜失败!");
//					e.printStackTrace();
//				}
//				dto.setInfo("恭喜您抵扣成功!");
//				dto.setSuccess(true);
//			} else { // 错误的抵扣密码
//				dto.setInfo("您输入的抵扣密码不正确或已经被使用!");
//				dto.setSuccess(false);
//				rm.setResultCode("4003");
//				rm.setMessage("您输入的抵扣密码不正确或已经被使用!");
//				rm.setData(dto);
//				rm.setStatus(false);
//				return rm;
//			}
//		} else { // 没有抵扣密码，则微信支付
//			PayResult result = payService.requestPay(member.getUserOpenid(),
//					orderId, payLog.getPayMoney(), "美国Watero净饮水一体机" + "...",
//					NameUtils.getConfig("WECHAT_AGENT_RENEWAL_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;
	}
}
