package com.ywt.service;

import com.ywt.core.utils.Checker;
import com.ywt.domain.entity.center.RefundLog;
import com.ywt.domain.entity.center.RefundLogRepository;

import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@DubboService
@Service
public class RefundLogService extends ServiceBase {

    private static final Logger logger = LoggerFactory.getLogger(RefundLogService.class);

    @Autowired
    private RefundLogRepository refundLogRepository;

    @Autowired
    @Qualifier("ywtCenterJdbcTemplate")
    private JdbcTemplate ywtCenterJdbcTemplate;


    /**
     * 根据订单IDs得到对应的退款记录
     *
     * @param ) 退款编号s
     * @return {@link List<RefundLog>}
     */
    public List<RefundLog> getRefundLogListByRefundNos(List<String> refundNos) {
        refundNos = refundNos.stream().filter(p -> !Checker.isNone(p)).collect(Collectors.toList());
        int size = refundNos.size();
        if (!Checker.isNone(refundNos)) {
            // payment_status:2 表示支付成功
            StringBuilder sqlBuilder = new StringBuilder("select * from  refund_log where refund_status = 1 and ( ");
            for (int i = 0, j = refundNos.size(); i < j; i++) {
                if (i == 0) {
                    sqlBuilder.append(" refund_no = ");
                } else {
                    sqlBuilder.append(" or refund_no =  ");
                }
                sqlBuilder.append("'" + refundNos.get(i) + "'");
            }
            sqlBuilder.append(" ) limit ").append(size);
            return ywtCenterJdbcTemplate.query(sqlBuilder.toString(), new BeanPropertyRowMapper<>(RefundLog.class));
        }
        return null;
    }


    public String getRefundIdByRefundNo(List<RefundLog> refundLogList, String refundNo) {
        if (!Checker.isNone(refundLogList) && !Checker.isNone(refundNo)) {
            RefundLog refundLog = refundLogList.stream().filter(o -> o.getRefundNo().equals(refundNo)).findFirst().orElse(null);
            if (refundLog != null && !Checker.isNone(refundLog.getRefundId())) {
                return refundLog.getRefundId();
            }
        }
        return "";
    }

}
