package com.hi.music.player.ui.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.os.Handler;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.SeekBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.OptIn;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;
import androidx.media3.common.MediaItem;
import androidx.media3.common.MediaMetadata;
import androidx.media3.common.Player;
import androidx.media3.common.util.UnstableApi;
import androidx.media3.datasource.cache.SimpleCache;
import androidx.media3.exoplayer.offline.Download;
import androidx.media3.exoplayer.offline.DownloadManager;
import androidx.media3.exoplayer.offline.DownloadRequest;
import androidx.media3.exoplayer.offline.DownloadService;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.google.gson.Gson;
import com.hi.music.player.MusicApplication;
import com.hi.music.player.R;
import com.hi.music.player.adapter.AdapterDownloadSong;
import com.hi.music.player.adapter.AdapterPlayList;
import com.hi.music.player.api.LikeSongListener;
import com.hi.music.player.api.MediaControllerListener;
import com.hi.music.player.api.onCheckDownload;
import com.hi.music.player.api.onImageColorListener;
import com.hi.music.player.api.onPlayNextListener;
import com.hi.music.player.databinding.ActivityPlayBinding;
import com.hi.music.player.helper.CommonUtils;
import com.hi.music.player.helper.MyValue;
import com.hi.music.player.javabean.BoxDownloadSong;
import com.hi.music.player.javabean.BoxLikeSong;
import com.hi.music.player.javabean.CustomerDownload;
import com.hi.music.player.javabean.CustomerUrlInfo;
import com.hi.music.player.javabean.response.ResponsePlayListInfo;
import com.hi.music.player.javabean.response.ResponsePlayUrl;
import com.hi.music.player.javabean.response.child.ResponseCategory;
import com.hi.music.player.javabean.response.child.ResponseSingle;
import com.hi.music.player.media3.MyDownloadService;
import com.hi.music.player.media3.MyMediaControllerManager;
import com.hi.music.player.media3.MyPlayCacheManager;
import com.hi.music.player.objectbox.ObjectBoxManager;
import com.hi.music.player.ui.activity.viewmodel.VMApplication;
import com.hi.music.player.ui.activity.viewmodel.VMPlay;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class PlayActivity extends BaseActivity<ActivityPlayBinding> implements SeekBar.OnSeekBarChangeListener {


    //单曲进入传递的数据
    private ResponseSingle responseSingle;
    private VMPlay vmPlay;


    private Handler mHandler;
    private Runnable mRunnable;


    private AdapterPlayList adapterPlayList;


    //播放列表ui初始化
    private boolean initPlayList = false;

    private GradientDrawable gradientDrawable;
    private int lighterColor, darkerColor;

    // 0 播放列表请求失败  1 立即播放的歌曲请求失败 2 封面图加载失败
    private int netError = 0;


    // 请求失败的立即播放的歌曲信息
    private CustomerUrlInfo mCustomerUrlInfo;
    private int mEnterType;


    //-------单曲进入播放列表接口请求需要的参数
    private String playlistId, videoId, params, musicVideoType = "";
    //-------单曲进入播放列表接口请求需要的参数

    private int mDefaultPlayStartIndex = 0;


    private int[] imageStates = {
            R.drawable.icon_looper_no,
            R.drawable.icon_looper_1,
            R.drawable.icon_looper
    };

    //0 不循环、1 列表循环、2 单曲循环、
    private int currentMode = 0;

    private List<BoxDownloadSong> downloadSongList = new ArrayList<>();

    @Override
    protected ActivityPlayBinding getViewBinding() {
        return ActivityPlayBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void onCreateInit() {
//        vb.progressBarLoading.setVisibility(View.VISIBLE);
        vmPlay = getActivityScopeViewModel(VMPlay.class);
        initMediaController();
        Intent intent = getIntent();
        mEnterType = intent.getIntExtra(MyValue.KEY_ENTER_SOURCE, MyValue.TYPE_ENTER_SOURCE_SINGLE);
        initPlayerView();
        initProgressHandler();

        CommonUtils.LogMsg("--------mEnterType=" + mEnterType);
        switch (mEnterType) {
            case MyValue.TYPE_ENTER_SOURCE_SINGLE:
                // 0--首页单曲进入
                updateMediaPlayList();
                responseSingle = (ResponseSingle) intent.getSerializableExtra(MyValue.KEY_PLAY_ACTIVITY_SINGER);
                playlistId = responseSingle.getPlaylistId();
                videoId = responseSingle.getVideoId();
                params = responseSingle.getParams();
                musicVideoType = responseSingle.getMusicVideoType();
                mDefaultPlayStartIndex = intent.getIntExtra(MyValue.KEY_PLAY_ACTIVITY_CATEGORY_LIST_INDEX, mDefaultPlayStartIndex);

                SimpleCache playCache = MyPlayCacheManager.getPlayCache();
//                boolean songCached = CommonUtils.isSongCached(playCache, videoId);

//                CommonUtils.LogMsg("---------------是否有播放缓存--songCached="+songCached +"--name="+responseSingle.getSongTitle());

                vmPlay.getPlayMusicList(playlistId, videoId, params, musicVideoType);
                vmPlay.playList.observe(this, new Observer<List<ResponsePlayListInfo>>() {
                    @Override
                    public void onChanged(List<ResponsePlayListInfo> listInfos) {
                        vmApplication.reSetPlayList(listInfos);
                    }
                });
                break;
            case MyValue.TYPE_ENTER_SOURCE_CATEGORY:
                // 1--首页音乐分类合集列表进入

                updateMediaPlayList();
                ResponsePlayListInfo playListInfo = (ResponsePlayListInfo) intent.getSerializableExtra(MyValue.KEY_PLAY_ACTIVITY_CATEGORY_LIST);
                mDefaultPlayStartIndex = intent.getIntExtra(MyValue.KEY_PLAY_ACTIVITY_CATEGORY_LIST_INDEX, mDefaultPlayStartIndex);
                videoId = playListInfo.getVideoId();
                break;

            case MyValue.TYPE_ENTER_SOURCE_MV:
                // 2--首页单个视频mv进入

                updateMediaPlayList();
                ResponseCategory responseCategory = (ResponseCategory) intent.getSerializableExtra(MyValue.KEY_PLAY_ACTIVITY_MV);
                videoId = responseCategory.getVideoId();
                playlistId = responseCategory.getPlayListId();
                params = responseCategory.getParams();
                musicVideoType = responseCategory.getMusicVideoType();
                vmPlay.getPlayMusicList(playlistId, videoId, params, musicVideoType);
                vmPlay.playList.observe(this, new Observer<List<ResponsePlayListInfo>>() {
                    @Override
                    public void onChanged(List<ResponsePlayListInfo> listInfos) {
                        vmApplication.reSetPlayList(listInfos);
                    }
                });

                break;

            case MyValue.TYPE_ENTER_PANEL:
                //  3--控制面板进入
                MediaItem curMediaItem = mediaControllerManager.getCurMediaItem();
                loadInfo(curMediaItem);
                mHandler.post(mRunnable);
                vb.progressBarLoading.setVisibility(View.GONE);
                vb.btnPlay.setSelected(mediaControllerManager.getIsPlaying());
                break;

            case MyValue.TYPE_ENTER_LIKE:
                //  4--从喜爱歌曲进入
                updateMediaPlayList();
                videoId = intent.getStringExtra(MyValue.KEY_PLAY_VIDEO_ID);
                mDefaultPlayStartIndex = intent.getIntExtra(MyValue.KEY_PLAY_INDEX, mDefaultPlayStartIndex);
                CommonUtils.LogMsg("-------------like进入 videoId= " + videoId + "---mDefaultPlayStartIndex=" + mDefaultPlayStartIndex);
                break;

            case MyValue.TYPE_ENTER_DOWNLOAD:
                //  5--从下载歌曲进入
                videoId = intent.getStringExtra(MyValue.KEY_PLAY_VIDEO_ID);
                mDefaultPlayStartIndex = intent.getIntExtra(MyValue.KEY_PLAY_INDEX, mDefaultPlayStartIndex);
                CommonUtils.LogMsg("-------------下载歌曲 videoId= " + videoId + "---mDefaultPlayStartIndex=" + mDefaultPlayStartIndex);
                break;
        }

        addDownloadListener();
        vmPlay.playUrlLiveData.observe(this, new Observer<CustomerUrlInfo>() {
            @Override
            public void onChanged(CustomerUrlInfo customerUrlInfo) {
                if (customerUrlInfo.isNeedPlayNow() && customerUrlInfo.getPlayUrl() == null) {
                    // TODO: 2024/9/26  需要马上播放这首歌曲，但是此次网络请求失败
                    CommonUtils.LogErrorMsg("-------------需要马上播放这首歌曲，但是此次网络请求失败");
                    updateErrorLayout(getString(R.string.song_loading_failed), true);
                    netError = 1;
                    mCustomerUrlInfo = customerUrlInfo;
                    initShowPlayList(false);
                    vb.progressBarLoading.setVisibility(View.GONE);
                    mediaControllerManager.pause();
                    return;
                }
                int second = customerUrlInfo.getPlayMusicIndex();
                if (customerUrlInfo.isNeedPlayNow()) {
                    mediaControllerManager.playPositionMusic(second);
//                    mediaControllerManager.play();
                }
            }
        });


    }


    /**
     * 更新播放列表
     */
    private void updateMediaPlayList() {
        vmApplication.playList.observe(this, new Observer<List<ResponsePlayListInfo>>() {
            @Override
            public void onChanged(List<ResponsePlayListInfo> playList) {
                if (playList == null) {
                    CommonUtils.LogErrorMsg("--------更新-playList null");
                    netError = 0;
                    updateErrorLayout(getString(R.string.playList_loading_failed), true);
                    vb.progressBarLoading.setVisibility(View.GONE);
                    return;
                }
                CommonUtils.LogMsg("--------更新-playList " + playList.size() + "--videoId=" + videoId);
                if (playList.size() > 0) {
                    updateErrorLayout(null, false);
                    setPlayListAndGetUrl(playList, videoId, mDefaultPlayStartIndex);
                }
            }
        });
    }

    private void updateErrorLayout(String msg, boolean isShow) {
        if (isShow)
            vb.layoutError.linearRetry.setVisibility(View.VISIBLE);
        else vb.layoutError.linearRetry.setVisibility(View.GONE);

        if (msg != null && !msg.isEmpty()) {
            vb.layoutError.tvErrorMsg.setText(msg);
        }
    }

    /**
     * 设置播放列表，并请求当前需要播放的音乐url
     *
     * @param list
     * @param id
     * @param index
     */
    @OptIn(markerClass = UnstableApi.class)
    private void setPlayListAndGetUrl(List<ResponsePlayListInfo> list, String id, int index) {
        mediaControllerManager.resetPlayList();
        MyMediaControllerManager.getInstance().setPlayList(list);
        MyDownloadService.queryIsDownload(id, new onCheckDownload() {
            @Override
            public void onHasDownload(CustomerDownload customerDownload) {
                if(customerDownload.isDownload()){
                    MediaItem mediaItem = CommonUtils.downloadToMediaItem(customerDownload.getDownloadData());
                    mediaControllerManager.replaceMediaItem(index,mediaItem);
                    CommonUtils.LogMsg("-------------setPlayListAndGetUrl已经下载过  index" + index + "---playNow=" + true);
                    mediaControllerManager.playPositionMusic(index);
                }else {
                    CommonUtils.LogMsg("-------------setPlayListAndGetUrl index" + index + "---playNow=" + true);
                    vmPlay.getPlayUrl(id, index, true);
                }

            }
        });

    }

    @OptIn(markerClass = UnstableApi.class)
    private void initPlayerView() {
        vb.playerView.setShowRewindButton(false);
        vb.playerView.setShowPreviousButton(false);
        vb.playerView.setPlayer(mediaControllerManager.getMediaController());
    }

    private void initMediaController() {
        int repeatMode = mediaControllerManager.getRepeatMode();
        CommonUtils.LogMsg("-------------repeatMode=" + repeatMode);
        vb.btnLoop.setImageResource(imageStates[repeatMode]);
        mediaControllerManager.addListener(vmApplication, new MediaControllerListener() {
            @Override
            public void onPlayStatus(int playStatus) {

                switch (playStatus) {
                    case Player.STATE_IDLE:
                        CommonUtils.LogMsg("-------------IDLE");
                        break;
                    case Player.STATE_BUFFERING:
                        //快进没有缓冲的时候触发
                        vb.btnPlay.setSelected(false);
//                        vb.progressBarLoading.setVisibility(View.VISIBLE);
                        CommonUtils.LogMsg("-------------缓冲");
                        break;
                    case Player.STATE_READY:
                        vb.btnPlay.setSelected(true);
                        mHandler.post(mRunnable);
                        vb.progressBarLoading.setVisibility(View.GONE);
                        CommonUtils.LogMsg("-------------准备");
                        break;

                    case Player.STATE_ENDED:
                        //播放完成
                        vb.btnPlay.setSelected(false);
                        CommonUtils.LogMsg("------------- 播放完成");
                        mHandler.removeCallbacks(mRunnable); // 停止更新
                        updatePlayComplete();
                        break;

                    case MyValue.PLAY_STATUS_CODE_PAUSE:
                        CommonUtils.LogMsg("------------- 暂停");
                        vb.btnPlay.setSelected(false);
                        vb.layoutPlayList.imPlay.setSelected(false);
                        break;
                    case MyValue.PLAY_STATUS_CODE_PLAYING:

                        CommonUtils.LogMsg("------------- 播放ing getCurIndex=" + mediaControllerManager.getCurIndex());
                        vb.progressBarLoading.setVisibility(View.GONE);
                        updateErrorLayout(null, false);
                        vb.btnPlay.setSelected(true);
                        vb.layoutPlayList.imPlay.setSelected(true);
                        break;
                    case MyValue.PLAY_STATUS_CODE_ERROR:
                        vb.progressBarLoading.setVisibility(View.GONE);
                        int currentMediaItemIndex = mediaControllerManager.getMediaController().getCurrentMediaItemIndex();
                        CommonUtils.LogMsg("-------------  播放错误 currentMediaItemIndex=" + currentMediaItemIndex);
                        mediaControllerManager.playPositionMusic(currentMediaItemIndex);
                        // TODO: 2024/10/16  
                        break;

                }
            }

            @Override
            public void onRequestNextUri(String videoId, int playListIndex, boolean playNow) {
                if (playNow) {
//                    vb.progressBarLoading.setVisibility(View.VISIBLE);
                }
                vmPlay.getPlayUrl(videoId, playListIndex, playNow);
            }


            @Override
            public void onChangeMusic(MediaItem mediaItem) {
                CommonUtils.LogMsg("歌曲切换-" + mediaItem.mediaMetadata.title + "---id=" + mediaItem.mediaId);
                loadInfo(mediaItem);
            }

        });
    }

    @Override
    protected void onInitClick() {
        vb.btnPlay.setOnClickListener(this);
        vb.playProgress.setOnSeekBarChangeListener(this);
        vb.btnNext.setOnClickListener(this);
        vb.btnPrevious.setOnClickListener(this);
        vb.imBack.setOnClickListener(this);
        vb.btnMusicList.setOnClickListener(this);
        vb.layoutError.tvRetry.setOnClickListener(this);
        vb.btnLoop.setOnClickListener(this);
        vb.layoutLike.setOnClickListener(this);
        vb.layoutDownload.setOnClickListener(this);

    }


    /**
     * 更新播放进度Ui、缓冲进度
     */
    private void updatePlaybackProgress() {
        // 获取当前播放位置
        long contentPos = mediaControllerManager.getContentPos();
        long bufferPos = mediaControllerManager.getBufferPos();


        String s = CommonUtils.convertMillisToTime(contentPos);
        vb.tvCurrent.setText(s);
        vb.playProgress.setProgress((int) contentPos);
        vb.progressBarBuffer.setProgress((int) bufferPos);
    }


    /**
     * 播放完成 更新播放进度Ui
     */
    private void updatePlayComplete() {
        vb.tvCurrent.setText(vb.tvDuration.getText().toString());
    }


    /**
     * 加载当前播放歌曲信息
     */
    @OptIn(markerClass = UnstableApi.class)
    private void loadInfo(MediaItem mediaItem) {
        MediaMetadata mediaMetadata = mediaItem.mediaMetadata;
        CommonUtils.LogMsg("--------------加载当前播放歌曲信息 title=" + mediaMetadata.title);
        if (mediaMetadata.artworkUri != null) {
            loadCovert(mediaMetadata.artworkUri.toString());
        }
        vb.tvSongName.setText(mediaMetadata.title);
        vb.tvSingerName.setText(mediaMetadata.artist);
        vb.tvDuration.setText(mediaMetadata.description);

        if (mediaMetadata.durationMs != null) {
            long durationMs = mediaMetadata.durationMs;
            vb.playProgress.setMax((int) durationMs);
            vb.progressBarBuffer.setMax((int) durationMs);
        }
        if (vb.layoutPlayList.linearLayout.getVisibility() == View.VISIBLE) {
            updatePlayListUi();
        }

        //刷新当前歌曲的喜爱状态
        boolean isLike = ObjectBoxManager.queryIsLike(mediaItem.mediaId);
        vb.imLike.setSelected(isLike);

        //刷新当前歌曲的下载状态
        String mediaId = mediaItem.mediaId;
        MyDownloadService.queryIsDownload(mediaId, new onCheckDownload() {
            @Override
            public void onHasDownload(CustomerDownload customerDownload) {
                vb.imDownload.setSelected(customerDownload.isDownload());
            }
        });

    }

    private void loadCovert(String url) {

        Glide.with(MusicApplication.myApplication)
                .asDrawable()
                .load(url)
                .placeholder(R.mipmap.im_placeholder)
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, @Nullable Object model, @NonNull Target<Drawable> target, boolean isFirstResource) {
                        CommonUtils.LogMsg(e.getMessage());
//                        netError = 2;
//                        vb.tvErrorMsg.setText(getString(R.string.image_loading_failed));
//                        vb.linearRetry.setVisibility(View.VISIBLE);
                        return false;
                    }

                    @OptIn(markerClass = UnstableApi.class)
                    @Override
                    public boolean onResourceReady(@NonNull Drawable resource, @NonNull Object model, Target<Drawable> target, @NonNull DataSource dataSource, boolean isFirstResource) {
                        vb.imCovert.setImageDrawable(resource);
                        CommonUtils.getMainColor(resource, new onImageColorListener() {
                            @Override
                            public void onImageColor(int color) {
                                if (color == -1) {
                                    return;
                                }
                                lighterColor = CommonUtils.adjustBrightness(color, 0.8f);  // 比原始颜色亮 20%
                                darkerColor = CommonUtils.adjustBrightness(color, 0.6f);  // 比原始颜色暗 20%
                                gradientDrawable = new GradientDrawable(
                                        GradientDrawable.Orientation.TOP_BOTTOM,
                                        new int[]{lighterColor, darkerColor}  // 浅到深渐变
                                );
                                vb.rootLayout.setBackground(gradientDrawable);

                                if (vb.layoutPlayList.linearLayout.getVisibility() == View.VISIBLE) {
                                    updatePlayListColor();
                                }
                            }
                        });
                        return false;
                    }
                })
                .preload();


    }


    private void initProgressHandler() {
        mHandler = new Handler();
        mRunnable = new Runnable() {
            @Override
            public void run() {
                updatePlaybackProgress();
                mHandler.postDelayed(this, 1000);
            }
        };
    }

    @Override
    public boolean isFullScreen() {
        return true;
    }

    @Override
    public boolean statusBarLight() {
        return false;
    }

    @Override
    public boolean showPanel() {
        return false;
    }

    @OptIn(markerClass = UnstableApi.class)
    @Override
    public void onClick(View v) {
        if (v.equals(vb.btnPlay)) {
            vb.btnPlay.setSelected(!vb.btnPlay.isSelected());
            if (vb.btnPlay.isSelected()) {
                mediaControllerManager.play();
            } else {
                mediaControllerManager.pause();
            }
        } else if (v.equals(vb.btnNext)) {
            mediaControllerManager.playNext(new onPlayNextListener() {
                @Override
                public void onPlayNext(boolean hasNext) {
                    if (!hasNext) {
                        Toast.makeText(PlayActivity.this, getString(R.string.no_next_song_yet), Toast.LENGTH_SHORT).show();
                    }
                }
            });

        } else if (v.equals(vb.btnPrevious)) {
            mediaControllerManager.playPrevious();
        } else if (v.equals(vb.imBack)) {
            finish();
        } else if (v.equals(vb.btnMusicList)) {
            initShowPlayList(true);
        } else if (v.equals(vb.layoutPlayList.imPlay)) {
            vb.layoutPlayList.imPlay.setSelected(!vb.layoutPlayList.imPlay.isSelected());
            if (vb.layoutPlayList.imPlay.isSelected()) {
                mediaControllerManager.play();
            } else {
                mediaControllerManager.pause();
            }
            if (adapterPlayList != null) {
                adapterPlayList.updateCurMusicAnimation();
            }
        } else if (v.equals(vb.layoutError.tvRetry)) {
            //重试按钮
            updateErrorLayout(null, false);
            switch (netError) {
                case 0:
                    switch (mEnterType) {
                        case MyValue.TYPE_ENTER_SOURCE_SINGLE:
                            vmPlay.getPlayMusicList(playlistId, videoId, params, musicVideoType);
                            break;
                    }
                    break;
                case 1:
                    vb.progressBarLoading.setVisibility(View.VISIBLE);
                    int curIndex = mediaControllerManager.getCurIndex();

                    String curVideoId = mediaControllerManager.getCurVideoId();

                    String videoId1 = mCustomerUrlInfo.getVideoId();
                    int playMusicIndex = mCustomerUrlInfo.getPlayMusicIndex();

                    CommonUtils.LogMsg("-------重试 curIndex=" + curIndex + "----curVideoId=" + curVideoId + "---videoId1=" + videoId1 + "---playMusicIndex=" + playMusicIndex);

                    vmPlay.getPlayUrl(mCustomerUrlInfo.getVideoId(), mCustomerUrlInfo.getPlayMusicIndex(), true);
                    break;
                case 2:
                    MediaItem curMediaItem = mediaControllerManager.getCurMediaItem();
                    MediaMetadata mediaMetadata = curMediaItem.mediaMetadata;
                    if (mediaMetadata.artworkUri != null) {
                        loadCovert(mediaMetadata.artworkUri.toString());
                    }
                    break;
            }

        } else if (v.equals(vb.btnLoop)) {
            currentMode = (currentMode + 1) % imageStates.length;
            vb.btnLoop.setImageResource(imageStates[currentMode]);
            CommonUtils.LogMsg("----currentMode=" + currentMode);
            mediaControllerManager.setMode(currentMode);
        } else if (v.equals(vb.layoutLike)) {
            boolean selected = vb.imLike.isSelected();
            vb.imLike.setSelected(!selected);
            boolean newSelect = vb.imLike.isSelected();
            MediaItem curMediaItem = mediaControllerManager.getCurMediaItem();
            MediaMetadata mediaMetadata = curMediaItem.mediaMetadata;
            if (mediaMetadata.title != null && mediaMetadata.artist != null && mediaMetadata.durationMs != null && mediaMetadata.description != null) {
                BoxLikeSong boxLikeSong = new BoxLikeSong(mediaMetadata.title.toString(),
                        mediaMetadata.artist.toString(),
                        curMediaItem.mediaId,
                        String.valueOf(mediaMetadata.artworkUri),
                        mediaMetadata.durationMs, mediaMetadata.description.toString());
                if (newSelect) {
                    ObjectBoxManager.insertOrUpdateLike(boxLikeSong);
                } else {
                    ObjectBoxManager.deleteLike(boxLikeSong);
                }
            }


        } else if (v.equals(vb.layoutDownload)) {
            if (vb.imDownload.isSelected()) {
                //已经下载
                Toast.makeText(this,getText(R.string.text_has_downloaded),Toast.LENGTH_SHORT).show();
                return;
            }
            vb.downloadPb.setVisibility(View.VISIBLE);
            vb.imDownload.setVisibility(View.INVISIBLE);
            BoxDownloadSong curMediaItemInfo = getCurMediaItemInfo();
            if (curMediaItemInfo != null) {
                Gson gson = new Gson();
                String info = gson.toJson(curMediaItemInfo);
                byte[] data = info.getBytes(StandardCharsets.UTF_8);

                String videoId1 = curMediaItemInfo.getVideoId();
                CommonUtils.LogMsg("----------------开始下载   id=" + videoId1);
                DownloadRequest downloadRequest = new DownloadRequest.Builder(videoId1, Uri.parse(curMediaItemInfo.getVideoUrl()))
                        .setMimeType("video/mp4")
                        .setData(data)
                        .build();

                // 启动 DownloadService 进行下载
                DownloadService.sendAddDownload(
                        this,
                        MyDownloadService.class, // 上面定义的下载服务类
                        downloadRequest,
                        true // 是否在前台运行
                );
            }


        }

    }


    @OptIn(markerClass = UnstableApi.class)
    private BoxDownloadSong getCurMediaItemInfo() {
        MediaItem curMediaItem = mediaControllerManager.getCurMediaItem();
        if (curMediaItem == null) {
            return null;
        }
        MediaMetadata mediaMetadata = curMediaItem.mediaMetadata;
        if (mediaMetadata.title == null || mediaMetadata.artist == null || mediaMetadata.description == null
                || mediaMetadata.durationMs == null || curMediaItem.localConfiguration == null) {
            return null;
        }

        BoxDownloadSong boxDownloadSong = new BoxDownloadSong();
        boxDownloadSong.setVideoId(curMediaItem.mediaId);
        boxDownloadSong.setCovert(String.valueOf(mediaMetadata.artworkUri));
        boxDownloadSong.setSongName((String) mediaMetadata.title);
        boxDownloadSong.setSingerName((String) mediaMetadata.artist);
        boxDownloadSong.setDuration((String) mediaMetadata.description);
        boxDownloadSong.setDurationMs(mediaMetadata.durationMs);
        boxDownloadSong.setVideoUrl(String.valueOf(curMediaItem.localConfiguration.uri));

        return boxDownloadSong;
    }

    /**
     * 控制播放列表的显示
     *
     * @param show
     */
    private void initShowPlayList(boolean show) {
        if (show) {
            Animation animation = AnimationUtils.loadAnimation(this, R.anim.slide_up);
            vb.layoutPlayList.linearLayout.startAnimation(animation);
            vb.layoutPlayList.linearLayout.setVisibility(View.VISIBLE);
            vb.contentLayout.setVisibility(View.GONE);

            if (!initPlayList) {
                List<ResponsePlayListInfo> playList;
                if (mEnterType == MyValue.TYPE_ENTER_DOWNLOAD){
                    playList = new ArrayList<>();
                    for(BoxDownloadSong data:downloadSongList){
                        ResponsePlayListInfo playListInfo = new ResponsePlayListInfo();
                        playListInfo.setSongTitle(data.getSongName());
                        playListInfo.setSingerName(data.getSingerName());
                        playListInfo.setCovert(data.getCovert());
                        playListInfo.setSmallCovert(data.getCovert());
                        playListInfo.setVideoId(data.getVideoId());
                        playListInfo.setDuration(data.getDuration());
                        playListInfo.setDurationMs(data.getDurationMs());
                        playList.add(playListInfo);
                    }

                }else {
                     playList = mediaControllerManager.getPlayList();
                }
                adapterPlayList = new AdapterPlayList();
                vb.layoutPlayList.recyclerList.setLayoutManager(new LinearLayoutManager(MusicApplication.myApplication));
                adapterPlayList.setData(playList);
                // TODO: 2024/10/16 播放列表显示
                vb.layoutPlayList.recyclerList.setAdapter(adapterPlayList);
                vb.layoutPlayList.imPlay.setOnClickListener(this);
                initPlayList = true;

            }
            updatePlayListUi();

        } else {

            vb.rootLayout.setBackground(gradientDrawable);
            vb.contentLayout.setVisibility(View.VISIBLE);

            Animation animation = AnimationUtils.loadAnimation(this, R.anim.slide_down);
            vb.layoutPlayList.linearLayout.startAnimation(animation);
            vb.layoutPlayList.linearLayout.setVisibility(View.GONE);
        }


    }

    /**
     * 更新播放列表的显示
     */
    private void updatePlayListUi() {
        CommonUtils.LogMsg("----------更新播放列表的显示");

        MediaItem currentMediaItem = mediaControllerManager.getCurMediaItem();
        if (currentMediaItem != null) {
            if (adapterPlayList != null) {
                adapterPlayList.setCurVideId(currentMediaItem.mediaId);
            }
            Uri artworkUri = currentMediaItem.mediaMetadata.artworkUri;
            vb.layoutPlayList.topSongName.setText(currentMediaItem.mediaMetadata.title);
            vb.layoutPlayList.topSingerName.setText(currentMediaItem.mediaMetadata.artist);
            updatePlayListColor();
            Glide.with(MusicApplication.myApplication)
                    .asDrawable()
//                    .apply(RequestOptions.bitmapTransform(new RoundedCorners(CommonUtils.dpToPx(10))))
                    .load(artworkUri)
                    .placeholder(R.mipmap.im_placeholder)
                    .listener(new RequestListener<Drawable>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, @Nullable Object model, @NonNull Target<Drawable> target, boolean isFirstResource) {
                            CommonUtils.LogMsg(e.getMessage());
                            return false;
                        }

                        @OptIn(markerClass = UnstableApi.class)
                        @Override
                        public boolean onResourceReady(@NonNull Drawable resource, @NonNull Object model, Target<Drawable> target, @NonNull DataSource dataSource, boolean isFirstResource) {

                            return false;
                        }
                    })
                    .into(vb.layoutPlayList.topIm);
        }
        vb.layoutPlayList.imPlay.setSelected(mediaControllerManager.getIsPlaying());
    }

    private void updatePlayListColor() {
        vb.layoutPlayList.topLayout.setBackgroundColor(darkerColor);
        GradientDrawable gradientDrawable = new GradientDrawable(
                GradientDrawable.Orientation.TOP_BOTTOM,
                new int[]{darkerColor, darkerColor}
        );
        vb.rootLayout.setBackground(gradientDrawable);
        Drawable newDrawable = CommonUtils.getNewDrawable(lighterColor, 24f, 24f, 0, 0);
        vb.layoutPlayList.listLayout.setBackground(newDrawable);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null && mRunnable != null)
            mHandler.removeCallbacks(mRunnable);
    }

    @Override
    public void onBackPressed() {
        if (vb.layoutPlayList.linearLayout.getVisibility() == View.VISIBLE) {
            initShowPlayList(false);
        } else {
            super.onBackPressed();  // 调用系统默认的返回行为
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (fromUser) {
            mediaControllerManager.getMediaController().seekTo(progress);
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }

    @OptIn(markerClass = UnstableApi.class)
    private void addDownloadListener() {
        MyDownloadService.addDownloadListener(vmApplication);
        vmApplication.downloadData.observe(this, new Observer<List<Download>>() {
            @Override
            public void onChanged(List<Download> downloads) {
                if (downloads == null || downloads.size() == 0) {
                    return;
                }
                String id = downloads.get(downloads.size() - 1).request.id;

                MediaItem curMediaItem = mediaControllerManager.getCurMediaItem();
                if (curMediaItem != null) {
                    String mediaId = mediaControllerManager.getCurMediaItem().mediaId;
                    if (mediaId.equals(id)) {
                        vb.downloadPb.setVisibility(View.GONE);
                        vb.imDownload.setVisibility(View.VISIBLE);
                        vb.imDownload.setSelected(true);
                    }
                }

                CommonUtils.LogMsg("-------onChanged id=" + id);
                if (mEnterType == MyValue.TYPE_ENTER_DOWNLOAD) {
                    //下载进入播放，这里进行重置播放列表并播放
                    mediaControllerManager.resetPlayList();
                    for (Download data : downloads) {
                        BoxDownloadSong boxDownloadSong = CommonUtils.downloadToBean(data);
                        downloadSongList.add(boxDownloadSong);
                        MediaItem mediaItem = CommonUtils.downloadToMediaItem(data);
                        mediaControllerManager.addMusicPlayList(mediaItem);
                    }
                    mediaControllerManager.playPositionMusic(mDefaultPlayStartIndex);
                    mediaControllerManager.play();
                }
            }
        });
    }
}