package com.sonic.lion.service.impl;

import com.sonic.lion.dao.PayCallChannelRecordDao;
import com.sonic.lion.dao.PayTradeDao;
import com.sonic.lion.dao.ProcessingWithdrawReviewDao;
import com.sonic.lion.domain.entity.PayTrade;
import com.sonic.lion.domain.entity.ProcessingWithdrawReview;
import com.sonic.lion.service.ProcessingWithdrawReviewService;
import com.sonic.lion.service.WithdrawService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProcessingWithdrawReviewServiceImpl implements ProcessingWithdrawReviewService {

    @Autowired
    private ProcessingWithdrawReviewDao processingWithdrawReviewDao;

    @Autowired
    private WithdrawService withdrawService;

    @Autowired
    private PayTradeDao payTradeDao;


    @Autowired
    private PayCallChannelRecordDao payCallChannelRecordDao;

    @Override
    public void hand() {
        List<ProcessingWithdrawReview> list = processingWithdrawReviewDao.findAll(LocalDateTime.now().plusDays(-1) );
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        log.info("handProcessingWithdrawReview size {}", list.size());
        List<PayTrade> payTrades = payTradeDao.selectBatchIds(list.stream().map(ProcessingWithdrawReview::getTradeId).collect(Collectors.toList()));
        Map<Long, PayTrade> map = payTrades.stream().collect(Collectors.toMap(PayTrade::getId, record -> record));

        for (ProcessingWithdrawReview processingWithdraw : list) {
            hand(map, processingWithdraw);
        }
    }

    private void hand(Map<Long, PayTrade> map, ProcessingWithdrawReview processingWithdraw) {
        try {
            PayTrade payTrade = map.get(processingWithdraw.getTradeId());
            log.error("handProcessingWithdrawReview ...{}", processingWithdraw);
            withdrawService.handWithdrawWhenReviewTimeOut(payTrade);
            processingWithdrawReviewDao.deleteById(processingWithdraw.getId());
        } catch (Exception e) {
            log.error("handProcessingWithdrawReview fail", e);
        }
    }
}
