package com.offline.music.playermp3.network;

import com.offline.music.playermp3.helper.CommonUtils;
import com.offline.music.playermp3.helper.MyValue;
import com.offline.music.playermp3.javabean.response.ResponseCategoryList;
import com.offline.music.playermp3.javabean.response.ResponsePlayListInfo;
import com.offline.music.playermp3.javabean.response.ResponsePlayUrl;
import com.offline.music.playermp3.javabean.response.ResponseResult;
import com.offline.music.playermp3.javabean.response.ResponseResultList;
import com.offline.music.playermp3.javabean.response.ResponseSearch;
import com.offline.music.playermp3.javabean.response.child.ResponseCategory;
import com.offline.music.playermp3.javabean.response.ResponseHome;
import com.offline.music.playermp3.javabean.response.child.ResponseHomeChild;
import com.offline.music.playermp3.javabean.response.child.ResponseResultListChild;
import com.offline.music.playermp3.javabean.response.child.ResponseSearchChild;
import com.offline.music.playermp3.javabean.response.child.ResponseSingle;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class JsonHelper {


    /**
     * 解析首页单曲
     *
     * @param jsonObject
     * @return
     */
    public static ResponseHome ResolveHomeJson(JSONObject jsonObject) {
        ResponseHome responseHome = new ResponseHome();
        try {
            String bgUrl = getCovertUrl(jsonObject.getJSONObject("background"), true);

            JSONObject sectionListRenderer = jsonObject.getJSONObject("contents").getJSONObject("singleColumnBrowseResultsRenderer").getJSONArray("tabs").getJSONObject(0).getJSONObject("tabRenderer").getJSONObject("content").getJSONObject("sectionListRenderer");

            JSONObject responseContext = jsonObject.getJSONObject("responseContext");
            JSONArray serviceTrackingParams = responseContext.getJSONArray("serviceTrackingParams");
            String visitorData = responseContext.getString("visitorData");


            responseHome.setBackgroundUrl(bgUrl);
            responseHome.setVisitorData(visitorData);
            getCommonHome(sectionListRenderer, responseHome);


        } catch (JSONException exception) {

            exception.printStackTrace();

        }

        return responseHome;
    }


    /**
     * 解析首页不同类型的音乐分类
     *
     * @param jsonObject
     * @return
     */
    public static ResponseHome ResolveHomeMoreJson(JSONObject jsonObject) {
        ResponseHome responseHome = new ResponseHome();
        try {

            JSONObject sectionListContinuation = jsonObject.getJSONObject("continuationContents").getJSONObject("sectionListContinuation");


            JSONObject responseContext = jsonObject.getJSONObject("responseContext");
            JSONArray serviceTrackingParams = responseContext.getJSONArray("serviceTrackingParams");

            getCommonHome(sectionListContinuation, responseHome);

        } catch (JSONException exception) {

            exception.printStackTrace();

        }
        return responseHome;
    }

    /**
     * 解析根据单曲获取的播放列表
     *
     * @param jsonObject
     * @return
     */
    public static List<ResponsePlayListInfo> ResolvePlayListJson(JSONObject jsonObject) {
        List<ResponsePlayListInfo> list = new ArrayList<>();
        try {
            JSONObject playlistPanelRenderer = jsonObject.getJSONObject("contents").getJSONObject("singleColumnMusicWatchNextResultsRenderer").getJSONObject("tabbedRenderer").getJSONObject("watchNextTabbedResultsRenderer").getJSONArray("tabs").getJSONObject(0).getJSONObject("tabRenderer").getJSONObject("content").getJSONObject("musicQueueRenderer").getJSONObject("content").getJSONObject("playlistPanelRenderer");

            JSONArray contents = playlistPanelRenderer.getJSONArray("contents");

            for (int i = 0; i < contents.length(); i++) {
                ResponsePlayListInfo responsePlayListInfo = new ResponsePlayListInfo();
                JSONObject playlistPanelVideoRenderer = contents.getJSONObject(i).getJSONObject("playlistPanelVideoRenderer");

                String maxUrl = getCovertUrl(playlistPanelVideoRenderer, true);

                String smallUrl = getCovertUrl(playlistPanelVideoRenderer, false);



                String songName = getJsonTitle(playlistPanelVideoRenderer.getJSONObject("title"), 0);

                JSONObject longBylineText = playlistPanelVideoRenderer.getJSONObject("longBylineText");
                String singerName = getJsonTitle(longBylineText, 0);
                String AlbumTitle = getJsonTitle(longBylineText, 2);
                String YearRelease = getJsonTitle(longBylineText, 4);

                String SongDuration = getJsonTitle(playlistPanelVideoRenderer.getJSONObject("lengthText"), 0);

                long ms = CommonUtils.convertToMilliseconds(SongDuration);
                String textTime = CommonUtils.convertMillisToTime(ms);
                CommonUtils.LogMsg("----------SongDuration=" + SongDuration + "---ms=" + ms + "---textTime=" + textTime);

                String[] watchEndPoint = getWatchEndPoint(playlistPanelVideoRenderer);

                responsePlayListInfo.setCovert(maxUrl);
                responsePlayListInfo.setSmallCovert(smallUrl);
                responsePlayListInfo.setSongTitle(songName);
                responsePlayListInfo.setSingerName(singerName);
                responsePlayListInfo.setAlbumTitle(AlbumTitle);
                responsePlayListInfo.setYear(YearRelease);
                responsePlayListInfo.setDuration(textTime);
                responsePlayListInfo.setDurationMs(ms);
                responsePlayListInfo.setVideoId(watchEndPoint[0]);
                if (watchEndPoint[0] == null || watchEndPoint[0].isEmpty()) {

                    continue;
                }
                responsePlayListInfo.setPlaylistId(watchEndPoint[1]);
                responsePlayListInfo.setParams(watchEndPoint[2]);
                responsePlayListInfo.setMusicVideoType(watchEndPoint[3]);

                list.add(responsePlayListInfo);

            }


        } catch (JSONException exception) {
            CommonUtils.LogMsg("----------exception=");
            exception.printStackTrace();

        }
        return list;
    }

    /**
     * 解析音乐音频源地址
     *
     * @param jsonObject
     * @return
     */
    public static ResponsePlayUrl ResolvePlayUrlJson(JSONObject jsonObject) {
        try {
            ResponsePlayUrl responsePlayUrl = new ResponsePlayUrl();
            String status = jsonObject.getJSONObject("playabilityStatus").getString("status");
            JSONObject streamingData = jsonObject.getJSONObject("streamingData");
//            JSONArray jsonArray = streamingData.getJSONArray("adaptiveFormats");
//            for (int i = 0; i < jsonArray.length(); i++) {
//                JSONObject jsonIndex = jsonArray.getJSONObject(i);
//
//                String mimeType = jsonIndex.getString("mimeType");
//                String itag = jsonIndex.getString("itag");
//                String url = jsonIndex.getString("url");
//                if (mimeType.contains("video/mp4")) {
//                    String quality = jsonIndex.optString("quality");
//                    if(quality.equals("medium")){
//                        responsePlayUrl.setVideoUrlMedium(url);
//                    }
//
//                }
//                if (mimeType.contains("audio/mp4")) {
//                    String audioQuality1 = jsonIndex.optString("audioQuality");
//                    if (audioQuality1.equals("AUDIO_QUALITY_MEDIUM")) {
//                        responsePlayUrl.setAudioUrlMedium(url);
//                    } else {
//                        responsePlayUrl.setAudioUrlLow(url);
//                    }
//
//                }
//
//            }


            String videoUrl = streamingData.getJSONArray("formats").getJSONObject(0).getString("url");
            responsePlayUrl.setVideoUrlMedium(videoUrl);


            JSONObject videoDetails = jsonObject.getJSONObject("videoDetails");

            String videoId = videoDetails.getString("videoId");
            String title = videoDetails.getString("title");
            JSONArray thumbnails = videoDetails.getJSONObject("thumbnail").getJSONArray("thumbnails");

            String url = thumbnails.getJSONObject(thumbnails.length() - 1).getString("url");


            responsePlayUrl.setBigCovert(url);
            responsePlayUrl.setVideoId(videoId);
            responsePlayUrl.setStatus(status);
            return responsePlayUrl;

        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }

    }


    /**
     * 解析音乐分类合集列表
     * MUSIC_PAGE_TYPE_ALBUM、MUSIC_PAGE_TYPE_PLAYLIST、MUSIC_PAGE_TYPE_USER_CHANNEL
     *
     * @param jsonObject
     * @return
     */
    public static ResponseCategoryList ResolveCategoryList(JSONObject jsonObject, String browseId) {
        try {
            ResponseCategoryList responseCategoryList = new ResponseCategoryList();
            JSONObject contents = jsonObject.getJSONObject("contents");
            JSONObject twoColumnBrowseResultsRenderer = contents.optJSONObject("twoColumnBrowseResultsRenderer");
            if (twoColumnBrowseResultsRenderer != null) {
                // MUSIC_PAGE_TYPE_ALBUM、MUSIC_PAGE_TYPE_PLAYLIST
                JSONObject jsonObject1 = contents
                        .getJSONObject("twoColumnBrowseResultsRenderer");


                JSONObject musicResponsiveHeaderRenderer = jsonObject1
                        .getJSONArray("tabs")
                        .getJSONObject(0)
                        .getJSONObject("tabRenderer")
                        .getJSONObject("content")
                        .getJSONObject("sectionListRenderer")
                        .getJSONArray("contents")
                        .getJSONObject(0)
                        .getJSONObject("musicResponsiveHeaderRenderer");

                //封面图
                String covert = getCovertUrl(musicResponsiveHeaderRenderer.getJSONObject("thumbnail"), true);


                //轻松愉悦的经典摇滚乐
                String title = getJsonTitle(musicResponsiveHeaderRenderer.getJSONObject("title"), 0);

                String description = "";


                JSONObject straplineTextOne = musicResponsiveHeaderRenderer.optJSONObject("straplineTextOne");
                if (straplineTextOne != null) {
                    String jsonTitle = getJsonTitle(straplineTextOne, 0);
                    responseCategoryList.setSingName(jsonTitle);
                }

                //110 首歌曲.超过6小时
                String secondSubtitle = getJsonTextNew(musicResponsiveHeaderRenderer.getJSONObject("secondSubtitle"));

                if (musicResponsiveHeaderRenderer.has("description")) {
                    //-----------------单曲合集类型
                    //Hold on to the feeling.
                    description = getJsonTitle(musicResponsiveHeaderRenderer.getJSONObject("description")
                            .getJSONObject("musicDescriptionShelfRenderer")
                            .getJSONObject("description"), 0);
                }
                if (musicResponsiveHeaderRenderer.has("subtitle")) {
                    //-----------------专辑类型
                    //专辑.1998
                    description = getJsonTextNew(musicResponsiveHeaderRenderer.getJSONObject("subtitle"));
                }


                responseCategoryList.setCovert(covert);
                responseCategoryList.setDescription(description);
                responseCategoryList.setTitle(title);
                responseCategoryList.setSecondSubtitle(secondSubtitle);

                CommonUtils.LogMsg("-------------title=" + title + "--description=" + description + "---secondSubtitle=" + secondSubtitle + "---covert=" + covert);

                JSONObject contentsArray = jsonObject1.getJSONObject("secondaryContents")
                        .getJSONObject("sectionListRenderer")
                        .getJSONArray("contents")
                        .getJSONObject(0);
                List<ResponsePlayListInfo> mList = new ArrayList<>();
                if (contentsArray.has("musicPlaylistShelfRenderer")) {
                    // MUSIC_PAGE_TYPE_PLAYLIST、MUSIC_PAGE_TYPE_USER_CHANNEL
                    JSONArray jsonArray = contentsArray.getJSONObject("musicPlaylistShelfRenderer")
                            .getJSONArray("contents");


                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject arrayJSONObject = jsonArray.getJSONObject(i).getJSONObject("musicResponsiveListItemRenderer");
                        ResponsePlayListInfo child = getCommonCategoryList(arrayJSONObject);
                        String thumbnail = getCovertUrl(arrayJSONObject.getJSONObject("thumbnail"), true);
//                        CommonUtils.LogMsg("----图片-------------thumbnail=" + thumbnail);
                        child.setSmallCovert(thumbnail);
//                child.setCovert(thumbnail);


                        if (child.getVideoId() == null || child.getVideoId().isEmpty()) {
//                            CommonUtils.LogErrorMsg("--歌曲" + i + "-------------SongTitle=" + child.getSongTitle() + "--getVideoId=" + child.getVideoId() + "---请求参数browseId=" + browseId);
                            continue;
                        }
                        mList.add(child);

                    }
                }
                if (contentsArray.has("musicShelfRenderer")) {
                    //  MUSIC_PAGE_TYPE_ALBUM
                    JSONArray jsonArray = contentsArray.getJSONObject("musicShelfRenderer")
                            .getJSONArray("contents");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject arrayJSONObject = jsonArray.getJSONObject(i).getJSONObject("musicResponsiveListItemRenderer");
                        ResponsePlayListInfo child = getCommonCategoryList(arrayJSONObject);
                        child.setCovert(covert);
                        child.setSmallCovert(covert);
                        if (child.getVideoId() == null || child.getVideoId().isEmpty()) {
                            continue;
                        }
                        mList.add(child);
                    }

                }


                responseCategoryList.setList(mList);
            }


            return responseCategoryList;

        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }

    }


    public static List<String> ResolveSearchSuggestion(JSONObject jsonObject) {
        try {
            List<String> stringList = new ArrayList<>();
            JSONArray contents = jsonObject.getJSONArray("contents");
            for (int i = 0; i < contents.length(); i++) {
                JSONArray jsonArray = contents.getJSONObject(i)
                        .getJSONObject("searchSuggestionsSectionRenderer")
                        .getJSONArray("contents");

                for (int j = 0; j < jsonArray.length(); j++) {

                    JSONObject searchSuggestionRenderer = jsonArray.getJSONObject(j)
                            .optJSONObject("searchSuggestionRenderer");
                    if (searchSuggestionRenderer != null) {
                        String string = searchSuggestionRenderer
                                .getJSONObject("navigationEndpoint")
                                .getJSONObject("searchEndpoint")
                                .getString("query");
                        stringList.add(string);
                    }

                }

            }

            return stringList;

        } catch (JSONException e) {
            CommonUtils.LogErrorMsg("--" + e.getMessage());
            return null;
        }

    }


    /**
     * 解析搜索结果
     *
     * @param jsonObject
     */
    public static List<ResponseSearch> ResolveSearchResult(JSONObject jsonObject) {
        try {
            JSONArray jsonArray = jsonObject.getJSONObject("contents")
                    .getJSONObject("tabbedSearchResultsRenderer")
                    .getJSONArray("tabs")
                    .getJSONObject(0)
                    .getJSONObject("tabRenderer")
                    .getJSONObject("content")
                    .getJSONObject("sectionListRenderer")
                    .getJSONArray("contents");

            List<ResponseSearch> searchList = new ArrayList<>();
            for (int i = 0; i < jsonArray.length(); i++) {
                ResponseSearch responseSearch = new ResponseSearch();
                JSONArray contents1 = null;

                String headerTitle = "";

                JSONObject contents = jsonArray.getJSONObject(i);

                //最佳结果
                JSONObject musicCardShelfRenderer = contents.optJSONObject("musicCardShelfRenderer");

                JSONObject musicShelfRenderer = contents.optJSONObject("musicShelfRenderer");

                if (musicCardShelfRenderer != null) {
                    String covertUrl = getCovertUrl(musicCardShelfRenderer.getJSONObject("thumbnail"), true);
                    String title = getJsonTitle(musicCardShelfRenderer.getJSONObject("title"), 0);
                    String subtitle = getJsonTextNew(musicCardShelfRenderer.getJSONObject("subtitle"));

                    headerTitle = getJsonTitle(musicCardShelfRenderer.getJSONObject("header")
                            .getJSONObject("musicCardShelfHeaderBasicRenderer")
                            .getJSONObject("title"), 0);
                    contents1 = musicCardShelfRenderer.optJSONArray("contents");


                    JSONObject jsonObject1 = musicCardShelfRenderer.getJSONObject("title")
                            .getJSONArray("runs")
                            .getJSONObject(0);
                    String[] browser = getBrowser(jsonObject1);
                    if (browser != null) {
                        responseSearch.setBeastBrowserId(browser[0]);
                        responseSearch.setPageType(browser[1]);


                    }
                    String[] watchEndPoint = getWatchEndPoint(jsonObject1);
                    if (watchEndPoint != null) {
                        responseSearch.setBeastVideoId(watchEndPoint[0]);
                    }

                    responseSearch.setBeastSongTCovert(covertUrl);
                    responseSearch.setBeastSongTitle(title);
                    responseSearch.setBeastSongDescribe(subtitle);

                    CommonUtils.LogMsg("--搜索结果 最佳" + "--songTitle=" + responseSearch.getBeastSongTitle() + "---videoId=" + responseSearch.getBeastVideoId() + "---browserId=" + responseSearch.getBeastBrowserId());
                } else if (musicShelfRenderer != null) {
                    headerTitle = getJsonTitle(musicShelfRenderer.getJSONObject("title"), 0);
                    contents1 = musicShelfRenderer.optJSONArray("contents");
                }

                responseSearch.setHeaderTitle(headerTitle);

                List<ResponseSearchChild> list = new ArrayList<>();
                if (contents1 != null) {
                    for (int k = 0; k < contents1.length(); k++) {
                        ResponseSearchChild responseSearchChild = new ResponseSearchChild();

                        JSONObject musicResponsiveListItemRenderer = contents1.getJSONObject(k)
                                .optJSONObject("musicResponsiveListItemRenderer");

                        String playCount = "";
                        String songTitle = "";
                        String videoId = "";
                        String describe = "";
                        String browserId = "";
                        String pageType = "";

                        String covertUrl1 = "";
                        if (musicResponsiveListItemRenderer != null) {
                            covertUrl1 = getCovertUrl(musicResponsiveListItemRenderer.
                                    getJSONObject("thumbnail")
                                    .getJSONObject("musicThumbnailRenderer"), true);


                            String[] browser1 = getBrowser(musicResponsiveListItemRenderer);
                            if (browser1 != null) {
                                browserId = browser1[0];
                                pageType = browser1[1];
                                if (Objects.equals(pageType, "MUSIC_PAGE_TYPE_PODCAST_SHOW_DETAIL_PAGE") || pageType.equals("MUSIC_PAGE_TYPE_USER_CHANNEL")) {
                                    //博客或者个人资料
                                    continue;
                                }
                            }

                            JSONArray flexColumns = musicResponsiveListItemRenderer.getJSONArray("flexColumns");
                            for (int h = 0; h < flexColumns.length(); h++) {
                                JSONObject musicResponsiveListItemFlexColumnRenderer = flexColumns.getJSONObject(h)
                                        .getJSONObject("musicResponsiveListItemFlexColumnRenderer");
                                JSONObject text = musicResponsiveListItemFlexColumnRenderer.getJSONObject("text");
                                if (h == 0) {
                                    songTitle = getJsonTitle(text, 0);
                                    String[] runs = getWatchEndPoint(text.getJSONArray("runs").getJSONObject(0));
                                    videoId = runs[0];
                                } else if (h == 1) {
                                    describe = getJsonTextNew(text);
                                } else {
                                    playCount = getJsonTitle(text, 0);
                                }


                            }
                            boolean b = videoId == null || videoId.isEmpty();
                            if (b && pageType.isEmpty()) {
                                continue;
                            }
                            responseSearchChild.setBrowserId(browserId);
                            responseSearchChild.setPageType(pageType);
                            responseSearchChild.setSongCovert(covertUrl1);
                            responseSearchChild.setSongTitle(songTitle);
                            responseSearchChild.setSongDescribe(describe);
                            responseSearchChild.setSongPlayCount(playCount);
                            responseSearchChild.setSongVideoId(videoId);
                            CommonUtils.LogMsg("--搜索结果 videoId=" + videoId + "--songTitle=" + songTitle + "---browserId=" + browserId + "---pageType=" + pageType);
                            list.add(responseSearchChild);
                        }


                    }
                }
                if (list.size() > 0) {
                    responseSearch.setList(list);
                }
                if (musicCardShelfRenderer != null) {
                    searchList.add(responseSearch);
                } else if (list.size() > 0) {
                    searchList.add(responseSearch);
                }

            }
            return searchList;

        } catch (JSONException e) {
            CommonUtils.LogErrorMsg("--" + e.getMessage());
            return null;

        }
    }


    /**
     * 根据搜索结果返回的browserId 进行请求返回的数据列表
     *
     * @return
     */
    public static ResponseResult ResolveSearchResultList(JSONObject jsonObject) {
        try {
            ResponseResult responseResult = new ResponseResult();

            JSONObject contents = jsonObject.getJSONObject("contents");
            JSONObject musicImmersiveHeaderRenderer = jsonObject.getJSONObject("header")
                    .getJSONObject("musicImmersiveHeaderRenderer");

            String mainTitle = getJsonTitle(musicImmersiveHeaderRenderer.getJSONObject("title"), 0);
            String thumbnail = getCovertUrl(musicImmersiveHeaderRenderer.getJSONObject("thumbnail"), true);

            responseResult.setMainTitle(mainTitle);
            responseResult.setMainCovert(thumbnail);

            JSONObject singleColumnBrowseResultsRenderer = contents.optJSONObject("singleColumnBrowseResultsRenderer");
            if (singleColumnBrowseResultsRenderer != null) {
                JSONArray contentsArray = singleColumnBrowseResultsRenderer
                        .getJSONArray("tabs")
                        .getJSONObject(0)
                        .getJSONObject("tabRenderer")
                        .getJSONObject("content")
                        .getJSONObject("sectionListRenderer")
                        .getJSONArray("contents");
                List<ResponseResultList> list = new ArrayList<>();
                for (int a = 0; a < contentsArray.length(); a++) {
                    ResponseResultList resultList = new ResponseResultList();
                    List<ResponseResultListChild> childList = new ArrayList<>();


                    JSONObject arrayJSONObject = contentsArray.getJSONObject(a);
                    JSONObject musicShelfRenderer = arrayJSONObject.optJSONObject("musicShelfRenderer");
                    JSONObject musicCarouselShelfRenderer = arrayJSONObject.optJSONObject("musicCarouselShelfRenderer");
                    if (musicShelfRenderer != null) {
                        String headerTitle = getJsonTitle(musicShelfRenderer.getJSONObject("title"), 0);
                        resultList.setHeaderTitle(headerTitle);
                        CommonUtils.LogMsg("----------结果子页面111--------------------headerTitle" + headerTitle);
                        JSONArray contents1 = musicShelfRenderer.getJSONArray("contents");
                        for (int f = 0; f < contents1.length(); f++) {
                            ResponseResultListChild responseResultListChild = new ResponseResultListChild();

                            JSONObject musicResponsiveListItemRenderer = contents1.getJSONObject(f)
                                    .getJSONObject("musicResponsiveListItemRenderer");

                            String thumbnail1 = getCovertUrl(musicResponsiveListItemRenderer.getJSONObject("thumbnail"), true);

                            JSONArray flexColumns = musicResponsiveListItemRenderer.getJSONArray("flexColumns");

                            String songName = "";
                            String singerName = "";
                            String playCount = "";
                            String videoId = "";
                            String playLIstId = "";
                            for (int b = 0; b < flexColumns.length(); b++) {
                                JSONObject jsonObject1 = flexColumns.getJSONObject(b)
                                        .getJSONObject("musicResponsiveListItemFlexColumnRenderer")
                                        .getJSONObject("text");

                                switch (b) {
                                    case 0:
                                        songName = getJsonTitle(jsonObject1, 0);
                                        String[] watchEndPoint = getWatchEndPoint(jsonObject1.getJSONArray("runs").getJSONObject(0));
                                        videoId = watchEndPoint[0];
                                        playLIstId = watchEndPoint[1];
                                        break;
                                    case 1:
                                        singerName = getJsonTitle(jsonObject1, 0);
                                        break;
                                    case 2:
                                        playCount = getJsonTitle(jsonObject1, 0);
                                        break;
                                }
                            }

                            responseResultListChild.setThumbnail(thumbnail1);
                            responseResultListChild.setSongName(songName);
                            responseResultListChild.setSubTitle(singerName);
                            responseResultListChild.setPlayCount(playCount);
                            responseResultListChild.setVideoId(videoId);
                            responseResultListChild.setPlayListId(playLIstId);

                            CommonUtils.LogMsg("----------结果子页面111 songName=" + songName + "---videoId=" + videoId + "--playLIstId=" + playLIstId);
                            childList.add(responseResultListChild);
                        }
                    } else if (musicCarouselShelfRenderer != null) {
                        String headerTitle = getJsonTitle(musicCarouselShelfRenderer.getJSONObject("header")
                                .getJSONObject("musicCarouselShelfBasicHeaderRenderer")
                                .getJSONObject("title"), 0);
                        resultList.setHeaderTitle(headerTitle);
                        CommonUtils.LogMsg("----------结果子页面222--------------------headerTitle" + headerTitle);
                        JSONArray contents1 = musicCarouselShelfRenderer.getJSONArray("contents");
                        for (int f = 0; f < contents1.length(); f++) {
                            ResponseResultListChild responseResultListChild = new ResponseResultListChild();

                            JSONObject musicTwoRowItemRenderer = contents1.getJSONObject(f)
                                    .getJSONObject("musicTwoRowItemRenderer");

                            String thumbnail1 = getCovertUrl(musicTwoRowItemRenderer.getJSONObject("thumbnailRenderer"), true);

                            JSONObject title = musicTwoRowItemRenderer.getJSONObject("title");
                            String albumName = getJsonTitle(title, 0);

                            String[] browser = getBrowser(title.getJSONArray("runs").getJSONObject(0));
                            String subtitle = getJsonTextNew(musicTwoRowItemRenderer.getJSONObject("subtitle"));

                            if (browser != null) {
                                String browserId = browser[0];
                                responseResultListChild.setBrowserId(browserId);
                                responseResultListChild.setPageType(browser[1]);
                            }
                            String[] watchEndPoint = getWatchEndPoint(musicTwoRowItemRenderer);
                            if (watchEndPoint != null) {
                                responseResultListChild.setVideoId(watchEndPoint[0]);
                                responseResultListChild.setPlayListId(watchEndPoint[1]);
                            }
                            responseResultListChild.setThumbnail(thumbnail1);
                            responseResultListChild.setSongName(albumName);
                            responseResultListChild.setSubTitle(subtitle);

                            CommonUtils.LogMsg("----------结果子页面222 songName=" + albumName + "---videoId=" + responseResultListChild.getVideoId() + "--playLIstId=" + responseResultListChild.getPlayListId()
                                    + "---BrowserId=" + responseResultListChild.getBrowserId() + "---PageType=" + responseResultListChild.getPageType());
                            childList.add(responseResultListChild);
                        }
                    }


                    resultList.setChildList(childList);
                    list.add(resultList);
                }


                responseResult.setList(list);

            }
            return responseResult;

        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }


    private static ResponsePlayListInfo getCommonCategoryList(JSONObject musicResponsiveListItemRenderer) throws JSONException {
        JSONObject jsonText = musicResponsiveListItemRenderer.getJSONArray("fixedColumns")
                .getJSONObject(0)
                .getJSONObject("musicResponsiveListItemFixedColumnRenderer")
                .getJSONObject("text");

        String duration = getJsonTitle(jsonText, 0);
        long ms = CommonUtils.convertToMilliseconds(duration);
        //比接口返回的减少一秒
        String textTime = CommonUtils.convertMillisToTime(ms);

        JSONArray flexColumns = musicResponsiveListItemRenderer
                .getJSONArray("flexColumns");

        ResponsePlayListInfo listInfo = new ResponsePlayListInfo();
        //歌名、歌手名字、描述
        String SongTitle = "";
        String SingerName = "";
        String Description = "";
        for (int g = 0; g < flexColumns.length(); g++) {
            JSONObject jsonObjectText = flexColumns.getJSONObject(g)
                    .getJSONObject("musicResponsiveListItemFlexColumnRenderer")
                    .getJSONObject("text");
            String text = getJsonTitle(jsonObjectText, 0);

            CommonUtils.LogMsg("---------g=" + g + "---text=" + text);
            if (g == 0) {
                SongTitle = text;

                JSONObject runs = jsonObjectText.getJSONArray("runs").getJSONObject(0);

                String[] watchEndPoint = getWatchEndPoint(runs);

                listInfo.setVideoId(watchEndPoint[0]);
                if (watchEndPoint[0] == null || watchEndPoint[0].isEmpty()) {
                    CommonUtils.LogMsg("---------getCommonCategoryList-SongTitle=" + SongTitle + "---setVideoId=null");
                }

                listInfo.setPlaylistId(watchEndPoint[1]);
                listInfo.setParams(watchEndPoint[2]);
                listInfo.setMusicVideoType(watchEndPoint[3]);

            }
            if (g == 1) {
                SingerName = text;
            }
            if (g == 2) {
                Description = text;
            }
        }
        listInfo.setDescribe(Description);
        listInfo.setDuration(textTime);
        listInfo.setDurationMs(ms);
        listInfo.setSingerName(SingerName);
        listInfo.setSongTitle(SongTitle);

        return listInfo;
    }

    private static void getCommonHome(JSONObject sectionListRenderer, ResponseHome responseHome) throws JSONException {


        JSONObject nextContinuationData = sectionListRenderer.getJSONArray("continuations").getJSONObject(0).getJSONObject("nextContinuationData");

        //token=continuation,cit= clickTrackingParams

        String clickTrackingParams = nextContinuationData.getString("clickTrackingParams");
        String continuation = nextContinuationData.getString("continuation");

        responseHome.setClickTrackingParams(clickTrackingParams);
        responseHome.setContinuation(continuation);

        JSONArray contents = sectionListRenderer.getJSONArray("contents");

        List<ResponseHomeChild> childList = new ArrayList<>();

        for (int i = 0; i < contents.length(); i++) {
            ResponseHomeChild responseHomeChild = new ResponseHomeChild();
            JSONObject object = contents.getJSONObject(i);

            JSONObject musicCarouselShelfRenderer = object.optJSONObject("musicCarouselShelfRenderer");
            if (musicCarouselShelfRenderer != null) {

                //模块标题
                String title = getJsonTitle(musicCarouselShelfRenderer.getJSONObject("header").getJSONObject("musicCarouselShelfBasicHeaderRenderer").getJSONObject("title"), 0);

                responseHomeChild.setHeaderTitle(title);
                JSONArray childContents = musicCarouselShelfRenderer.getJSONArray("contents");


                List<ResponseCategory> categoryList = new ArrayList<>();
                List<ResponseSingle> singleList = new ArrayList<>();
                for (int j = 0; j < childContents.length(); j++) {
                    JSONObject jsonList = childContents.getJSONObject(j);
                    JSONObject musicResponsiveListItemRenderer = jsonList.optJSONObject("musicResponsiveListItemRenderer");
                    if (musicResponsiveListItemRenderer != null) {
                        //-------------------------单曲
                        ResponseSingle responseSingle = new ResponseSingle();

                        String SingerHead = getCovertUrl(musicResponsiveListItemRenderer.getJSONObject("thumbnail"), true);
//                        CommonUtils.LogMsg("----图片-------------SingerHead=" + SingerHead);

                        JSONArray flexColumns = musicResponsiveListItemRenderer.getJSONArray("flexColumns");

                        //歌名、歌手名字、描述
                        String SongTitle = "";
                        String SingerName = "";
                        String Description = "";
                        for (int g = 0; g < flexColumns.length(); g++) {
                            JSONObject jsonObject = flexColumns.getJSONObject(g).getJSONObject("musicResponsiveListItemFlexColumnRenderer").getJSONObject("text");
                            String text = getJsonTitle(jsonObject, 0);
                            if (g == 0) {
                                SongTitle = text;

                                JSONObject runs = jsonObject.getJSONArray("runs").getJSONObject(0);

                                String[] watchEndPoint = getWatchEndPoint(runs);

                                responseSingle.setVideoId(watchEndPoint[0]);
                                responseSingle.setPlaylistId(watchEndPoint[1]);
                                responseSingle.setParams(watchEndPoint[2]);
                                responseSingle.setMusicVideoType(watchEndPoint[3]);

                            }
                            if (g == 1) {
                                SingerName = text;
                            }
                            if (g == 2) {
                                //这里应该没有值
                                Description = text;
                            }
                        }
                        responseSingle.setSongTitle(SongTitle);
                        responseSingle.setSingerName(SingerName);
                        responseSingle.setSingerHead(SingerHead);
                        responseSingle.setDescription(Description);
                        singleList.add(responseSingle);

                        //"musicVideoType":"MUSIC_VIDEO_TYPE_UGC"
                        if (j == 0)
                            CommonUtils.LogMsg("      ----------111111111111----SongTitle=" + SongTitle + "--getMusicVideoType=" + responseSingle.getMusicVideoType());
                    }

                    JSONObject musicTwoRowItemRenderer = jsonList.optJSONObject("musicTwoRowItemRenderer");
                    if (musicTwoRowItemRenderer != null) {
                        //------------------------音乐合集或者专辑
                        ResponseCategory responseCategory = new ResponseCategory();
                        String covert = getCovertUrl(musicTwoRowItemRenderer.getJSONObject("thumbnailRenderer"), true);

                        JSONObject title1 = musicTwoRowItemRenderer.getJSONObject("title");
                        String twoTitle = getJsonTitle(title1, 0);
                        String twoSubtitle = getJsonTextNew(musicTwoRowItemRenderer.getJSONObject("subtitle"));


                        String browseId = "";
                        String pageType = "";
                        JSONObject runs = title1
                                .getJSONArray("runs")
                                .getJSONObject(0);
                        JSONObject subtitle = musicTwoRowItemRenderer
                                .getJSONObject("subtitle")
                                .getJSONArray("runs")
                                .getJSONObject(0);

                        String[] browser = null;
                        String[] browserTiTle = getBrowser(runs);
                        String[] browserSub = getBrowser(subtitle);
                        if (browserTiTle != null) {
                            browser = browserTiTle;
                        } else {
                            browser = browserSub;
                        }
                        if (browser != null) {
                            //-------------当pageType="MUSIC_PAGE_TYPE_PLAYLIST"或"MUSIC_PAGE_TYPE_ALBUM" 走这里
                            browseId = browser[0];
                            pageType = browser[1];

                            responseCategory.setPageType(pageType);
                            responseCategory.setBrowseId(browseId);
                            if (pageType.equals(MyValue.PAGE_TYPE_MV) || pageType.equals(MyValue.PAGE_TYPE_MV_LIST)) {
                                //视频mv 需要获取videoId 和PlayListId  用于进入播放页面请求播放列表数据

                                JSONObject jsonObject = musicTwoRowItemRenderer.getJSONObject("menu")
                                        .getJSONObject("menuRenderer")
                                        .getJSONArray("items")
                                        .getJSONObject(0)
                                        .getJSONObject("menuNavigationItemRenderer");
                                String[] watchEndPoint = getWatchEndPoint(jsonObject);
                                if (watchEndPoint[0] != null) {
                                    responseCategory.setVideoId(watchEndPoint[0]);
                                }
                                if (watchEndPoint[1] != null) {
                                    responseCategory.setPlayListId(watchEndPoint[1]);
                                }
                                if (watchEndPoint[2] != null) {
                                    responseCategory.setParams(watchEndPoint[2]);
                                }
                                if (watchEndPoint[3] != null) {
                                    responseCategory.setMusicVideoType(watchEndPoint[3]);
                                }
                            }
                        }
                        responseCategory.setCovert(covert);
                        responseCategory.setTwoTitle(twoTitle);
                        responseCategory.setTwoSubtitle(twoSubtitle);
                        categoryList.add(responseCategory);
                        if (j == 0) {

                        }
                    }

                }
                responseHomeChild.setCategoryList(categoryList);
                responseHomeChild.setSingleList(singleList);

                childList.add(responseHomeChild);
            }

        }
        responseHome.setChildList(childList);


    }


    private static String[] getWatchEndPoint(JSONObject job) {

        String[] strings = new String[4];
        try {
            JSONObject navigationEndpoint = job.optJSONObject("navigationEndpoint");
            if (navigationEndpoint == null) {
                return strings;
            }
            JSONObject watchEndpoint = navigationEndpoint.getJSONObject("watchEndpoint");
            if (watchEndpoint.has("videoId")) {
                strings[0] = watchEndpoint.getString("videoId");
            }
            if (watchEndpoint.has("playlistId")) {
                strings[1] = watchEndpoint.getString("playlistId");
            }
            if (watchEndpoint.has("params")) {
                strings[2] = watchEndpoint.getString("params");
            }
            if (watchEndpoint.has("watchEndpointMusicSupportedConfigs")) {
                strings[3] = watchEndpoint.getJSONObject("watchEndpointMusicSupportedConfigs").getJSONObject("watchEndpointMusicConfig").getString("musicVideoType");
            }

        } catch (JSONException exception) {
            exception.printStackTrace();
        }
        return strings;
    }


    /**
     * @param jsonObject
     * @param maxBig     是否取最大的一张图片
     * @return
     */
    private static String getCovertUrl(JSONObject jsonObject, boolean maxBig) {
        try {

            JSONArray jsonArray;
            JSONObject musicThumbnailRenderer = jsonObject.optJSONObject("musicThumbnailRenderer");
            if (musicThumbnailRenderer == null) {
                JSONObject thumbnail = jsonObject.optJSONObject("thumbnail");
                if (thumbnail != null) {
                    jsonArray = thumbnail.getJSONArray("thumbnails");
                } else {
                    return null;
                }
            } else {
                jsonArray = musicThumbnailRenderer.getJSONObject("thumbnail").getJSONArray("thumbnails");
            }

            int length = jsonArray.length();
            int index = 0;
            if (maxBig) {
                index = length - 1;
            } else if (length > 2) {
                index = length - 2;
            }
            String pngUrl = jsonArray.getJSONObject(index).getString("url");
            return pngUrl;
        } catch (JSONException exception) {
            return null;
        }
    }


    private static String[] getBrowser(JSONObject jsonObject) throws JSONException {

        String[] strings = new String[2];
        JSONObject navigationEndpoint = jsonObject.optJSONObject("navigationEndpoint");
        if (navigationEndpoint != null) {

            JSONObject browseEndpoint = navigationEndpoint.optJSONObject("browseEndpoint");
            if (browseEndpoint == null) return null;
            strings[0] = browseEndpoint.getString("browseId");

            strings[1] = browseEndpoint.getJSONObject("browseEndpointContextSupportedConfigs")
                    .getJSONObject("browseEndpointContextMusicConfig")
                    .getString("pageType");
            return strings;
        }
        return null;
    }

    private static String getJsonTitle(JSONObject jsonObject, int index) {
        String text = "";
        try {
            JSONArray runs = jsonObject.getJSONArray("runs");
            if (index < runs.length()) {
                text = runs.getJSONObject(index).getString("text");
            }

        } catch (JSONException exception) {
            return text;
        }
        return text;
    }


    /**
     * runs 数组的字符串拼接
     *
     * @param jsonObject
     * @return
     */
    private static String getJsonTextNew(JSONObject jsonObject) {
        StringBuilder text = new StringBuilder();
        try {
            JSONArray runs = jsonObject.getJSONArray("runs");
            for (int i = 0; i < runs.length(); i++) {
                String text1 = runs.getJSONObject(i).getString("text");
                text.append(text1);
            }

        } catch (JSONException exception) {

        }
        return text.toString();
    }
}
