VideoServiceImpl.java 11.6 KB
package com.bsth.service.impl.videoimpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.bsth.entity.Business;
import com.bsth.entity.Line;
import com.bsth.entity.video.VideoChannel;
import com.bsth.entity.video.VideoTree;
import com.bsth.service.BusinessService;
import com.bsth.service.LineService;
import com.bsth.service.video.VideoService;
import com.bsth.util.HttpClientUtils;
import com.bsth.util.MailUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.geolatte.geom.M;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author liujun
 * @date 2024年07月01日 12:57
 */
@Service
@Slf4j
public class VideoServiceImpl implements VideoService {
    @Autowired
    private BusinessService businessService;
    @Autowired
    private LineService lineService;
    @Autowired
    private WvpConfig wvpConfig;


    @Override
    public List<VideoTree> combinationTree() {
        List<VideoTree> returnList = new ArrayList<>();

        List<VideoTree> bussessTree = queryBusiness();
        if (CollectionUtils.isNotEmpty(bussessTree)) {
            returnList.addAll(bussessTree);
        }

//        List<VideoTree> lineTree = queryLine();
//        if (CollectionUtils.isNotEmpty(lineTree)) {
//            returnList.addAll(lineTree);
//        }
        return returnList;

    }

    @Override
    public List<Map<String, Object>> getVideoChannel(String carNo) throws Exception {
        return getWvpVideoChannelByCarNo(carNo);
    }

    @Override
    public List<Map<String, Object>> getVideoChannelHistoryList(String device, String channel, String dateStr,String token) throws Exception {
        return getVideoChannelHistoryListReq(device, channel, dateStr,token);
    }

    @Override
    public String getToken() throws Exception {
        return getWvpLoginToken();
    }


    /***
     *查询公交公司的数据。
     * @author liujun
     * @date 2024/6/27 11:29
     * @return java.util.List<com.bsth.entity.video.VideoTree>
     */
    private List<VideoTree> queryBusiness() {
        Iterable<Business> businessIterable = businessService.list(new HashMap<>());
        if (Objects.isNull(businessIterable)) {
            return Collections.emptyList();
        }

        List<VideoTree> trees = new ArrayList<>();
        Iterator<Business> iterator = businessIterable.iterator();
        while (iterator.hasNext()) {
            Business business = iterator.next();
            VideoTree videoTree = combinationVideoTree(business.getBusinessCode(), business.getBusinessName(), business.getUpCode(), business.getId(), null, null, business.getBusinessCode());
            trees.add(videoTree);
        }
        List<VideoTree> groupTree = new ArrayList<>();
        for (VideoTree tree : trees) {
            if (Objects.equals(tree.getNodePValue(), "0")) {
                VideoTree target = new VideoTree();
                BeanUtils.copyProperties(tree, target);
//                target.setParent("#");
                target.setType(0);
                groupTree.add(target);
            }
        }

        if (CollectionUtils.isNotEmpty(groupTree)) {
            for (VideoTree tree : groupTree) {
                groupTree(trees, tree);
            }
        }

        return groupTree;
    }

    private List<VideoTree> queryLine() {
        Iterable<Line> lines = lineService.list(new HashMap<>());
        if (Objects.isNull(lines)) {
            return Collections.emptyList();
        }

        List<VideoTree> trees = new ArrayList<>();
        Iterator<Line> iterator = lines.iterator();
        while (iterator.hasNext()) {
            Line line = iterator.next();
            VideoTree videoTree = combinationVideoTree(line.getId(), line.getName(), line.getCompany(), line.getId(), 2, null, null);
            trees.add(videoTree);
        }


        return trees;
    }

    private List<VideoTree> queryCars() {
        return null;
    }

    /***
     * 组合树
     * @author liujun
     * @date 2024/6/27 13:12
     * @param id id
     * @param text 显示的文本
     * @param sourceId 数据的ID
     * @param parent 数据的父节点
     * @param type 类型
     * @param icon 图标
     * @return com.bsth.entity.video.VideoTree
     */
    private VideoTree combinationVideoTree(Object id, String text, String parent, Integer sourceId, Integer type, String icon, Object code) {
        VideoTree videoTree = new VideoTree();
        videoTree.setId(id);
        videoTree.setText(text);
        videoTree.setSourceId(sourceId);
        videoTree.setNodePValue(parent);
        videoTree.setType(type);
//        videoTree.setIcon(icon);
        videoTree.setCode(code);
        return videoTree;
    }

    private void groupTree(List<VideoTree> trees, VideoTree tree) {
        if (Objects.isNull(trees) || CollectionUtils.isEmpty(trees)) {
            return;
        }
        for (VideoTree videoTree : trees) {
            if (Objects.equals(videoTree.getNodePValue(), tree.getId())) {
                if (Objects.isNull(tree.getChildren())) {
                    tree.setChildren(new ArrayList<>());
                }
                VideoTree target = new VideoTree();
                BeanUtils.copyProperties(videoTree, target);
                target.setType(tree.getType() + 1);


                tree.getChildren().add(target);
                groupTree(trees, target);
            }
        }
    }

