package com.hfkj.service.hlt;

import com.alibaba.fastjson.JSONObject;
import com.hfkj.common.exception.BaseException;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.utils.DateUtil;
import com.hfkj.common.utils.RandomUtils;
import com.hfkj.entity.BsHltCardRecord;
import com.hfkj.entity.BsMerPayConfig;
import com.hfkj.entity.BsOrderRefund;
import com.hfkj.mer.BsMerPayConfigService;
import com.hfkj.model.order.OrderChildModel;
import com.hfkj.model.order.OrderModel;
import com.hfkj.service.order.BsOrderRefundService;
import com.hfkj.service.order.BsOrderService;
import com.hfkj.sysenum.hlt.HltCardRecordPayStatusEnum;
import com.hfkj.sysenum.mer.PayPlatformEnum;
import com.hfkj.sysenum.order.OrderChildStatusEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @className: HltCardRefundService
 * @author: HuRui
 * @date: 2024/8/21
 **/
@Component
public class HltCardRefundService {
    @Resource
    private BsHltCardRecordService hltCardRecordService;
    @Resource
    private BsOrderRefundService orderRefundService;
    @Resource
    private BsMerPayConfigService merPayConfigService;
    @Resource
    private BsOrderService orderService;
    /**
     * 退款
     * @param orderRefund
     * @return
     */
    public boolean refund(BsOrderRefund orderRefund) {
        // 查询系统订单号
        BsHltCardRecord oldCardRecord = hltCardRecordService.getNewPayOrderNo(orderRefund.getOrderNo());
        if (oldCardRecord == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到最新的支付订单");
        }
        try {
            // 订单退款
            JSONObject refundObj = HuiLianTongUnionCardService.refund(orderRefund.getRefundOrderNo(), oldCardRecord.getPayOrderNo());
            if (!refundObj.getString("respCode").equals("0000")) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, refundObj.getString("respMessage"));
            }
            JSONObject consumptionResult = HuiLianTongUnionCardService.resolveResponse(refundObj.getString("data"));
            if (consumptionResult.getBoolean("success") != true) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "交易失败!"+consumptionResult.getString("message"));
            }
            oldCardRecord.setRefundTime(new Date());
            oldCardRecord.setPayStatus(HltCardRecordPayStatusEnum.status3.getCode());
            hltCardRecordService.update(oldCardRecord);

            orderRefund.setRefundSerialNo(consumptionResult.getString("orderId"));
            orderRefundService.editData(orderRefund);

            // 重新支付金额
            BigDecimal newPayPrice = oldCardRecord.getPayPrice().subtract(orderRefund.getRefundPrice());
            if (newPayPrice.compareTo(new BigDecimal("0")) > 0) {
                BsHltCardRecord newRecord = new BsHltCardRecord();
                try {
                    newRecord.setOrderNo(orderRefund.getOrderNo());
                    newRecord.setCardNo(oldCardRecord.getCardNo());
                    newRecord.setUserPhone(oldCardRecord.getUserPhone());
                    newRecord.setPayOrderNo(DateUtil.date2String(new Date(), "yyMMddHHmmss") + RandomUtils.number(6, false));
                    newRecord.setPayPrice(newPayPrice);
                    newRecord.setPayStatus(HltCardRecordPayStatusEnum.status1.getCode());
                    newRecord.setExceptionStatus(false);
                    hltCardRecordService.create(newRecord);

                    // 查询订单
                    OrderModel order = orderService.getDetail(orderRefund.getOrderNo());
                    // 查询平台
                    BsMerPayConfig merPay = merPayConfigService.getMerPay(order.getOrderChildList().get(0).getMerId(), PayPlatformEnum.type2);
                    if (merPay == null) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "商户未配置支付");
                    }
                    // 重新扣款
                    String goodsDesc = "";
                    String tranDesc = "";
                    String businessType = "HiSen_phg_goods";

                    List<OrderChildModel> childModelList = order.getOrderChildList().stream()
                            .filter(o -> o.getStatus().equals(OrderChildStatusEnum.status2.getCode())
                                    || o.getStatus().equals(OrderChildStatusEnum.status3.getCode()))
                            .collect(Collectors.toList());
                    for (OrderChildModel orderChild :childModelList) {
                        if (StringUtils.isBlank(tranDesc)) {
                            tranDesc = tranDesc + orderChild.getProductName();
                        } else {
                            tranDesc = tranDesc +","+ orderChild.getProductName();
                        }
                    }
                    // 描述超过30字符，截取加省略号
                    if (tranDesc.length()>30) {
                        tranDesc = tranDesc.substring(1,30) + "...";
                    }
                    JSONObject consumption = HuiLianTongUnionCardService.consumption(newRecord.getPayOrderNo(), newRecord.getCardNo(), newRecord.getPayPrice(), businessType, merPay.getHltInstCode(), goodsDesc, tranDesc);
                    if (!consumption.getString("respCode").equals("0000")) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, consumption.getString("respMessage"));
                    }
                    // 响应参数
                    JSONObject payConsumptionResult = HuiLianTongUnionCardService.resolveResponse(consumption.getString("data"));
                    if (payConsumptionResult.getBoolean("success") != true) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, payConsumptionResult.getString("message"));
                    }
                    newRecord.setPaySerialNo(consumptionResult.getString("orderId"));
                    newRecord.setPayTime(new Date());
                    newRecord.setPayStatus(HltCardRecordPayStatusEnum.status2.getCode());
                    hltCardRecordService.update(newRecord);

                } catch (BaseException e) {
                    newRecord.setExceptionStatus(true);
                    newRecord.setExceptionContent(e.getErrorMsg());
                    hltCardRecordService.update(newRecord);
                } catch (Exception e) {
                    newRecord.setExceptionStatus(true);
                    newRecord.setExceptionContent("未知错误");
                    hltCardRecordService.update(newRecord);
                }
            }

        } catch (BaseException e) {
            oldCardRecord.setExceptionStatus(true);
            oldCardRecord.setExceptionContent(e.getErrorMsg());
            hltCardRecordService.update(oldCardRecord);
        } catch (Exception e) {
            oldCardRecord.setExceptionStatus(true);
            oldCardRecord.setExceptionContent("未知错误");
            hltCardRecordService.update(oldCardRecord);
        }
        return !oldCardRecord.getExceptionStatus();
    }
}
