package com.ghy.web.controller.pay;

import com.ghy.payment.service.AdapayService;
import com.ghy.common.adapay.model.PayParam;
import com.ghy.common.core.controller.BaseController;
import com.ghy.common.core.domain.AjaxResult;
import com.ghy.order.domain.OrderMaster;
import com.ghy.order.service.OrderMasterService;
import com.ghy.payment.domain.FinancialMaster;
import com.ghy.payment.service.FinancialMasterService;
import com.huifu.adapay.core.exception.BaseAdaPayException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;

/**
 * 支付宝支付API
 *
 * @author HH 2022/5/10
 */
@RestController
@RequestMapping("pay/ali")
public class AlipayController extends BaseController {

    @Resource
    private AdapayService adapayService;
    @Resource
    private OrderMasterService orderMasterService;
    @Resource
    private FinancialMasterService financialMasterService;

    /**
     * 支付宝正扫支付
     */
    @PostMapping("qr")
    public AjaxResult qrPay(@RequestBody Long orderMasterId) {
        OrderMaster om = orderMasterService.selectById(orderMasterId);
        FinancialMaster fm = financialMasterService.selectByOrderMasterId(orderMasterId);
        if (om == null || fm == null) {
            return AjaxResult.error("订单不存在");
        }
        if (om.getPayStatus() == 1 || fm.getPayStatus() == 1) {
            return AjaxResult.error("订单已支付,不要重复付款!");
        }
        Map<String, Object> map;
        String payMoney = fm.getPayMoney().setScale(2, BigDecimal.ROUND_UNNECESSARY).toString();
        // TODO 这里需要补充商品标题和商品描述信息
        PayParam payParam = PayParam.createDelayPay(om.getCode() + "_" + System.currentTimeMillis(), "0.01", "商品标题", "商品描述信息");
        try {
            map = adapayService.alipayQrPay(om.getDeptId(), payParam, null, null, null);
        } catch (BaseAdaPayException e) {
            logger.error("创建支付失败", e);
            return AjaxResult.error("网络不佳 请稍后再试");
        }
        return AjaxResult.success(map);
    }
}
