package com.ghy.callback;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ghy.common.adapay.model.AdapayStatusEnum;
import com.ghy.common.adapay.model.Event;
import com.ghy.common.adapay.model.PayReverseCallback;
import com.ghy.order.service.OrderDetailService;
import com.ghy.order.service.OrderMasterService;
import com.ghy.payment.domain.ReverseRecord;
import com.ghy.payment.mapper.ReverseRecordMapper;
import com.ghy.payment.service.CallBackService;
import com.ghy.payment.service.FinancialChangeRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 撤销支付回调
 *
 * @author HH 2022/5/31
 */
@Slf4j
@Service("payReverseCallbackService")
public class PayReverseCallbackService implements CallBackService {

    private OrderMasterService orderMasterService;
    private OrderDetailService orderDetailService;
    private ReverseRecordMapper reverseRecordMapper;
    private FinancialChangeRecordService financialChangeRecordService;

    @Override
    public void onCallback(Event event) {
        log.debug("撤销支付 callback: {}", event);
        PayReverseCallback callback = JSON.parseObject(event.getData(), PayReverseCallback.class);
        String reverseId = callback.getId();
        if (AdapayStatusEnum.succeeded.code.equals(callback.getStatus())) {
            String orderNo = callback.getOrderNo();
            String type = orderNo.substring(0, 3);
            switch (type) {
                case "ROM":
                    orderMasterService.refundSucceeded(reverseId);
                    break;
                case "ROD":
                    orderDetailService.refundSucceeded(reverseId);
                    break;
                case "RCG":
                    financialChangeRecordService.refundSucceeded(reverseId);
                    break;
                case "RAS": // TODO
                    break;
                default:
                    throw new IllegalArgumentException(String.format("未知的退款类型[%s]", type));
            }

        }
    }

    @Override
    public void onResponse(JSONObject response) {
        reverseRecordMapper.insert(JSONObject.toJavaObject(response, ReverseRecord.class));
    }

    @Autowired
    public void setOrderMasterService(OrderMasterService orderMasterService) {
        this.orderMasterService = orderMasterService;
    }

    @Autowired
    public void setOrderDetailService(OrderDetailService orderDetailService) {
        this.orderDetailService = orderDetailService;
    }

    @Autowired
    public void setFinancialChangeRecordService(FinancialChangeRecordService financialChangeRecordService) {
        this.financialChangeRecordService = financialChangeRecordService;
    }

    @Autowired
    public void setReverseRecordMapper(ReverseRecordMapper reverseRecordMapper) {
        this.reverseRecordMapper = reverseRecordMapper;
    }
}
