package com.crm.ib.task.service.impl;

import com.crm.ib.task.service.*;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by max on 2020/6/15.
 */
@SuppressWarnings({"SpringJavaAutowiringInspection", "Duplicates"})
@Service
public class MainTaskServiceImpl implements MainTaskService {

    private Logger logger = LoggerFactory.getLogger(MainTaskServiceImpl.class);

    @Autowired
    private ListeningExecutorService listeningExecutorService;
    @Autowired
    private DailyConfigService dailyConfigService;
    @Autowired
    private DailyTradeService dailyTradeService;


    @Override
    @Scheduled(fixedDelay = 5 * 60 * 1000)
    public void start() {
        /*
            获取所有统计起始时间
         */
        final Map<String, Date> configs;
        try {
            configs = dailyConfigService.getConfigMap();
            if (configs == null) {
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        //多线程
        List<ListenableFuture<Integer>> futures = Lists.newArrayList();

        /*
            平仓数据
         */
        futures.add(listeningExecutorService.submit(() -> {
            try {
                return dailyTradeService.calc(configs);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage());
                return 400;
            }
        }));

        try {
            /*
                执行计算任务
             */
            ListenableFuture<List<Integer>> all = Futures.allAsList(futures);
            List<Integer> result = all.get();
            //释放余额更新信号量
        } catch (Exception e) {
            //释放余额更新信号量
            e.printStackTrace();
            logger.error(e.getMessage());
        }


    }
}
