package com.yeejoin.amos.supervision.business.service.impl;

import com.google.common.collect.Lists;
import com.yeejoin.amos.supervision.business.dao.repository.IInputItemDao;
import com.yeejoin.amos.supervision.business.dao.repository.IRoutePointDao;
import com.yeejoin.amos.supervision.business.dao.repository.IRoutePointItemDao;
import com.yeejoin.amos.supervision.business.service.intfc.IRoutePointItemService;
import com.yeejoin.amos.supervision.dao.entity.InputItem;
import com.yeejoin.amos.supervision.dao.entity.Plan;
import com.yeejoin.amos.supervision.dao.entity.RoutePoint;
import com.yeejoin.amos.supervision.dao.entity.RoutePointItem;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("routePointItemService")
public class RoutePointItemServiceImpl implements IRoutePointItemService {

    @Autowired
    private IRoutePointItemDao routePointItemDao;

    @Autowired
    private IInputItemDao inputItemDao;

    @Autowired
    private IRoutePointDao routePointDao;

    @Override
    public List<RoutePointItem> addRoutePointItemList(Plan plan, List<Long> inputItemIds, String userId) {
        Long planId = plan.getId();
        Long routeId = plan.getRouteId();
        if (CollectionUtils.isNotEmpty(inputItemIds) && routeId != null && planId != null) {
            routePointItemDao.deleteByPlanId(planId);
            List<InputItem> inputItemList = inputItemDao.listByIds(inputItemIds);
            List<RoutePoint> routePointList = routePointDao.findByRouteId(routeId);
            if (CollectionUtils.isNotEmpty(inputItemList) && CollectionUtils.isNotEmpty(routePointList)) {
                List<RoutePointItem> list = new ArrayList<>();
                routePointList.stream().forEach(route->{
                    Long routePointId = route.getId();
                    inputItemList.stream().forEach(item->{
                        RoutePointItem routePointItem = new RoutePointItem();
                        routePointItem.setInputItemId(item.getId());
                        routePointItem.setBasisJson(item.getBasisJson());
                        routePointItem.setOrderNo(item.getOrderNo());
                        routePointItem.setRoutePointId(routePointId);
                        routePointItem.setCreatorId(userId);
                        routePointItem.setCreateDate(new Date());
                        list.add(routePointItem);
                    });
                });
                return routePointItemDao.saveAll(list);
            }
        }
        return Lists.newArrayList();
    }
}
