package com.ghy.web.controller.pay;

import com.ghy.common.adapay.model.DivMember;
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.json.JSONObject;
import com.ghy.common.utils.ExceptionUtil;
import com.ghy.order.domain.OrderMaster;
import com.ghy.order.service.OrderMasterService;
import com.ghy.payment.domain.FinancialMaster;
import com.ghy.payment.service.AdapayService;
import com.ghy.payment.service.FinancialMasterService;
import com.huifu.adapay.core.exception.BaseAdaPayException;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
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 FinancialMasterService financialMasterService;

    @PostMapping("drawCash")
    @ResponseBody
    public AjaxResult drawCash(@RequestBody JSONObject object) {
        try {
            // 101 123dasda D0 1.00 C7D101
            Long deptId = object.getLong("deptId");
            String orderNo = object.getStr("orderNo");
            String cashType = object.getStr("cashType");
            String cashAmt = object.getStr("cashAmt");
            String memberId = object.getStr("memberId");
            String remark = object.getStr("remark");
            adapayService.drawCash(deptId, orderNo, cashType, cashAmt, memberId, remark, null);
            return AjaxResult.success("操作成功");
        } catch (Exception e) {
            return AjaxResult.error("操作失败");
        }
    }

    /**
     * 微信小程序支付
     */
    @PostMapping("lite")
    @ResponseBody
    public AjaxResult litePay(HttpServletRequest request) {
        String openId = request.getHeader("code");
        String orderMasterCode = request.getHeader("orderMasterCode");
        OrderMaster orderMaster = orderMasterService.selectByCode(orderMasterCode);
        Assert.notNull(orderMaster, "找不到对应的订单");
        FinancialMaster financialMaster = financialMasterService.selectByOrderMasterId(orderMaster.getId());
        //调用adapay微信公众号支付.
        WxpayExpend expend = new WxpayExpend();
        expend.setOpenId(openId);
        Map<String, Object> map;
        try {
            List<DivMember> divMembers = new ArrayList<>();
            divMembers.add(new DivMember("C7D101", String.valueOf(financialMaster.getPayMoney()), true));
            // TODO 订单里需要补充支付金额、tittle、简要描述、分账信息、description
            PayParam payParam = PayParam.delayPayParam(orderMaster.getCode() + "_" + System.currentTimeMillis(),
                    String.valueOf(financialMaster.getPayMoney()), "工圈子居家设备", "工圈子居家设备购买付费");
            map = adapayService.wxLitePay(orderMaster.getDeptId(), payParam, 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 openId = request.getParameter("openId");
        String orderMasterCode = request.getHeader("orderMasterCode");
        OrderMaster orderMaster = orderMasterService.selectByCode(orderMasterCode);
        if (orderMaster == null) {
            return AjaxResult.error("订单不存在");
        }
        try {
            logger.info("open id is " + openId);
            //调用adapay微信公众号支付.
            WxpayExpend expend = new WxpayExpend();
            expend.setOpenId(openId);
            Map<String, Object> map;
            PayParam payParam = PayParam.delayPayParam(orderMaster.getCode(), "0.01", "工圈子测试", "工圈子测试描述");
            map = adapayService.wxPubPay(orderMaster.getDeptId(), payParam, expend, null, null);
            return AjaxResult.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtil.getExceptionMessage(e));
        }
        return AjaxResult.success();
    }

}
