package com.ghy.web.controller.pay;

import com.alibaba.fastjson.JSONObject;
import com.ghy.common.adapay.model.AdapayStatusEnum;
import com.ghy.common.adapay.model.PayParam;
import com.ghy.common.core.controller.BaseController;
import com.ghy.common.core.domain.AjaxResult;
import com.ghy.common.enums.PayStatus;
import com.ghy.common.enums.PayTypeEnum;
import com.ghy.order.domain.OrderDetail;
import com.ghy.order.domain.OrderMaster;
import com.ghy.order.service.OrderDetailService;
import com.ghy.order.service.OrderMasterService;
import com.ghy.payment.domain.FinancialChangeRecord;
import com.ghy.payment.domain.FinancialMaster;
import com.ghy.payment.service.AdapayService;
import com.ghy.payment.service.FinancialChangeRecordService;
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;
import java.util.Objects;

/**
 * 支付宝支付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;

    @Resource
    private OrderDetailService orderDetailService;

    @Resource
    private FinancialChangeRecordService financialChangeRecordService;

    /**
     * 支付宝正扫支付
     */
    @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.delayPayParam(om.getCode() + "_" + System.currentTimeMillis(), payMoney, "商品标题", "商品描述信息");
        try {
            map = adapayService.alipayQrPay(om.getDeptId(), payParam, null, null, null);
        } catch (BaseAdaPayException e) {
            logger.error("创建支付失败", e);
            return AjaxResult.error("网络不佳 请稍后再试");
        }
        return AjaxResult.success(map);
    }

    @PostMapping("/addQr")
    public AjaxResult addQrPay(@RequestBody Long orderDetailId) {
        BigDecimal payMoney = BigDecimal.ZERO;
        // 查询回原子单
        OrderDetail orderDetail = orderDetailService.selectById(orderDetailId);
        if (orderDetail == null) {
            return AjaxResult.error("子订单不存在!");
        }
        OrderMaster orderMaster = orderMasterService.selectById(orderDetail.getOrderMasterId());
        if (orderMaster == null) {
            return AjaxResult.error("主订单不存在!");
        }
        // 查询主单是否有未支付的付款单
        FinancialMaster fm = financialMasterService.selectByOrderMasterId(orderDetail.getOrderMasterId());
        if (fm == null) {
            return AjaxResult.error("财务单不存在!");
        }
        // 主单是否付款 没付款的话一起付
        boolean fmPaid = Objects.equals(PayStatus.WAIT_PAY.getCode(), fm.getPayStatus());
        if (fmPaid) {
            payMoney = payMoney.add(fm.getPayMoney());
        }
        // 查询关联的加价单
        FinancialChangeRecord financialChangeRecord = financialChangeRecordService.selectNotPayRecordByDetailId(orderDetailId);
        if (financialChangeRecord != null) {
            payMoney = payMoney.add(financialChangeRecord.getChangeMoney());
        }

        if (BigDecimal.ZERO.compareTo(payMoney) > -1) {
            return AjaxResult.error("不需要支付");
        }

        // 付款
        PayParam payParam;
        if (financialChangeRecord == null) {
            payParam = PayParam.delayPayParam(orderMaster.getCode() + "_" + System.currentTimeMillis(),
                    payMoney.setScale(2, BigDecimal.ROUND_UNNECESSARY).toString(),
                    "订单支付", "叮咚到家服务");
        } else {
            payParam = PayParam.delayPayParam(orderMaster.getCode() + "_" + financialChangeRecord.getId() + "_" + System.currentTimeMillis(),
                    payMoney.setScale(2, BigDecimal.ROUND_UNNECESSARY).toString(),
                    "加价付款", "叮咚到家服务");
        }

        JSONObject response;
        try {
            response = adapayService.alipayQrPay(orderMaster.getDeptId(), payParam, null, null, null);
        } catch (BaseAdaPayException e) {
            logger.error("创建支付失败: " + e.getMessage(), e);
            return AjaxResult.error("网络不佳 请稍后再试");
        }
        boolean status = AdapayStatusEnum.succeeded.code.equals(response.getString("status"));
        if (!status) {
            logger.error("创建支付失败: {}", response.toJSONString());
            return AjaxResult.error("网络不佳 请稍后再试");
        }
        // 支付二维码创建成功 保存一下paymentId
        String paymentId = response.getString("id");
        if (fmPaid) {
            FinancialMaster fm2update = new FinancialMaster();
            fm2update.setId(fm.getId());
            fm2update.setPaymentId(paymentId);
            fm2update.setPayType(PayTypeEnum.ALIPAY_QR.getCode());
            financialMasterService.updateFinancialMaster(fm2update);
        }
        if (financialChangeRecord != null) {
            FinancialChangeRecord fcr2update = new FinancialChangeRecord();
            fcr2update.setId(financialChangeRecord.getId());
            fcr2update.setPaymentId(paymentId);
            financialChangeRecordService.update(fcr2update);
        }
        return AjaxResult.success(response);
    }
}
