package com.sonic.lion.service.impl;

import com.sonic.lion.enums.PayChannel;
import com.sonic.lion.dao.PayCallChannelRecordDao;
import com.sonic.lion.dao.ProcessingChargeDao;
import com.sonic.lion.domain.entity.PayCallChannelRecord;
import com.sonic.lion.domain.entity.ProcessingCharge;
import com.sonic.lion.domain.output.SyncChannelOutput;
import com.sonic.lion.service.ChannelProcessingService;
import com.sonic.lion.service.ProcessingChargeService;
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 ProcessingChargeServiceImpl implements ProcessingChargeService {

    @Autowired
    private ProcessingChargeDao processingChargeDao;

    @Autowired
    private ChannelProcessingService channelProcessingService;

    @Autowired
    private PayCallChannelRecordDao payCallChannelRecordDao;

    @Override
    public void hand() {
        //查询除payssion外的其他渠道待处理充值数据进行处理
        List<ProcessingCharge> list = processingChargeDao.findOtherChannelAll();
        //查询payssion渠道的待处理充值数据进行处理，每次只取50条数据进行处理
        List<ProcessingCharge> payssionList = processingChargeDao.findPayssionChannelAll();
        //将数据列表中的数据进行合并处理
        list.addAll(payssionList);
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        log.info("handProcessingOrders size {}", list.size());
        List<PayCallChannelRecord> payCallChannelRecords = payCallChannelRecordDao.selectBatchIds(list.stream().map(ProcessingCharge::getCallChannelRecordId).collect(Collectors.toList()));
        Map<Long, PayCallChannelRecord> map = payCallChannelRecords.stream().collect(Collectors.toMap(PayCallChannelRecord::getId, record -> record));
        for (ProcessingCharge processingCharge : list) {
            hand(map, processingCharge);
        }
    }

    private void hand(Map<Long, PayCallChannelRecord> map, ProcessingCharge processingCharge) {
        try {
            PayCallChannelRecord record = map.get(processingCharge.getCallChannelRecordId());
            SyncChannelOutput syncChannelOutput = channelProcessingService.chargeProcessing(record);
            log.info("handProcessingOrders result {}", syncChannelOutput);
        } catch (Exception e) {
            log.error("handProcessingOrders fail", e);
        }
    }
}
