package com.kxs.common.pay.service.yue;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.kxs.common.core.constant.SecurityConstants;
import com.kxs.common.core.exception.GlobalCustomerException;
import com.kxs.common.core.util.R;
import com.kxs.common.pay.enums.PayPlatformEnum;
import com.kxs.common.pay.model.*;
import com.kxs.common.pay.service.PayService;
import com.kxs.user.api.dto.kxsapp.userAccount.PayRequestDTO;
import com.kxs.user.api.dto.kxsapp.userAccount.RefundRequestDTO;
import com.kxs.user.api.feign.RemoteYuePayService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;

import java.util.Optional;

/**
 * 余额支付 服务
 *
 * @author 没秃顶的码农
 * @date 2024-04-24
 */
@RequiredArgsConstructor
public class YuePayService implements PayService {

    private final RemoteYuePayService remoteYuePayService;

    @Override
    public PayResponse appPay(PayRequest payReq) {

        PayRequestDTO payRequestDTO = new PayRequestDTO();
        BeanUtil.copyProperties(payReq, payRequestDTO);
        R result = remoteYuePayService.yuePay(payRequestDTO);
        if (result.getStatus() != 1) {
            throw new GlobalCustomerException(result.getMsg());
        }
        YuePayMessage payMessage = BeanUtil.toBean(result.getData(), YuePayMessage.class);

        Optional.ofNullable(payMessage).orElseThrow(() -> new GlobalCustomerException("yue pay is empty"));

        return PayResponse.builder()
                .payPlatformEnum(PayPlatformEnum.YUEPAY)
                .result(JSON.toJSONString(payMessage))
                .build();
    }

    @Override
    public QueryResponse query(QueryRequest queryReq) {
        return null;
    }

    @Override
    public RefundResponse refund(RefundRequest refundReq) {

        RefundRequestDTO refundRequestDTO = new RefundRequestDTO();
        BeanUtil.copyProperties(refundReq, refundRequestDTO);
        R result = remoteYuePayService.refund(refundRequestDTO, SecurityConstants.FROM_IN);
        if (result.getStatus() != 1) {
            throw new GlobalCustomerException(result.getMsg());
        }
        RefundResponse refundResponse = BeanUtil.toBean(result.getData(), RefundResponse.class);

        Optional.ofNullable(refundResponse).orElseThrow(() -> new GlobalCustomerException("yue refund is empty"));

        return refundResponse;

    }

    @Override
    public String payBack(HttpServletRequest request) {
        return null;
    }

}