    /***
     * 获取wvp 系统的登陆token
     * @author liujun
     * @date 2024/7/2 16:16
     * @return java.lang.String
     */
    private String getWvpLoginToken() throws Exception {
        StringBuilder url = new StringBuilder();
        url.append(wvpConfig.getLoginURL());
        if (StringUtils.indexOf(wvpConfig.getLoginURL(), "?") == -1) {
            url.append("?");
        }
        url.append("username=");
        url.append(wvpConfig.getUserName());
        url.append("&password=");
        url.append(wvpConfig.getPwd());
        try {
            StringBuilder result = HttpClientUtils.get(url.toString());
            Map<String, Object> resultMap = (Map<String, Object>) switchWVPResult(result, url);
            if (MapUtils.isEmpty(resultMap)) {
                return null;
            }
            return Objects.isNull(resultMap.get("accessToken")) ? null : resultMap.get("accessToken").toString();

        } catch (Exception e) {
            log.error("[{}]请求异常:", url, e);
            throw e;
        }
    }

    private List<Map<String, Object>> getWvpVideoChannelByCarNo(String carNo) throws Exception {
        String token = getWvpLoginToken();
        if (StringUtils.isEmpty(token)) {
            log.error("wvp login token is null");
            return Collections.emptyList();
        }
        Map<String, Object> headers = new HashMap<>();
        headers.put("Access-Token", token);
        String url = StringUtils.replace(wvpConfig.getChannelListOfCarNoURL(), "{carNo}", carNo);
        try {
            StringBuilder result = get(url, headers);
            return (List<Map<String, Object>>) switchWVPResult(result, url);

        } catch (Exception e) {
            log.error("get wvp of channel list error[{}];", url, e);
            throw e;
        }
    }

    private List<Map<String, Object>> getVideoChannelHistoryListReq(String device, String channel, String dateStr,String token) throws Exception {
        if (StringUtils.isEmpty(token)) {
            log.error("wvp login token is null");
            return Collections.emptyList();
        }
        Map<String, Object> headers = new HashMap<>();
        headers.put("Access-Token", token);


        String url = StringUtils.replace(wvpConfig.getWvpChannelHistoryUrl(), "{device}", device);
        url = StringUtils.replace(url, "{channel}", channel);
        url = StringUtils.replace(url, "{startTimeStr}", dateStr + "%2000:00:00");
        url = StringUtils.replace(url, "{endTimeStr}", dateStr + "%2023:59:59");

        try {
            StringBuilder result = get(url, headers);
            Map<String, Object> resulMap = (Map<String, Object>) switchWVPResult(result, url);
            if (MapUtils.isEmpty(resulMap)) {
                return Collections.emptyList();
            }

            List<Map<String, Object>> recordList = (List<Map<String, Object>>) resulMap.get("recordList");

            return CollectionUtils.isEmpty(recordList) ? Collections.emptyList() : recordList;
        } catch (Exception e) {
            log.error("get wvp of channel history list error[{}];", url, e);
            throw e;
        }
    }

    public static StringBuilder get(String url, Map<String, Object> headers) throws Exception {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        StringBuilder stringBuffer = null;
        try {
            httpClient = HttpClientUtils.defaultHttpClient(url);
            HttpGet get = new HttpGet(url);

            if (MapUtils.isNotEmpty(headers)) {
                for (Map.Entry<String, Object> header : headers.entrySet()) {
                    get.setHeader(header.getKey(), String.valueOf(header.getValue()));
                }
            }
            //超时时间
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(12500).setConnectionRequestTimeout(12000)
                    .setSocketTimeout(13500).build();
            get.setConfig(requestConfig);

            response = httpClient.execute(get);
            stringBuffer = getResult(response.getEntity());
        } catch (Exception e) {
            log.error("", e);
            throw e;
        } finally {
            if (null != httpClient)
                httpClient.close();
            if (null != response)
                response.close();
        }
        return stringBuffer;
    }

    private static StringBuilder getResult(HttpEntity entity) throws IOException {
        StringBuilder stringBuffer = null;
        if (null != entity) {
            BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
            stringBuffer = new StringBuilder();
            String str = "";
            while ((str = br.readLine()) != null)
                stringBuffer.append(str);
        }
        return stringBuffer;
    }

    /***
     * 解析wvp系统返回的数据
     * @author liujun
     * @date 2024/7/2 14:43
     * @param result
     * @param url
     * @return java.lang.Object
     */
    private Object switchWVPResult(Object result, Object url) {
        log.info("[{}]请求返回的数据:[{}]", url, result);
        if (Objects.nonNull(result)) {
            String resultStr = result.toString();
            if (StringUtils.isNotEmpty(resultStr)) {
                Map<String, Object> resultMap = (Map<String, Object>) JSON.parse(resultStr);
                Integer code = (Integer) resultMap.get("code");
                if (Objects.equals(0, code)) {
                    return resultMap.get("data");
                }
            }

        }
        return null;
    }

}