package com.fs.store.service.channel;

import cn.hutool.core.util.ObjectUtil;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.store.domain.FsStoreOrder;
import com.fs.store.domain.FsStorePayment;
import com.fs.store.domain.FsUser;
import com.fs.store.service.IFsStoreOrderService;
import com.fs.store.service.IFsStorePaymentService;
import com.fs.store.service.IFsUserService;
import com.fs.store.service.channel.param.PayProcessContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE;

@Service
@Scope(value = SCOPE_PROTOTYPE)
@Slf4j
public abstract class PaymentHandler {
    @Autowired
    protected IFsStorePaymentService fsStorePaymentService;
    @Autowired
    protected RedisCache redisCache;
    @Autowired
    protected IFsStoreOrderService orderService;
    @Autowired
    protected IFsUserService fsUserService;

    // 订单号可能为空
    protected FsStoreOrder order;

    protected FsUser user;

    protected FsStorePayment fsStorePayment;
    /**
     * 处理支付
     * @param context 上下文
     * @return R
     */
    public final R createOrder(PayProcessContext context){
        if(ObjectUtil.isNotNull(context.getOrderId())){
            this.order = orderService.selectFsStoreOrderById(context.getOrderId());
        }

        if(ObjectUtil.isNotNull(context.getUserId())){
            this.user = fsUserService.selectFsUserById(context.getUserId());
        }

        if(ObjectUtil.isNotNull(context.getPaymentId())){
            this.fsStorePayment = fsStorePaymentService.selectFsStorePaymentById(context.getPaymentId());
        }
        return doCreateOrder(context);
    }

    public final void refundOrder(PayProcessContext context){
        if(ObjectUtil.isNotNull(context.getPaymentId())){
            this.fsStorePayment = fsStorePaymentService.selectFsStorePaymentById(context.getPaymentId());
        }
        if(ObjectUtil.isNotNull(context.getOrderId())){
            this.order = orderService.selectFsStoreOrderById(context.getOrderId());
        }
        if(ObjectUtil.isNotNull(context.getUserId())){
            this.user = fsUserService.selectFsUserById(context.getUserId());
        }
        doRefundOrder(context);
    }
    /**
     * 子类实现的具体支付处理逻辑
     * 创建订单
     * @param context 上下文
     * @return R
     */
    protected abstract R doCreateOrder(PayProcessContext context);

    /**
     * 子类实现的具体支付处理逻辑
     * 退款
     * @param context 上下文
     * @return R
     */
    protected abstract void doRefundOrder(PayProcessContext context);

    /**
     * 是否支持
     * @return 支付类型
     */
    protected boolean support(String code){
        return false;
    }
}
