package com.prolog.eis.service.buildwave.impl;

import com.alibaba.fastjson.JSONObject;
import com.prolog.eis.constants.sys.SysParamConstants;
import com.prolog.eis.dto.buildwave.BuildWaveDispatchDto;
import com.prolog.eis.dto.buildwave.PObResultDto;
import com.prolog.eis.service.buildwave.BuildWaveDispatchService;
import com.prolog.eis.service.buildwave.BuildWaveInitService;
import com.prolog.eis.service.buildwave.BuildWaveSaveResultService;
import com.prolog.eis.service.buildwave.BuildWaveService;
import com.prolog.eis.service.sys.SysParamService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Version: 1.0
 * @Author: wuhan
 * @Created: 2024/7/30 15:11
 */
@Service
@Slf4j
public class BuildWaveDispatchServiceImpl implements BuildWaveDispatchService {
    @Resource
    private BuildWaveInitService buildWaveInitService;
    @Resource
    private BuildWaveService buildWaveService;
    @Resource
    private BuildWaveSaveResultService buildWaveSaveResultService;
    @Resource
    private SysParamService sysParamService;

    @Override
    public int dispatch() throws Exception {
        BuildWaveDispatchDto dispatchDto = buildWaveInitService.init();
        if (dispatchDto == null) {
            return 0;
        }

        log.info(String.format("新组波调度组装数据：【%s】", JSONObject.toJSONString(dispatchDto)));
        dispatchDto.init();

        PObResultDto result = buildWaveService.buildWave(dispatchDto);

        if (sysParamService.findVal(SysParamConstants.NEW_WAVE_TASK_SWITCH, "0").equals("0")) {
            System.out.println("新组波调度任务下发开关关闭");
            if (result == null) {
                return 0;
            } else {
                return result.getOrderList().size();
            }
        }

        if (result.getOrderList().size() < dispatchDto.getMaxWaveOrderCount() && dispatchDto.getTailWaveSwitch() == 0) {
            return 0;
        }

        if (result == null) {
            return 0;
        } else {
            //生成波次数据
            buildWaveSaveResultService.saveResult(result);
            return result.getOrderList().size();
        }
    }
}
