package com.sonic.lion.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sonic.lion.dao.ProcessingDisputeDao;
import com.sonic.lion.domain.entity.ProcessingDispute;
import com.sonic.lion.service.ProcessingDisputeService;
import com.sonic.lion.service.RefundService;
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;

@Slf4j
@Service
public class ProcessingDisputeServiceImpl implements ProcessingDisputeService {

    @Autowired
    private ProcessingDisputeDao processingDisputeDao;


    @Autowired
    private RefundService refundService;

    public void hand() {
        //查询待处理的50条数据进行处理
        List<ProcessingDispute> list = processingDisputeDao.selectList(Wrappers.<ProcessingDispute>lambdaQuery()
                .eq(ProcessingDispute::getStatus, 0)
                .orderByDesc(ProcessingDispute::getId)
                .last("limit 50"));
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        log.info("handProcessingDispute size {}", list.size());
        for (ProcessingDispute processingDispute : list) {
            hand(processingDispute);
        }
    }

    private void updateErrorStatus(Long id, String errorMessage) {
        ProcessingDispute updateProcessingDispute = new ProcessingDispute();
        updateProcessingDispute.setId(id);
        updateProcessingDispute.setStatus(2);
        updateProcessingDispute.setError(errorMessage);
        updateProcessingDispute.setEditTime(LocalDateTime.now());
        processingDisputeDao.updateById(updateProcessingDispute);
    }


    public void hand(ProcessingDispute processingDispute) {
        try {
            log.info("handProcessingDispute data {}", processingDispute);
            boolean success = refundService.processingDisupte(processingDispute);
            if (success) {
                processingDisputeDao.deleteById(processingDispute.getId());
            } else {
                updateErrorStatus(processingDispute.getId(), String.valueOf(success));
            }
        } catch (Exception e) {
            updateErrorStatus(processingDispute.getId(), e.getMessage());
            log.error("handProcessingOrders fail", e);
        }
    }
}
