package com.ghy.web.controller.pay;

import com.alibaba.fastjson.JSONObject;
import com.ghy.common.adapay.AdapayService;
import com.ghy.common.adapay.callback.model.WxLiteExpend;
import com.ghy.common.adapay.callback.reply.WxPubPayCallBack;
import com.ghy.common.core.controller.BaseController;
import com.ghy.common.core.domain.AjaxResult;
import com.ghy.common.utils.ExceptionUtil;
import com.ghy.common.utils.WxUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
@RequestMapping("/pay/wx")
public class WxPayController extends BaseController {

    @Autowired
    private AdapayService adapayService;

    /**
     * 微信公众号支付.
     * https://open.weixin.qq.com/connect/oauth2/authorize?
     * appid=wx404f2439a8c24e15
     * &redirect_uri=http%3A%2F%2Fwww.opsoul.com%2Fpay%2Fwx%2Fpub
     * &response_type=code
     * &scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect
     */
    @GetMapping("/pub")
    @ResponseBody
    public AjaxResult pubPay(HttpServletRequest request) {
        String code = request.getParameter("code");
        logger.info("code is " + code);
        //测试时前端不带订单号.
//        String orderId = request.getParameter("orderId");
        // 查询回订单信息。如果订单不存在，则退出.
        try {
            JSONObject wxUser = WxUtils.getOpenid(code);
            String openId = wxUser.getString("openid");
            logger.info("open id is " + openId);
            //调用adapay微信公众号支付.
            WxLiteExpend expend = new WxLiteExpend();
            expend.setOpen_id(openId);
            Map<String, Object> map = adapayService.wxPubPay(new WxPubPayCallBack(), expend, "wxPay123456" + Math.ceil(Math.random() * 100), "1.00",
                    "测试商品", "测试商品detail", null, "description");
            //拼接消息给前端.前端通过JSAPI调用微信支付
            map.forEach((key, value) -> {
                logger.info("key is " + key + ", value is " + value);
            });
            return AjaxResult.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtil.getExceptionMessage(e));
        }
        return AjaxResult.success();
    }

}
