package com.izouma.nineth.web;

import com.github.binarywang.wxpay.exception.WxPayException;
import com.izouma.nineth.service.OrderService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.EncoderException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.regex.Pattern;

@Controller
@RequestMapping("/payOrder")
@Slf4j
@AllArgsConstructor
public class OrderPayController {
    private final OrderService orderService;

    @RequestMapping(value = "/alipay", method = RequestMethod.GET)
    public String payOrderAlipay(Long id, Model model, @RequestHeader(value = "User-Agent") String userAgent) {

        boolean weixin = Pattern.matches(".*(micromessenger).*", userAgent.toLowerCase());
        boolean ios = Pattern.matches(".*(ipad|iphone).*", userAgent.toLowerCase());
        boolean android = Pattern.matches(".*(android).*", userAgent.toLowerCase());
        model.addAttribute("weixin", weixin);
        model.addAttribute("ios", ios);
        model.addAttribute("android", android);
        orderService.payOrderAlipay(id, model);
        return "AlipayHtml";
    }

    @RequestMapping(value = "/weixin_h5")
    public String payOrderWeixinH5(Long id, Model model, @RequestHeader(value = "User-Agent") String userAgent) throws EncoderException, WxPayException {

        boolean weixin = Pattern.matches(".*(micromessenger).*", userAgent.toLowerCase());
        boolean ios = Pattern.matches(".*(ipad|iphone).*", userAgent.toLowerCase());
        boolean android = Pattern.matches(".*(android).*", userAgent.toLowerCase());
        model.addAttribute("weixin", weixin);
        model.addAttribute("ios", ios);
        model.addAttribute("android", android);
        model.addAttribute("payUrl", orderService.payOrderWeixinH5(id));
        return "WeixinPayHtml";
    }

    @RequestMapping(value = "/weixin")
    @ResponseBody
    public Object payOrderWeixin(@RequestParam Long id, @RequestParam String openId) throws WxPayException {
        return orderService.payOrderWeixin(id, openId);
    }
}
