GarCarController.java 16.3 KB
package com.trash.garbage.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.api.R;
import com.github.pagehelper.PageInfo;
import com.trash.carInfo.domain.CarDriverRelation;
import com.trash.carInfo.domain.CarInfo;
import com.trash.carInfo.domain.vo.CarInfoVo;
import com.trash.carInfo.service.impl.CarInfoServiceImpl;
import com.trash.common.constant.HttpStatus;
import com.trash.common.core.page.TableDataInfo;
import com.trash.driver.domain.Driver;
import com.trash.driver.domain.vo.DriverVo;
import com.trash.driver.service.IDriverService;
import com.trash.enterprise.domain.TransportationEnterprise;
import com.trash.garbage.global.Result;
import com.trash.garbage.pojo.dto.GarCarInfoVo;
import com.trash.garbage.pojo.domain.GarOrderMatchAsk;
import com.trash.garbage.service.GarCarServer;
import com.trash.garbage.service.GarOrderMatchAskService;
//import javafx.scene.controlra.SplitPane;
import com.trash.garbage.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/gar/car")
@Slf4j
public class GarCarController {
    private final CarInfoServiceImpl carInfoServiceImpl;
    private String contentType = "application/json";

    @Value("${trash.token}")
    private String authorization;
    @Value("${trash.remotePath}")
    private String remotePath;

    @Autowired
    private IDriverService driverService;
    @Autowired
    private GarCarServer garCarServer;
    @Autowired
    private GarOrderMatchAskService garOrderMatchAskService;

    public GarCarController(CarInfoServiceImpl carInfoServiceImpl) {
        this.carInfoServiceImpl = carInfoServiceImpl;
    }
    public String queryAllVehicleInfo(String carNo) {
        Map<String, Object> params = new HashMap<>();
        params.put("_t", System.currentTimeMillis());
        String json = HttpUtil.doGet("/api/gpsservice/v1/baseVehicle/QueryAllVehicleInfo", params);

        // 如果提供了carNo参数,则筛选匹配的车辆信息
        if (carNo != null && !carNo.isEmpty()) {
            JSONArray vehicleArray = JSONArray.parseArray(json);
            for (int i = 0; i < vehicleArray.size(); i++) {
                    JSONObject vehicle = vehicleArray.getJSONObject(i);
                if (vehicle.getString("licenseplateNo").contains(carNo)) {
                    return vehicle.getString("vehicleId");
                }
            }
        }
        return json;
    }

