package com.ghy.web.controller.pay;

import cn.hutool.core.collection.CollectionUtil;
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.common.utils.MoneyUtil;
import com.ghy.order.domain.OrderAttachmentRecord;
import com.ghy.order.domain.OrderDetail;
import com.ghy.order.domain.OrderMaster;
import com.ghy.order.service.IOrderAttachmentRecordService;
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.domain.PaymentRelation;
import com.ghy.payment.service.AdapayService;
import com.ghy.payment.service.FinancialChangeRecordService;
import com.ghy.payment.service.FinancialMasterService;
import com.ghy.payment.service.IPaymentRelationService;
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.ArrayList;
import java.util.Arrays;
import java.util.List;
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 OrderDetailService orderDetailService;
    @Resource
    private FinancialMasterService financialMasterService;
    @Resource
    private IPaymentRelationService paymentRelationService;
    @Resource
    private FinancialChangeRecordService financialChangeRecordService;
    @Resource
    private IOrderAttachmentRecordService orderAttachmentRecordService;


    /**
     * 支付宝正扫支付
     */
    @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("订单已支付,不要重复付款!");
        }
        String payMoney = MoneyUtil.toS(fm.getPayMoney());
        // TODO 这里需要补充商品标题和商品描述信息
        PayParam payParam = PayParam.delayPayParam(om.getCode() + "_" + System.currentTimeMillis(), payMoney, "商品标题", "商品描述信息");
        try {
            JSONObject response = adapayService.alipayQrPay(om.getDeptId(), payParam, null, null, null);
            boolean status = AdapayStatusEnum.succeeded.code.equals(response.getString("status"));
            if (!status) {
                logger.error("创建支付失败: {}", response.toJSONString());
                return AjaxResult.error("网络不佳 请稍后再试");
            }
            // 支付二维码创建成功 保存一下paymentId
            String paymentId = response.getString("id");
            // 更新财务主单的paymentId
            FinancialMaster fm2update = new FinancialMaster();
            fm2update.setId(fm.getId());
            fm2update.setPaymentId(paymentId);
            fm2update.setPayType(PayTypeEnum.ALIPAY_QR.getCode());
            financialMasterService.updateFinancialMaster(fm2update);
            // 保存支付ID与主财务单ID到关系表
            PaymentRelation relation = new PaymentRelation(null, fm.getId(), PaymentRelation.FINANCIAL_MASTER, fm.getPayMoney());
            relation.setPaymentId(paymentId);
            paymentRelationService.insert(relation);
            return AjaxResult.success(response);
        } catch (BaseAdaPayException e) {
            logger.error("创建支付失败", e);
            return AjaxResult.error("网络不佳 请稍后再试");
        }
    }

    @PostMapping("/addMasterQr")
    public AjaxResult addMasterQrPay(@RequestBody String orderId) {
        orderId = orderId.replace("\"", "");
        String [] orderIds = orderId.split(",");
        List<String> orderIdList = Arrays.asList(orderIds);
        ArrayList<PaymentRelation> relations = new ArrayList<>();
        List<Long> fmList = new ArrayList<>();
        BigDecimal payMoney = BigDecimal.ZERO;
        for (String id : orderIdList){
            // 不知道为啥参数可能会带上双引号 这里去掉再转Long
            Long orderMasterId = Long.valueOf(id);
            OrderMaster orderMaster = orderMasterService.selectById(orderMasterId);
            if (orderMaster == null) {
                return AjaxResult.error("主订单不存在!");
            }
            // 查询主单是否有未支付的付款单
            FinancialMaster fm = financialMasterService.selectByOrderMasterId(orderMaster.getId());
            if (fm == null) {
                return AjaxResult.error("财务单不存在!");
            }
            // 主单是否付款 没付款的话一起付
            boolean fmPaid = Objects.equals(PayStatus.WAIT_PAY.getCode(), fm.getPayStatus());
            if (fmPaid) {
                fmList.add(fm.getId());
                payMoney = payMoney.add(fm.getPayMoney());
                relations.add(new PaymentRelation(null, fm.getId(), PaymentRelation.FINANCIAL_MASTER, fm.getPayMoney()));
            }else {
                return AjaxResult.error("选择了不需要付款的订单!");
            }

            if (MoneyUtil.lte0(payMoney)) {
                return AjaxResult.error("不需要支付");
            }

        }
        // 以第一单为第三放的付款单号
        OrderMaster orderMaster = orderMasterService.selectById(Long.valueOf(orderIdList.get(0)));
        // 付款
        PayParam payParam = PayParam.delayPayParam(orderMaster.getCode() + "_" + System.currentTimeMillis(),
                MoneyUtil.toS(payMoney), "订单支付", "叮咚到家服务");

        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");
        for (Long id : fmList){
            FinancialMaster fm2update = new FinancialMaster();
            fm2update.setId(id);
            fm2update.setPaymentId(paymentId);
            fm2update.setPayType(PayTypeEnum.ALIPAY_QR.getCode());
            financialMasterService.updateFinancialMaster(fm2update);
        }
        // 保存支付ID与订单ID到关系表
        for (PaymentRelation relation : relations) {
            relation.setPaymentId(paymentId);
            paymentRelationService.insert(relation);
        }

        return AjaxResult.success(response);
    }

    @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("财务单不存在!");
        }
        ArrayList<PaymentRelation> relations = new ArrayList<>();
        // 主单是否付款 没付款的话一起付
        boolean fmPaid = Objects.equals(PayStatus.WAIT_PAY.getCode(), fm.getPayStatus());
        if (fmPaid && !"01".equals(orderMaster.getConsultMode())) {
            payMoney = payMoney.add(fm.getPayMoney());
            relations.add(new PaymentRelation(null, fm.getId(), PaymentRelation.FINANCIAL_MASTER, fm.getPayMoney()));
        }
        // 查询关联的加价单
        FinancialChangeRecord fcr = financialChangeRecordService.selectNotPayRecordByDetailId(orderDetailId);
        if (fcr != null && !"01".equals(orderMaster.getConsultMode())) {
            payMoney = payMoney.add(fcr.getChangeMoney());
            relations.add(new PaymentRelation(null, fcr.getId(), PaymentRelation.FINANCIAL_CHANGE, fcr.getChangeMoney()));
        }else if(fcr != null){
            payMoney = payMoney.add(fcr.getChangeMoney());
            relations.add(new PaymentRelation(null, fcr.getId(), PaymentRelation.CONSULT_ADD, fcr.getChangeMoney()));
        }
        OrderAttachmentRecord param = new OrderAttachmentRecord();
        param.setOrderDetailId(orderDetailId);
        List<OrderAttachmentRecord> orderAttachmentRecordList = orderAttachmentRecordService.selectOrderAttachmentRecordList(param);
        if(CollectionUtil.isNotEmpty(orderAttachmentRecordList)){
            payMoney = payMoney.add(orderAttachmentRecordList.get(0).getAttachMoney());
            relations.add(new PaymentRelation(null, orderAttachmentRecordList.get(0).getId(), PaymentRelation.ORDER_ATTACHMENT, orderAttachmentRecordList.get(0).getAttachMoney()));
        }
        if (MoneyUtil.lte0(payMoney)) {
            return AjaxResult.error("不需要支付");
        }

        // 付款
        PayParam payParam;
        if (fcr == null) {
            payParam = PayParam.delayPayParam(orderMaster.getCode() + "_" + System.currentTimeMillis(),
                    payMoney.setScale(2, BigDecimal.ROUND_UNNECESSARY).toString(),
                    "订单支付", "叮咚到家服务");
        } else {
            payParam = PayParam.delayPayParam(orderMaster.getCode() + "_" + fcr.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 (fcr != null) {
            FinancialChangeRecord fcr2update = new FinancialChangeRecord();
            fcr2update.setId(fcr.getId());
            fcr2update.setPaymentId(paymentId);
            financialChangeRecordService.update(fcr2update);
        }
        if(CollectionUtil.isNotEmpty(orderAttachmentRecordList)){
            OrderAttachmentRecord oarUpdate = new OrderAttachmentRecord();
            oarUpdate.setId(orderAttachmentRecordList.get(0).getId());
            oarUpdate.setPaymentId(paymentId);
            orderAttachmentRecordService.updateOrderAttachmentRecord(oarUpdate);
        }
        // 保存支付ID与订单ID到关系表
        for (PaymentRelation relation : relations) {
            relation.setPaymentId(paymentId);
            paymentRelationService.insert(relation);
        }
        return AjaxResult.success(response);
    }
}
