package com.sckw.fleet.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sckw.core.model.base.BaseModel;
import com.sckw.core.utils.DateUtils;
import com.sckw.core.utils.StringUtils;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.core.web.response.result.PageDataResult;
import com.sckw.fleet.model.*;
import com.sckw.fleet.model.dto.KwfTruckRouteDto;
import com.sckw.fleet.model.request.DeleteTruckRoteReq;
import com.sckw.fleet.model.request.QueryTruckRoteReq;

import com.sckw.fleet.model.request.TruckRoteDetailReq;
import com.sckw.fleet.model.vo.QueryTruckRoteVo;
import com.sckw.fleet.model.vo.TruckRoteDetailVo;
import com.sckw.fleet.repository.*;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author PC
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class KwfTruckRouteService {

    private final KwfTruckRouteRepository truckRouteRepository;
    private final KwfDriverRepository driverRepository;
    private final KwfFleetTruckRepository fleetTruckRepository;
    private final KwfTruckRepository truckRepository;
    @Resource
    private  KwfFleetRepository fleetRepository;


    public PageDataResult<QueryTruckRoteVo> pageTruckRoute(QueryTruckRoteReq req) {
        log.info("分页查询车辆惯用路线,参数:{}", JSON.toJSONString(req));
        Long entId = LoginUserHolder.getEntId();
        //获取司机id
        Set<Long> driveIds = getDriveIds(req);
        //获取车队id
        Set<Long> fleetIds = getFleetIds(req);
        if (org.apache.commons.lang3.StringUtils.isNotBlank(req.getFleetId())){
            fleetIds.add(Long.valueOf(req.getFleetId()));
        }

        KwfTruckRouteDto kwfTruckRoute = new KwfTruckRouteDto();
        kwfTruckRoute.setFleetIds(fleetIds);
        kwfTruckRoute.setDriverIds(driveIds);
        kwfTruckRoute.setStartPoint(req.getStartPoint());
        kwfTruckRoute.setUnloadingPoint(req.getUnloadingPoint());
        kwfTruckRoute.setTruckNo(req.getTruckNo());
        kwfTruckRoute.setEntId(entId);
        IPage<KwfTruckRoute> truckRoutePage = truckRouteRepository.pageTruckRoute(req.getPageNum(), req.getPageSize(), kwfTruckRoute);
        List<KwfTruckRoute> records = truckRoutePage.getRecords();
        if (CollectionUtils.isEmpty(records)){
            return PageDataResult.empty(req.getPageNum(), req.getPageSize());
        }
        //获取车队id
        Set<Long> fleetIdList = records.stream()
                .map(KwfTruckRoute::getFleetId)
                .collect(Collectors.toSet());
        //查询车队信息
        List<KwfFleet> fleets =  fleetRepository.findByfleetIds(fleetIdList);
        //车队id映射车队
        Map<Long, KwfFleet> fleetIdAndFleetMap = fleets.stream().collect(Collectors.toMap(KwfFleet::getId, Function.identity(), (k1, k2) -> k1));
        Set<Long> driveIdList = records.stream()
                .map(KwfTruckRoute::getDriverId)
                .collect(Collectors.toSet());
        //查询司机信息
        List<KwfDriver> drivers = driverRepository.findByDriverIds(driveIdList);
        //司机id映射司机
        Map<Long, KwfDriver> driverIdAndDriverMap = drivers.stream()
                .collect(Collectors.toMap(BaseModel::getId, Function.identity(), (k1, k2) -> k1));
        //组织返回数据
        List<QueryTruckRoteVo> queryTruckRoteVos = records.stream()
                .map(r -> getQueryTruckRoteVo(r, fleetIdAndFleetMap, driverIdAndDriverMap))
                .collect(Collectors.toList());
        return PageDataResult.of(truckRoutePage, queryTruckRoteVos);
    }

    /**
     * 获取车队id
     * @param req 请求参数
     * @return 车队id集合
     */
    private Set<Long> getFleetIds(QueryTruckRoteReq req) {
        if (StringUtils.isBlank(req.getTruckNo())) {
            return Collections.emptySet();
        }
        KwfTruck kwfTruck = truckRepository.queryByTruckNo(req.getTruckNo());
        if (Objects.isNull(kwfTruck)) {
            return Collections.emptySet();
        }
        List<KwfFleetTruck> kwfFleetTrucks = fleetTruckRepository.queryByTruckId(kwfTruck.getId());
        if (CollectionUtils.isEmpty(kwfFleetTrucks)) {
            return Collections.emptySet();
        }
        return kwfFleetTrucks.stream()
                .map(KwfFleetTruck::getFleetId)
                .collect(Collectors.toSet());
    }

    /**
     * 返回司机id
     * @param req 请求参数
     * @return 驾驶员id集合
     */
    private Set<Long> getDriveIds(QueryTruckRoteReq req) {
        if (StringUtils.isBlank(req.getDriverName())) {
            return new HashSet<>();
        }
        //查询司机信息
        List<KwfDriver> drivers = driverRepository.findDriverByName(req.getDriverName());
        if (CollectionUtils.isEmpty(drivers)) {
            return new HashSet<>();
        }
        return drivers.stream()
                .map(BaseModel::getId)
                .collect(Collectors.toSet());
    }

    /**
     * 组织返回参数
     * @param r 路线信息
     * @param fleetIdAndFleetMap 车队id映射车队信息
     * @param driverIdAndDriverMap 驾驶员id映射驾驶员信息
     * @return 查询车辆惯用路线返回参数
     */
    private static QueryTruckRoteVo getQueryTruckRoteVo(KwfTruckRoute r, Map<Long, KwfFleet> fleetIdAndFleetMap, Map<Long, KwfDriver> driverIdAndDriverMap) {
        QueryTruckRoteVo queryTruckRoteVo = new QueryTruckRoteVo();
        queryTruckRoteVo.setId(String.valueOf(r.getId()));
        queryTruckRoteVo.setTruckNo(r.getTruckNo());
        queryTruckRoteVo.setStartPoint(r.getStartPoint());
        queryTruckRoteVo.setUnloadingPoint(r.getUnloadingPoint());
        queryTruckRoteVo.setFleetId(String.valueOf(r.getFleetId()));
        KwfFleet fleet = fleetIdAndFleetMap.getOrDefault(r.getFleetId(), new KwfFleet());
        queryTruckRoteVo.setFleetName(fleet.getName());
        KwfDriver driver = driverIdAndDriverMap.getOrDefault(r.getDriverId(), new KwfDriver());
        queryTruckRoteVo.setDriverName(driver.getName());
        queryTruckRoteVo.setDriverId(String.valueOf(r.getDriverId()));
        queryTruckRoteVo.setUpdateTime(DateUtils.format(r.getUpdateTime(),DateUtils.DATE_TIME_PATTERN));
        queryTruckRoteVo.setSortedTime(r.getShortestTime());
        return queryTruckRoteVo;
    }

    public Boolean deleteTruckRoute(DeleteTruckRoteReq req) {
        log.info("删除车辆惯用路线，请求参数 :{}", JSON.toJSONString(req));
        return truckRouteRepository.deleteTruckRoute(req.getId());

    }

    public TruckRoteDetailVo truckRouteDetail(@Valid TruckRoteDetailReq req) {
        log.info("查询车辆惯用路线详情，请求参数 :{}", JSON.toJSONString(req));
        KwfTruckRoute kwfTruckRoute = truckRouteRepository.findOneByDriverIdAndPoint(req.getDriverId(),req.getStartPoint(),req.getUnloadingPoint());
        if (Objects.isNull(kwfTruckRoute) || StringUtils.isBlank(kwfTruckRoute.getPointInfo())){
            return new TruckRoteDetailVo();
        }
        String pointInfo = kwfTruckRoute.getPointInfo();
        List<TruckRoteDetailVo.TruckRoteDetail> truckRoteDetails = JSON.parseArray(pointInfo, TruckRoteDetailVo.TruckRoteDetail.class);
        TruckRoteDetailVo truckRoteDetailVo = new TruckRoteDetailVo();
        truckRoteDetailVo.setStartPoint(kwfTruckRoute.getStartPoint());
        truckRoteDetailVo.setUnloadingPoint(kwfTruckRoute.getUnloadingPoint());
        truckRoteDetailVo.setTruckRoteDetails(truckRoteDetails);
        return truckRoteDetailVo;
    }
}