    @GetMapping("/queryLatitudeLongitude")
    public Result<?> queryLatitudeLongitude(String carNo) {
        String vehicleId = queryAllVehicleInfo(carNo);

        if (StringUtils.isEmpty(vehicleId)) {
            return Result.ERROR("未找到匹配的车辆信息");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("isArea", 1);
        params.put("vehicleList", vehicleId);

        String json = HttpUtil.doGet("/api/gpsservice/v1/LocationMonitoring/VehicleStatusInfo", params);

        try {
            // 解析GPS服务返回的JSON数据
            JSONArray jsonArray = JSONArray.parseArray(json);

            if (jsonArray.size() > 0) {
                // 获取第一个车辆对象
                JSONObject vehicleObj = jsonArray.getJSONObject(0);

                // 提取经纬度信息
                String latitude = vehicleObj.getString("latitude");
                String longitude = vehicleObj.getString("longitude");

                // 创建只包含经纬度的新对象
                JSONObject latLngObj = new JSONObject();
                latLngObj.put("latitude", latitude);
                latLngObj.put("longitude", longitude);

                // 返回只包含经纬度的单个对象
                return Result.OK(latLngObj);
            } else {
                return Result.ERROR("未找到车辆位置信息");
            }
        } catch (Exception e) {
            log.error("解析JSON数据出错: ", e);
            return Result.ERROR("解析JSON数据出错");
        }
    }

    @GetMapping("/queryMileage")
    public Result<?> queryMileage(String carNo) {
        String vehicleId = queryAllVehicleInfo(carNo);
        String startTime = resolveStartTimeByCarNo(carNo);
        Date currentDate = new Date();
        String currentTime = new SimpleDateFormat("yyyy-MM-dd+HH:mm:ss").format(currentDate);
        Map<String, Object> params = new HashMap<>();
        params.put("_t", System.currentTimeMillis());
        params.put("vehicleId", vehicleId);
        params.put("endTime", currentTime);
        params.put("startTime", startTime.replace(" ","+"));

        String json = HttpUtil.doGet("/api/gpsservice/v1/locationsection/" + vehicleId + "/search", params);

        try {
            JSONArray jsonArray = JSONArray.parseArray(json);
            if (jsonArray != null && !jsonArray.isEmpty()) {
                String expectedDay = new SimpleDateFormat("yyyy-MM-dd").format(currentDate);
                JSONObject targetObject = null;
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject currentObj = jsonArray.getJSONObject(i);
                    if (StringUtils.equals(expectedDay, currentObj.getString("day"))) {
                        targetObject = currentObj;
                        break;
                    }
                }
                if (targetObject == null) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject currentObj = jsonArray.getJSONObject(i);
                        if (StringUtils.isNotBlank(currentObj.getString("day"))) {
                            targetObject = currentObj;
                            break;
                        }
                    }
                }
                if (targetObject == null) {
                    targetObject = jsonArray.getJSONObject(0);
                }

                String mileage = targetObject.getString("mileage");

                JSONArray locationSectionList = targetObject.getJSONArray("locationSectionList");
                if (locationSectionList != null && !locationSectionList.isEmpty()) {
                    JSONObject firstLocationSection = locationSectionList.getJSONObject(0);

                    String endLatitude = firstLocationSection.getString("endLatitude");
                    String endLongitude = firstLocationSection.getString("endLongitude");

                    JSONObject result = new JSONObject();
                    result.put("mileage", mileage);
                    result.put("endLatitude", endLatitude);
                    result.put("endLongitude", endLongitude);

                    return Result.OK(result.toJSONString());
                }
            }
        } catch (Exception e) {
            log.error("解析JSON数据出错: ", e);
        }

        JSONObject result = new JSONObject();
        result.put("mileage", 1);
        return Result.OK(result);
    }

    private String resolveStartTimeByCarNo(String carNo) {
        String defaultStartTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                .format(new Date(System.currentTimeMillis() - 6 * 60 * 60 * 1000L));
        if (StringUtils.isBlank(carNo)) {
            return defaultStartTime;
        }
        GarOrderMatchAsk latestAsk = garOrderMatchAskService.lambdaQuery()
                .eq(GarOrderMatchAsk::getGarCarCode, carNo)
                .orderByDesc(GarOrderMatchAsk::getGarCreateTime)
                .last("limit 1")
                .one();
        if (Objects.nonNull(latestAsk) && Objects.nonNull(latestAsk.getGarCreateTime())) {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(latestAsk.getGarCreateTime());
        }
        return defaultStartTime;
    }

    @GetMapping("/requestStrByEnergyType")
    public Result<?> requestStrByEnergyType(String energyType) {
        List<String> json = garCarServer.getAllCompanyNamesByEnergyType(energyType);
        if (CollectionUtils.isEmpty(json)) {
            return Result.ERROR("查询失败");
        }
        return Result.OK(json);
    }

    @PostMapping("/list/group/by/carType")
    public TableDataInfo listGroupByCarTypePost(GarCarInfoVo carInfo) throws ParseException{
        return listGroupByCarType(carInfo);
    }
    @GetMapping("/list/group/by/carType")
    public TableDataInfo listGroupByCarType(GarCarInfoVo carInfo) throws ParseException {

        List<GarCarInfoVo> list = garCarServer.requestGarCarInfoVo(carInfo.getCompanyId());

//        saveOrUpdateCarInfoAndDriver(list);

        TableDataInfo data = getDataTable(list);
        if (CollectionUtils.isNotEmpty(list)) {
            Map<String, List<GarCarInfoVo>> carMap = list.stream().map(car -> {
                if (Objects.equals(car.getCarType(), "轻型车辆")) {
                    car.setCarLeft("car_2.png");
                    car.setRemark("箱体约长3.3~3.6m,宽1.85~2.0m,高0.6~1.05m;整车高约2.15m;最多可容纳约70-90袋装修垃圾(75cm×45cm每袋)");
                } else if (Objects.equals(car.getCarType(), "中型车辆")) {
                    car.setCarLeft("car_2.png");
                    car.setRemark("箱体约长3.5~3.8m,宽1.9~2.1m,高0.8~1.08m;整车高约2.4m;最多可容纳约90-110袋装修垃圾(75cm×45cm每袋)");
                } else if (Objects.equals(car.getCarType(), "重型车辆")) {
                    car.setCarLeft("car_2.png");
                    car.setRemark("箱体约长3.8~4.2m,宽2.1~2.2m,高0.8~1.1m;整车高约2.8m;最多可容纳约110-140袋装修垃圾(75cm×45cm每袋)");
                }
                return car;
            }).collect(Collectors.groupingBy(GarCarInfoVo::getCarType));

            List<GarCarInfoVo> carList = new ArrayList<>();
            for (Map.Entry<String, List<GarCarInfoVo>> entry : carMap.entrySet()) {
                if (CollectionUtils.isNotEmpty(entry.getValue())) {
                    Optional<GarCarInfoVo> opt = entry.getValue().stream().filter(car -> Objects.equals(car.getCarEquipment(), "4") || Objects.equals(car.getCarEquipment(), "6") || Objects.equals(car.getCarEquipment(), "8")).findFirst();
                    if (opt.isPresent()) {
                        carList.add(opt.get());
                    } else {
                        carList.add(entry.getValue().get(0));
                    }

                }
            }
            carList = carList.stream().sorted(Comparator.comparing(GarCarInfoVo::convertContainerVolumeDefaultMaxValue)).collect(Collectors.toList());

            data.setRows(carList);
        }

        return data;
    }

    private void saveOrUpdateCarInfoAndDriver(List<GarCarInfoVo> carInfoVos) {
        if (CollectionUtils.isNotEmpty(carInfoVos)) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (GarCarInfoVo vo : carInfoVos) {
                        try {
                            CarInfo carInfo = carInfoServiceImpl.selectCarInfoByIdStr(vo.getId());
                            CarInfo ci = new CarInfo();
                            ci.setId(vo.getId());
                            ci.setCarBrank(vo.getCarBrank());
                            ci.setCarCode(vo.getCarCode());
                            ci.setCarCode(vo.getCarCode());
                            ci.setCarIdentification(vo.getCarIdentification());
                            ci.setCarType(vo.getCarType());
                            ci.setCompanyId(vo.getCompanyId());
                            ci.setContainerVolume(vo.getContainerVolume());
                            ci.setEmissionStandard(vo.getEmissionStandard());
                            ci.setFarmeNumber(vo.getFarmeNumber());
                            ci.setId(vo.getId());
                            ci.setStatus(vo.getStatus());
                            ci.setRoadTransportDate(vo.getRoadTransportDate());
                            ci.setEnterDate(vo.getEnterDate());


                            if (Objects.isNull(carInfo)) {
                                carInfoServiceImpl.save(ci);
                            } else {
                                CarInfo source = new CarInfo();
                                source.setCarBrank(carInfo.getCarBrank());
                                source.setCarCode(carInfo.getCarCode());
                                source.setCarCode(carInfo.getCarCode());
                                source.setCarIdentification(carInfo.getCarIdentification());
                                source.setCarType(carInfo.getCarType());
                                source.setCompanyId(carInfo.getCompanyId());
                                source.setContainerVolume(carInfo.getContainerVolume());
                                source.setEmissionStandard(carInfo.getEmissionStandard());
                                source.setFarmeNumber(carInfo.getFarmeNumber());
                                source.setId(carInfo.getId());
                                source.setStatus(carInfo.getStatus());
                                source.setRoadTransportDate(carInfo.getRoadTransportDate());
                                source.setEnterDate(carInfo.getEnterDate());

                                if (!StringUtils.equals(JSON.toJSONString(source), JSON.toJSONString(ci))) {
                                    carInfoServiceImpl.updateById(ci);
                                }
                            }

                            if (CollectionUtils.isNotEmpty(vo.getDriverVoList())) {
                                for (DriverVo driverVo : vo.getDriverVoList()) {
                                    Driver driver = new Driver();
                                    driver.setId(driverVo.getId());
                                    driver.setCompanyId(vo.getCompanyId());
                                    driver.setName(driverVo.getName());
                                    driver.setPhoneNo(driverVo.getPhoneNo());
                                    driver.setStatus(1);

                                    Driver source = driverService.selectDriverById(driver.getId());
                                    if (Objects.isNull(source)) {
                                        driverService.save(driver,ci.getId());
                                    }else{
                                        Driver source1 = new Driver();
                                        source1.setId(source.getId());
                                        source1.setCompanyId(source.getCompanyId());
                                        source1.setName(source.getName());
                                        source1.setPhoneNo(source.getPhoneNo());
                                        source1.setStatus(source.getStatus());

                                        if(!StringUtils.equals(JSON.toJSONString(source1),JSON.toJSONString(driver))){
                                            driverService.updateById(driver,ci.getId());
                                        }
                                    }
                                }
                            }

                        } catch (Exception e) {
                            log.error(e.getMessage(),e);
                        }
                    }
                }
            }).start();
        }
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    protected TableDataInfo getDataTable(List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }
}