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

import com.alibaba.fastjson.JSONObject;
import com.prolog.eis.constants.sys.SysParamConstants;

import com.prolog.eis.dto.bindgridex.BGDExGridDto;
import com.prolog.eis.dto.bindgridex.BGDExDispatchDto;
import com.prolog.eis.service.bindgridex.BindGridExAlgorithmService;
import com.prolog.eis.service.bindgridex.BindGridExDispatchService;
import com.prolog.eis.service.bindgridex.BindGridExInitService;
import com.prolog.eis.service.bindgridex.BindGridExSaveResultService;
import com.prolog.eis.service.sys.SysParamService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Version: 1.0
 * @Author: wuhan
 * @Created: 2024/8/1 15:38
 */
@Slf4j
@Service
public class BindGridExDispatchServiceImpl implements BindGridExDispatchService {
    @Resource
    private BindGridExInitService bindGridExInitService;
    @Resource
    private BindGridExAlgorithmService bindGridExAlgorithmService;
    @Resource
    private BindGridExSaveResultService bindGridExSaveResultService;
    @Resource
    private SysParamService sysParamService;

    /**
     * 格口绑定逻辑（允许一个波次部分绑定格口）
     * @return
     * @throws Exception
     */
    @Override
    public int dispatch() throws Exception {
        BGDExDispatchDto dispatchDto = bindGridExInitService.init();
        if (dispatchDto == null) {
            return 0;
        }

        long freeGridCount = dispatchDto.getGridList().stream().filter(r -> r.getBindOrderId() == null || r.getBindOrderId() == 0).count();
        if (dispatchDto.getOrderList().size() > freeGridCount) {
            return 0;
        }

        List<BGDExGridDto> gridList = bindGridExAlgorithmService.bindGrid(dispatchDto);
        if (gridList != null && gridList.size() > 0) {
            log.info(String.format("新格口绑定调度组装数据：【%s】", JSONObject.toJSONString(dispatchDto)));
        }

        if (sysParamService.findVal(SysParamConstants.NEW_BIND_GRID_TASK_SWITCH, "0").equals("0")) {
            System.out.println("新格口绑定调度任务下发开关关闭");
            return gridList.size();
        }

        bindGridExSaveResultService.saveResult(gridList);
        return gridList.size();
    }
}
