package com.ghy.web.controller.pay;

import com.alibaba.fastjson.JSONObject;
import com.ghy.common.adapay.AdapayService;
import com.ghy.common.adapay.callback.PayCallback;
import com.ghy.common.adapay.model.PayParam;
import com.ghy.common.adapay.model.WxpayExpend;
import com.ghy.common.config.WxConfig;
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 com.ghy.order.domain.OrderMaster;
import com.ghy.order.service.OrderMasterService;
import com.huifu.adapay.core.exception.BaseAdaPayException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

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

    @Resource
    private WxConfig wxConfig;
    @Resource
    private AdapayService adapayService;
    @Resource
    private OrderMasterService orderMasterService;
    @Resource
    private PayCallback payCallback;

    /**
     * 微信小程序支付
     */
    @PostMapping("lite")
    @ResponseBody
    public AjaxResult litePay(HttpServletRequest request) {
        String openId = request.getHeader("code");
        String orderMasterCode = request.getHeader("orderMasterCode");
        OrderMaster orderMaster = orderMasterService.selectByCode(orderMasterCode);
        if (orderMaster == null) {
            return AjaxResult.error("订单不存在");
        }
//        JSONObject wxUser;
//        try {
//            wxUser = WxUtils.getOpenid(code, wxConfig.getAppId(), wxConfig.getSecret());
//        } catch (IOException e) {
//            logger.error("获取微信用户信息失败", e);
//            return AjaxResult.error();
//        }
//        String openId = wxUser.getString("openid");
        //调用adapay微信公众号支付.
        WxpayExpend expend = new WxpayExpend();
        expend.setOpenId(openId);
        Map<String, Object> map;
        try {
            // TODO 订单里需要补充支付金额、tittle、简要描述、分账信息、description
            PayParam payParam = new PayParam(orderMaster.getCode(),
                    "0.01", "工圈子测试", "工圈子测试描述");
            map = adapayService.wxLitePay(payParam, payCallback, expend, null, null);
        } catch (BaseAdaPayException e) {
            logger.error("获取微信用户信息失败", e);
            return AjaxResult.error();
        }
        return AjaxResult.success(map);
    }

    /**
     * 微信公众号支付.
     * 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");
        // TODO 查询回订单信息。如果订单不存在，则退出.
        try {
            JSONObject wxUser = WxUtils.getOpenid(code, wxConfig.getAppId(), wxConfig.getSecret());
            String openId = wxUser.getString("openid");
            logger.info("open id is " + openId);
            //调用adapay微信公众号支付.
            WxpayExpend expend = new WxpayExpend();
            expend.setOpenId(openId);
            Map<String, Object> map;
            // TODO 订单里需要补充支付金额、tittle、简要描述、分账信息、description
            PayParam payParam = new PayParam("订单号", "支付金额", "商品标题", "商品描述信息");
            map = adapayService.wxPubPay(payParam, payCallback, expend, null, null);
            return AjaxResult.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtil.getExceptionMessage(e));
        }
        return AjaxResult.success();
    }

}
