CarDataServiceImpl.java 19.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
package com.bs.cardata.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bs.cardata.config.CarSysConfig;
import com.bs.cardata.constant.ServiceConstants;
import com.bs.cardata.entity.CarTargetBean;
import com.bs.cardata.feign.FileFeignClient;
import com.bs.cardata.service.CarDataService;
import com.bs.cardata.service.CarSyncService;
import com.bs.cardata.utils.CarTypeJsonDeal;
import com.bs.cardata.utils.ConvertUtils;
import com.bs.cardata.utils.CrawlUtils;
import com.bs.cardata.utils.StringReplaceUtil;
import com.bs.common.core.domain.AjaxResult;
import com.bs.common.core.domain.FileEntity;
import com.bs.common.utils.StringUtils;
import com.bs.common.utils.http.HttpUtils;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created with GLSX_ACCOUNTS_GROUP.
 * <p>
 * User: Lenovo
 * CreateTime: 2018-08-15 10:11
 * <p>
 * Description: 车辆数据同步
 */
@Service
public class CarDataServiceImpl implements CarDataService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CarDataServiceImpl.class);

    @Autowired
    private CarSyncService carSyncService;
    @Autowired
    private RedisTemplate redisTemplate;


    @Autowired
    private FileFeignClient fileFeignClient;

    @Autowired
    private CarSysConfig carSysConfig;

    @Override
    public void syncCarInfo(String baseUrl) {
        try {

            Map<String, CarTargetBean> carTargetMap = getCarTargetMap();

            // 新接口地址
            // String newApiUrl = "https://www.autohome.com.cn/web-main/car/web/price/treeMenu?extendseries=1";
            String jsonRes = HttpUtil.get(baseUrl);

            if (StringUtils.isEmpty(jsonRes)) {
                LOGGER.info("====Get_carinfo_error==data empty==" + baseUrl);
                return;
            }

            JSONObject resJson = JSONObject.parseObject(jsonRes);
            if (resJson.getIntValue("returncode") != 0) {
                LOGGER.info("====Get_carinfo_error====returncode is:" + resJson.getIntValue("returncode"));
                return;
            }

            JSONArray resultList = resJson.getJSONArray("result");
            for (int i = 0; i < resultList.size(); i++) {
                JSONObject group = resultList.getJSONObject(i);
                JSONArray brandItems = group.getJSONArray("branditems");

                for (int j = 0; j < brandItems.size(); j++) {
                    JSONObject brandItem = brandItems.getJSONObject(j);
                    JSONObject ppJson = new JSONObject();

                    String ppId = brandItem.getString("id");
                    String ppName = brandItem.getString("name");
                    String ppLogo = brandItem.getString("logo");

                    ppJson.put("id", ppId);
                    ppJson.put("name", ppName);
                    if (!ppLogo.startsWith("http")) {
                        ppLogo = "http:" + ppLogo;
                    }
                    ppJson.put("logo", ppLogo);
                    // 新接口没有详情页链接,置为空或根据规则生成
                    ppJson.put("href", "");

                    // 获取是否在映射配置
                    CarTargetBean carTargetBean = carTargetMap.get(ppId);
                    if (carTargetBean != null) {
                        ppId = carTargetBean.getTargetId();
                        ppName = carTargetBean.getTargetName();
                        ppJson.put("id", ppId);
                        ppJson.put("name", ppName);
                        // 映射后通常不使用原Logo,或者沿用原Logo,原逻辑是置空
                        ppJson.put("logo", "");
                    }

                    parseBrandIdentityPhotoImg(ppJson);

                    // 保存父类品牌信息
                    int parentId = carSyncService.saveCarBrandForParent(ppJson);
                    ppJson.put(ServiceConstants.carBrandParentIdKey, parentId);
                    LOGGER.info("保存车品牌信息: " + ppJson.toString());

                    if (!brandItem.containsKey("fctitems")) {
                        continue;
                    }

                    JSONArray fctItems = brandItem.getJSONArray("fctitems");
                    for (int k = 0; k < fctItems.size(); k++) {
                        JSONObject fctItem = fctItems.getJSONObject(k);
                        String childPP = fctItem.getString("name");

                        // 保存车品牌信息 (子品牌)
                        // 注意:这里继续使用 ppJson (包含 Brand ID) 和 childPP (子品牌名称)
                        // 原逻辑:Integer brandId = carSyncService.saveCarBrand(ppJson, childPP);
                        Integer brandId = carSyncService.saveCarBrand(ppJson, childPP);
                        LOGGER.info("保存车子品牌信息: " + childPP);

                        if (!fctItem.containsKey("seriesitems")) {
                            continue;
                        }

                        // 获取所有车系的价格信息
                        Integer realBid = fctItem.getIntValue("realbid");
                        Map<String, JSONObject> priceInfoMap = getCarSeriesPriceInfo(realBid);

                        JSONArray seriesItems = fctItem.getJSONArray("seriesitems");
                        for (int m = 0; m < seriesItems.size(); m++) {
                            JSONObject seriesItem = seriesItems.getJSONObject(m);
                            JSONObject cxJson = new JSONObject();

                            String cxId = seriesItem.getString("id");
                            String cxName = seriesItem.getString("name");

                            cxJson.put("id", cxId);
                            cxJson.put("cx_name", cxName);
                            cxJson.put("child_pp", childPP);

                            // 封装车系价格
                            JSONObject priceInfo = priceInfoMap.get(cxId);
                            if (priceInfo != null) {
                                cxJson.put("cx_zdprice", priceInfo.getDouble("lowPrice"));
                                cxJson.put("lowerPrice", priceInfo.getDouble("lowPrice"));
                                cxJson.put("higherPrice", priceInfo.getDouble("highPrice"));
                            } else {
                                // 新接口不直接包含价格范围,置默认值
                                cxJson.put("cx_zdprice", "暂无");
                                cxJson.put("lowerPrice", 0.0);
                                cxJson.put("higherPrice", 0.0);
                            }

                            cxJson.put("cx_href", "");

                            Integer serId = carSyncService.saveCarSeries(cxJson, brandId);
                            LOGGER.info("===car_series_info===" + cxJson + "__brand=" + brandId);

                            JSONObject reqCarType = new JSONObject();
                            reqCarType.put("brandId", brandId);
                            reqCarType.put("brandName", childPP);
                            reqCarType.put("serId", serId);
                            reqCarType.put("serName", cxName);

                            getCarSeriesInfoV2(cxId, reqCarType);
                        }
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("====Get_carinfo_exception====" + e.getMessage(), e);
        }
    }

    public void getCarSeriesInfoV2(String cxId, JSONObject reqCarType) {
        // 1. 获取车系概况信息,通过车系ID
        String carSeriseViewUrl = "https://car-web-api.autohome.com.cn/car/series/getspeclistresponse?seriesid=" + cxId + "&tagid=1&tagname=";
        // 1.1 请求车系概况接口,解析返回的json数据
        String carSeriseViewRes = HttpUtil.get(carSeriseViewUrl);
        if (StringUtils.isEmpty(carSeriseViewRes)) {
            LOGGER.info("====Get_car_series_info_error==data empty==" + carSeriseViewUrl);
            return;
        }

        JSONObject carSeriseViewJson = JSONObject.parseObject(carSeriseViewRes);
        LOGGER.info("====Get_car_series_info_success==" + carSeriseViewRes);
        int resultCode = carSeriseViewJson.getIntValue("returncode");
        if (resultCode!=0) {
            LOGGER.info("====Get_car_series_info_error====resultCode is:" + resultCode);
            return;
        }

        String carTypeParamsUrl = carSysConfig.getCartypeParamsConfigUrl();
        // 1.2 解析当前在售车型
        boolean isOnSale = CarTypeJsonDeal.getOnSaleStatue(carSeriseViewJson);
        if (isOnSale) {
            String configOnOne = "参数配置未公布";
            List<JSONObject> onSaleList = CarTypeJsonDeal.getOnSaleList(carTypeParamsUrl, carSeriseViewJson, configOnOne, cxId);
            saveToCarTypeData(onSaleList, reqCarType, true);
        }

        // 如果配置false则不同步历史停售的数据
//        String syncRemovedSale = PropertyConfigurer.getString("autohome.removed.sale.sync.config");
        if (!carSysConfig.getSyncRemovedSale()) {
            LOGGER.info("====Get_car_series_info_FILTER====syncRemovedSale is FALSE carseiseId:" + cxId);
            return;
        }

        // 1.3 解析当前停售车型
        List<String> yearNameList = CarTypeJsonDeal.getYearNameList(carSeriseViewJson);
        if (yearNameList.isEmpty()) {
            LOGGER.info("====Get_car_series_info_error====yearNameList is EMPTY carseiseId:" + cxId);
            return;
        }
        for (String yearName : yearNameList) {
            LOGGER.info("====deal cxId:" +cxId+ " car_series_history_info ====yearName:" + yearName);
            String carSeriseHistoryViewUrl = "https://car-web-api.autohome.com.cn/car/series/getspeclistresponse?seriesid=" + cxId + "&tagid=1&tagname=" + yearName;
            String carSeriseHistoryViewRes = HttpUtil.get(carSeriseHistoryViewUrl);
            JSONObject carSeriseHistoryViewJson = JSONObject.parseObject(carSeriseHistoryViewRes);
            int resultHisrotyCode = carSeriseHistoryViewJson.getIntValue("returncode");
            if (resultHisrotyCode!=0) {
                LOGGER.info("====Get_car_series_history_info_error====resultCode is:" + resultHisrotyCode);
                return;
            }

            String configOffOne = "";
            List<JSONObject> offSaleList = CarTypeJsonDeal.getOnSaleList(carTypeParamsUrl, carSeriseViewJson, configOffOne, cxId);
            saveToCarTypeData(offSaleList, reqCarType, false);
        }
    }

    private void saveToCarTypeData(List<JSONObject> saleCarTypeList, JSONObject reqCarType, boolean uploadImage) {
        if (saleCarTypeList.isEmpty()) {
            LOGGER.info("====Get_car_series_info_error====onSaleList is EMPTY");
            return;
        }

        for (JSONObject specCXJson : saleCarTypeList) {
            // 存储车型信息
            saveCxData(specCXJson, reqCarType, uploadImage);
        }
    }

    /**
     * 将汽车之家图片上传到自己服务器
     * @param ppJson
     */
    private void parseBrandIdentityPhotoImg(JSONObject ppJson) {
        String baseLogo = ppJson.getString("logo");
        if (StringUtils.isEmpty(baseLogo)) {
            ppJson.put("upload_url", "");
            return;
        }
        String uploadUrl = dealUploadImageData(baseLogo);
        if (!StringUtils.isEmpty(uploadUrl)) {
            ppJson.put("upload_url", uploadUrl);
        }
    }

    /**
     * 保存车型信息
     * @param trJson
     * @param serTypeJson
     */
    private void saveCxData(JSONObject trJson, JSONObject serTypeJson, boolean uploadImage) {
        if (uploadImage) {
            // todo 暂时屏蔽图片
            trJson.put("cxImage", getCxImageByCxIdV2(trJson.getIntValue("Id")));
        } else {
            trJson.put("cxImage", "");
        }

        // 存储车型信息
        try {
            carSyncService.saveCarType(trJson, serTypeJson);
        } catch (Exception e) {
            LOGGER.error("===uploadImage:"+uploadImage+"===saveCxData_exception:" + trJson.toString(), e);
        }
    }

    /**
     * 新版本获取图片链接,新版本(汽车之家改版后新解析)
     * @param cxId  汽车之家车型ID
     * @return
     */
    private String getCxImageByCxIdV2(int cxId) {
        String imageUrl = CarTypeJsonDeal.getCxImageByCxIdV2(cxId, carSysConfig.getCarautoImgeHost());
        LOGGER.info("===deal cartypeId:{}===dealUploadImageData_imageUrl:{}",cxId, imageUrl);
        return dealUploadImageData(imageUrl);
    }

    private String dealUploadImageData(String imageUrl) {
        if (StringUtils.isEmpty(imageUrl)) {
            return "";
        }

        String urlKey = StringReplaceUtil.replaceUrlToString(imageUrl);
        String uploadUrl = getCxImageCache(urlKey);
        if (StringUtils.isEmpty(uploadUrl)) {
            if (!imageUrl.startsWith("http")) {
                imageUrl = "https:" + imageUrl;
            }

            try {
                // 通过HTTP请求获取图片数据
                byte[] imageData = HttpUtil.downloadBytes(imageUrl);

                // 从URL中提取文件名
                String fileName = "car_image_" + System.currentTimeMillis() + ".jpg";
                if (imageUrl.contains("/")) {
                    String[] parts = imageUrl.substring(imageUrl.lastIndexOf("/") + 1).split("\\?");
                    if (parts.length > 0 && !parts[0].isEmpty()) {
                        fileName = parts[0];
                    }
                }

                // 创建MockMultipartFile对象
                MockMultipartFile file = new MockMultipartFile("file", fileName, "image/jpeg", imageData);
//                MockMultipartFile file = new MockMultipartFile("file", originalFilename, contentType, inputStream);

//             调用文件上传的Feign客户端接口进行文件上传操作
                AjaxResult<FileEntity> upload = fileFeignClient.upload(file);
                LOGGER.info("upload car info image result: {}", upload);
                if (upload != null && upload.getData() != null) {
                    uploadUrl = upload.getData().getUrl();
                }
            } catch (Exception e) {
                LOGGER.error("===dealUploadImageData_exception:" + imageUrl + "__" + e.getMessage(), e);
            }
        }
        if (!StringUtils.isEmpty(uploadUrl)) {
            putCxImageCache(urlKey, uploadUrl);
            return uploadUrl;
        } else {
            return imageUrl;
        }
    }

    private void putCxImageCache(String urlKey, String uploadUrl) {
        redisTemplate.boundHashOps(ServiceConstants.CARTYPE_UPLOADURL_OBJ).put(urlKey, uploadUrl);
    }

    private String getCxImageCache(String urlKey) {
        return (String) redisTemplate.boundHashOps(ServiceConstants.CARTYPE_UPLOADURL_OBJ).get(urlKey);
    }

    /**
     * 将汽车之家的车型映射到指定品牌下(兼容汽车之家改动品牌归属)
     * @return
     */
    private Map<String, CarTargetBean> getCarTargetMap() {
//        String targetRefConfig = PropertyConfigurer.getString("carinfo.sync.target.ref");
        String targetRefConfig = carSysConfig.getTargetRef();
        Map<String, CarTargetBean> resultMap = new HashMap<>();
        
        if (StringUtils.isEmpty(targetRefConfig)) {
            return resultMap;
        }
        
        try {
            // 解析JsonArray格式的配置
            JSONArray configArray = JSONArray.parseArray(targetRefConfig);
            
            for (int i = 0; i < configArray.size(); i++) {
                JSONObject configItem = configArray.getJSONObject(i);
                String targetId = configItem.getString("targetId");
                String targetName = configItem.getString("targetName");
                String autohIds = configItem.getString("autohIds");
                
                // 创建CarTargetBean实例
                CarTargetBean carTargetBean = new CarTargetBean(targetId, targetName);
                
                // 将autohIds按逗号分割,每个id作为map的key
                if (!StringUtils.isEmpty(autohIds)) {
                    String[] idArray = autohIds.split(",");
                    for (String autohId : idArray) {
                        if (!StringUtils.isEmpty(autohId.trim())) {
                            resultMap.put(autohId.trim(), carTargetBean);
                        }
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("解析车型映射配置失败: {}", e.getMessage(), e);
        }
        
        return resultMap;
    }


    private Map<String, JSONObject> getCarSeriesPriceInfo(Integer realBid) {
        // https://car-web-api.autohome.com.cn/car/series/getserieslistbybrandid?brandid=509&source=
        // String priceServerUrl = PropertyConfigurer.getString("carinfo.price.server.url");
        String priceServerUrl = carSysConfig.getPriceServerUrl() + "?brandid=" + realBid + "&source=";

        Map<String, JSONObject> priceMap = new HashMap<>();
        try {
            String jsonRes = HttpUtil.get(priceServerUrl);
            if (StringUtils.isEmpty(jsonRes)) {
                LOGGER.info("====Get_car_series_price_error==data empty==" + priceServerUrl);
                return priceMap;
            }

            JSONObject resJson = JSONObject.parseObject(jsonRes);
            if (resJson.getIntValue("returncode") != 0) {
                LOGGER.info("====Get_car_series_price_error====returncode is:" + resJson.getIntValue("returncode"));
                return priceMap;
            }

            JSONObject result = resJson.getJSONObject("result");
            JSONArray seriesList = result.getJSONArray("serieslist");
            for (int i = 0; i < seriesList.size(); i++) {
                JSONObject series = seriesList.getJSONObject(i);
                String seriesId = series.getString("seriesid");

                JSONObject priceJson = new JSONObject();
                if (series.containsKey("minprice") && !series.get("minprice").toString().isEmpty()) {
                    BigDecimal lowPrice = new BigDecimal(series.getIntValue("minprice")).divide(new BigDecimal(10000), 2, RoundingMode.HALF_UP);
                    priceJson.put("lowPrice", lowPrice.doubleValue());
                }
                if (series.containsKey("maxprice") && !series.get("maxprice").toString().isEmpty()) {
                    BigDecimal highPrice = new BigDecimal(series.getIntValue("maxprice")).divide(new BigDecimal(10000), 2, RoundingMode.HALF_UP);
                    priceJson.put("highPrice", highPrice.doubleValue());
                }
                priceMap.put(seriesId, priceJson);
            }
        } catch (Exception e) {
            LOGGER.error("====Get_car_series_price_exception====" + e.getMessage(), e);
        }

        return priceMap;
    }


}