package com.jeequan.jeepay.thirdparty.service;

import cn.hutool.core.bean.BeanUtil;
import com.jeequan.jeepay.core.entity.PayOrder;
import com.jeequan.jeepay.core.entity.PayOrderDivisionRefundRecord;
import com.jeequan.jeepay.core.entity.RefundOrder;
import com.jeequan.jeepay.core.interfaces.IBizOrderQueryService;
import com.jeequan.jeepay.db.entity.PayOrderDivisionRecord;
import com.jeequan.jeepay.service.impl.PayOrderDivisionRecordService;
import com.jeequan.jeepay.service.impl.PayOrderDivisionRefundRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Slf4j
@Service
public class BizOrderQueryService implements IBizOrderQueryService {

    @Autowired private PayOrderDivisionRecordService payOrderDivisionRecordService;
    @Autowired private PayOrderDivisionRefundRecordService payOrderDivisionRefundRecordService;


    @Override
    public List<PayOrderDivisionRefundRecord> queryPayOrderRefundDivisionRefundRecordList(RefundOrder refundOrder, PayOrder payOrder) {

        List<PayOrderDivisionRefundRecord> result = new ArrayList<>();


        // 查询订单是否包含分账成功的账号
        List<PayOrderDivisionRecord> recordList = payOrderDivisionRecordService.list(PayOrderDivisionRecord.gw()
                .eq(PayOrderDivisionRecord::getPayOrderId, refundOrder.getPayOrderId())
                .eq(PayOrderDivisionRecord::getState, PayOrderDivisionRecord.STATE_SUCCESS)
        );

        // 不包含分账订单
        if(recordList.isEmpty()){
            return result;
        }

        // 遍历分账记录
        for (PayOrderDivisionRecord record : recordList) {

            com.jeequan.jeepay.db.entity.RefundOrder refundOrderByDB = new com.jeequan.jeepay.db.entity.RefundOrder();
            BeanUtil.copyProperties(refundOrder, refundOrderByDB);

            com.jeequan.jeepay.db.entity.PayOrder payOrderByDB = new com.jeequan.jeepay.db.entity.PayOrder();
            BeanUtil.copyProperties(payOrder, payOrderByDB);

            result.add(payOrderDivisionRefundRecordService.genRecord(record, refundOrderByDB, payOrderByDB));
        }

        return result;
    }
}
