package com.ruoyi.ss.refund.service.impl;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.ss.payBill.domain.PayBillVO;
import com.ruoyi.ss.payBill.domain.bo.PayBillRefundBO;
import com.ruoyi.ss.payBill.domain.dto.PayBillRefundDTO;
import com.ruoyi.ss.refund.domain.Refund;
import com.ruoyi.ss.refund.domain.enums.RefundBstType;
import com.ruoyi.ss.refund.domain.enums.RefundStatus;
import com.ruoyi.ss.refund.service.RefundConverter;
import com.ruoyi.ss.transactionBill.service.TransactionBillService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author wjh
 * 2024/7/9
 */
@Service
@Slf4j
public class RefundConverterImpl implements RefundConverter {

    @Autowired
    private TransactionBillService transactionBillService;

    @Override
    public Refund toPo(PayBillRefundBO bo) {
        if (bo == null) {
            return null;
        }

        PayBillRefundDTO dto = bo.getDto();
        PayBillVO payBill = bo.getPayBill();

        // 按比例计算退款金额
        String refundReason = dto.getRefundReason();
        if (StringUtils.isBlank(refundReason)) {
            refundReason = String.format("支付订单退款:%s", payBill.getPayNo());
        }

        Refund refund = new Refund();
        refund.setBillId(payBill.getPayId());
        refund.setAmount(dto.getRefundAmount());
        refund.setStatus(RefundStatus.REFUNDING.getStatus());
        refund.setReason(refundReason);
        refund.setChannelId(payBill.getChannelId());

        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            refund.setUserType(loginUser.getLoginType().getType());
            refund.setUserName(loginUser.getUsername());
            refund.setUserId(loginUser.getUserId());
        } catch (Exception e) {
            log.warn(e.getMessage());
        }

        refund.setBstType(RefundBstType.PAY_BILL.getType());
        return refund;
    }
}
