package com.gensee.multi_instance.demo.vod;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.gensee.common.GenseeConfig;
import com.gensee.entity.BroadCastMsg;
import com.gensee.entity.ChatMsg;
import com.gensee.entity.DocInfo;
import com.gensee.entity.InitParam;
import com.gensee.media.GSOLPlayer;
import com.gensee.media.IVideoIndication;
import com.gensee.media.PlaySpeed;
import com.gensee.media.VODPlayer;
import com.gensee.multi_instance.PageActivity;
import com.gensee.multi_instance.R;
import com.gensee.utils.GenseeLog;
import com.gensee.utils.StringUtil;
import com.gensee.view.GSAudoDecodeViewEx;
import com.gensee.view.GSGPUVideoView;
import com.gensee.view.GSVideoView;

import java.util.List;

@SuppressLint("ValidFragment")
public class VodPageFragment extends Fragment implements GSOLPlayer.OnOLPlayListener, SeekBar.OnSeekBarChangeListener {
    private static final String TAG = "PageFragment";
    private String mOriginalVodId = "";
    private String mVodId = "";
    private InitParam mInitParam;
    private VODPlayer mGSOLPlayer;
    private IVideoIndication mGSVideoView;
    private ImageView ivPlaceholder;
    private int speedItem = 0;
    private boolean isVideoClose = false;
    private Handler mHandler = new Handler();
    private TextView mNowTimeTextview;
    private TextView mAllTimeTextView;
    private SeekBar mSeekBarPlayViedo;
    private View playButton;
    private boolean isTouch = false;
    private boolean isStop = false;

    private long time = 0;
    private static final int DURITME = Toast.LENGTH_SHORT;
    private static final String DURATION = "DURATION";

    public VodPageFragment() {
        // 必须存在无参构造函数
    }

    // 静态工厂方法，用于创建Fragment实例并传递参数
    public static VodPageFragment newInstance(InitParam initParam) {
        VodPageFragment fragment = new VodPageFragment();
        Bundle args = new Bundle();
        args.putSerializable("init_param", initParam); // 假设InitParam实现了Serializable接口
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mInitParam = (InitParam) getArguments().getSerializable("init_param");
            mOriginalVodId = mInitParam.getVodNumber();
        }
    }


    interface MSG {
        int MSG_ON_INIT = 1;
        int MSG_ON_STOP = 2;
        int MSG_ON_POSITION = 3;
        int MSG_ON_VIDEOSIZE = 4;
        int MSG_ON_PAGE = 5;
        int MSG_ON_SEEK = 6;
        int MSG_ON_AUDIOLEVEL = 7;
        int MSG_ON_ERROR = 8;
        int MSG_ON_PAUSE = 9;
        int MSG_ON_RESUME = 10;
    }
    private int videoDuration = 0;

    protected Handler myHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (isDetached()) {
                return;
            }
            if (getContext() == null) {
                return;
            }
            if (getActivity() == null) {
                return;
            }
            switch (msg.what) {
                case MSG.MSG_ON_INIT:

                    int max = msg.getData().getInt(DURATION);
                    videoDuration = max;
                    mSeekBarPlayViedo.setMax(max);
                    max = max / 1000;
                    GenseeLog.i(TAG, "MSG_ON_INIT duration = " + max);
                    mAllTimeTextView.setText(getTime(max));
                    // 当初始化完成后，如果当前fragment可见，则直接开始播放
                    if (isActivityVisible()) {
                        isStop = false;
                        mGSOLPlayer.resume();
                    }
                    break;
                case MSG.MSG_ON_STOP:
                    String vodIdOrLocalPath = getVodIdOrLocalPath();
                    if (vodIdOrLocalPath == null) {
                        Toast.makeText(requireContext(), "路径不对", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    isStop= true;

                    Toast.makeText(requireContext(), "播放完成，重新播放", Toast.LENGTH_SHORT).show();
                    mGSOLPlayer.play(vodIdOrLocalPath, VodPageFragment.this, "",false);
                    time = System.currentTimeMillis();
                    playButton.setVisibility(View.GONE);
                    break;
                case MSG.MSG_ON_VIDEOSIZE:

                    break;
                case MSG.MSG_ON_PAGE:

                    break;
                case MSG.MSG_ON_PAUSE:
                    playButton.setVisibility(View.VISIBLE);
                    break;
                case MSG.MSG_ON_RESUME:

                    break;
                case MSG.MSG_ON_POSITION:
                    if (isTouch) {
                        return;
                    }
                case MSG.MSG_ON_SEEK:
                    isTouch = false;
                    int anyPosition = (Integer) msg.obj;
                    mSeekBarPlayViedo.setProgress(anyPosition);
                    anyPosition = anyPosition / 1000;
                    mNowTimeTextview.setText(getTime(anyPosition));
                    if (msg.what == MSG.MSG_ON_SEEK) {
                        playButton.setVisibility(View.GONE);
                    }

                    break;
                case MSG.MSG_ON_AUDIOLEVEL:

                    break;
                case MSG.MSG_ON_ERROR:
                    isTouch = false;
                    int errorCode = (Integer) msg.obj;
                    switch (errorCode) {
                        case ERR_PAUSE:
                            Toast.makeText(requireContext(), "暂停失败", DURITME)
                                    .show();
                            break;
                        case ERR_PLAY:
                            Toast.makeText(requireContext(), "播放失败", DURITME)
                                    .show();
                            break;
                        case ERR_RESUME:
                            Toast.makeText(requireContext(), "恢复失败", DURITME)
                                    .show();
                            break;
                        case ERR_SEEK:
                            Toast.makeText(requireContext(), "进度变化失败", DURITME)
                                    .show();
                            break;
                        case ERR_STOP:
                            Toast.makeText(requireContext(), "停止失败", DURITME)
                                    .show();
                            break;
                        default:
                            break;
                    }
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }

    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.layout_fragment_page, container, false);
        Log.i(TAG, "onCreateView: "+mOriginalVodId);
        createVodInfoIniters();
        ((PageActivity)getActivity()).addPageNum();
        playInfoIniter.getVodObject(mInitParam);


        return inflate;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        if (GenseeConfig.isPVHardDecode) {

            mGSVideoView = view.findViewById(R.id.gsvideoview2);
            ((View)mGSVideoView).setVisibility(View.VISIBLE);
            view.findViewById(R.id.gsvideoview).setVisibility(View.GONE);
        } else {
            mGSVideoView = view.findViewById(R.id.gsvideoview);
            ((View)mGSVideoView).setVisibility(View.VISIBLE);
            view.findViewById(R.id.gsvideoview2).setVisibility(View.GONE);
        }
        ivPlaceholder = view.findViewById(R.id.iv_placeholder);
        mNowTimeTextview = (TextView) view.findViewById(R.id.palynowtime);
        mAllTimeTextView = (TextView) view.findViewById(R.id.palyalltime);
        mSeekBarPlayViedo = (SeekBar) view.findViewById(R.id.seekbarpalyviedo);
        playButton = view.findViewById(R.id.playButton);

        mSeekBarPlayViedo.setOnSeekBarChangeListener(this);

        playButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mGSOLPlayer == null) {
                    return;
                }
                playButton.setVisibility(View.GONE);
                mGSOLPlayer.resume();
            }
        });

        view.findViewById(R.id.v_pause_area).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mGSOLPlayer == null) {
                    return;
                }

                mGSOLPlayer.pause();
            }
        });

        view.findViewById(R.id.btn_closeVideo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mGSOLPlayer == null) {
                    return;
                }
                if (isVideoClose) {
                    GenseeLog.d("GSOLPlayer", "videoSet isClose: false");
                    mGSOLPlayer.videoSet(false,null);
                    isVideoClose = false;
                    ((TextView)v).setText("关闭视频");
                } else {
                    GenseeLog.d("GSOLPlayer", "videoSet isClose: true");
                    mGSOLPlayer.videoSet(true,null);
                    isVideoClose = true;
                    ((TextView)v).setText("开启视频");

                }
            }
        });

        view.findViewById(R.id.btn_change_speed).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mGSOLPlayer == null) {
                    return;
                }
                switchSpeed();
            }
        });
    }


    private void initPlayer(String vodId) {
        Log.i(TAG, "initPlayer: " + vodId);
        mVodId = vodId;
        String vodIdOrLocalPath = getVodIdOrLocalPath();
        if (vodIdOrLocalPath == null) {
            Toast.makeText(getContext(), "路径不对", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mGSOLPlayer == null) {
            mGSOLPlayer = new VODPlayer();
            mGSOLPlayer.setGSVideoView(mGSVideoView);
//            mGSOLPlayer.setGSDocViewGx(mDocView);
            // 开始提前准备资源
            mGSOLPlayer.prepare(mVodId, VodPageFragment.this, "", false);
            time = System.currentTimeMillis();

        }
    }

    private boolean isVisible = false;

    public boolean isActivityVisible() {
        return isVisible;
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.i(TAG, "onStart: ");
    }

    @Override
    public void onResume() {
        super.onResume();
        isVisible = true;
        Log.i(TAG, "onResume: ");
        if (mGSOLPlayer != null) {
            mGSOLPlayer.resume();
            playButton.setVisibility(View.GONE);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        isVisible = false;
        Log.i(TAG, "onPause: ");
        if (mGSOLPlayer != null) {
            if (!isStop) {
                mGSOLPlayer.pause();
            }
        }
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
//        if (mGSOLPlayer == null) {
//            return;
//        }
//        if (isVisibleToUser) {
//            Log.i(TAG, "setUserVisibleHint: 可见");
//            mGSOLPlayer.resume();
//            playButton.setVisibility(View.GONE);
//
//        } else {
//            Log.i(TAG, "setUserVisibleHint: 不可见");
//            if (!isStop) {
//                mGSOLPlayer.pause();
//            }
//        }
    }

    @Override
    public void onStop() {
        super.onStop();
//        mGSOLPlayer.stop();
        Log.i(TAG, "onStop: ");
    }

    private String getVodIdOrLocalPath() {
        String vodId = mVodId;
        String localpath = "";
//        GenseeLog.d(TAG, "path = " + localpath + " vodId = " + vodId);
        String vodIdOrLocalPath = null;
        if (!StringUtil.isEmpty(localpath)) {
            vodIdOrLocalPath = localpath;
        } else if (!StringUtil.isEmpty(vodId)) {
            vodIdOrLocalPath = vodId;
        }
        return vodIdOrLocalPath;
    }

    @Override
    public void onInit(int result, boolean haveVideo, int duration,
                       List<DocInfo> docInfos) {
        Message message = new Message();
        message.what = MSG.MSG_ON_INIT;
        message.obj = docInfos;
        Bundle bundle = new Bundle();
        bundle.putInt(DURATION, duration);
        message.setData(bundle);
        myHandler.sendMessage(message);
    }


    @Override
    public void onPlayStop() {
        GenseeLog.d(TAG, "onPlayStop ");
        myHandler.sendMessage(myHandler.obtainMessage(MSG.MSG_ON_STOP, 0));
    }

    @Override
    public void onPosition(int position) {
        GenseeLog.d(TAG, "onPosition pos = " + position);
        myHandler.sendMessage(myHandler.obtainMessage(MSG.MSG_ON_POSITION,
                position));
    }

    @Override
    public void onVideoSize(int position, int videoWidth, int videoHeight) {
        myHandler.sendMessage(myHandler.obtainMessage(MSG.MSG_ON_VIDEOSIZE, 0));
    }

    @Override
    public void onPageSize(int position, int w, int h) {
        GenseeLog.d(TAG, "onPage pos = " + position);
        myHandler.sendMessage(myHandler
                .obtainMessage(MSG.MSG_ON_PAGE, position));
    }

    @Override
    public void onSeek(int position) {
        Log.i(TAG, "onSeek: ");
        myHandler.sendMessage(myHandler
                .obtainMessage(MSG.MSG_ON_SEEK, position));
    }

    @Override
    public void onAudioLevel(int level) {
        myHandler.sendMessage(myHandler.obtainMessage(MSG.MSG_ON_AUDIOLEVEL,
                level));
    }

    @Override
    public void onError(int errCode) {
        myHandler.sendMessage(myHandler
                .obtainMessage(MSG.MSG_ON_ERROR, errCode));
    }

    @Override
    public void onPlayPause() {
        Log.i(TAG, "onPlayPause: ");
        myHandler.sendMessage(myHandler.obtainMessage(MSG.MSG_ON_PAUSE, 0));
    }

    @Override
    public void onPlayResume() {
        Log.i(TAG, "onPlayResume: ");
        myHandler.sendMessage(myHandler.obtainMessage(MSG.MSG_ON_RESUME, 0));
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress,
                                  boolean fromUser) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        isTouch = true;
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        if (null != mGSOLPlayer) {
            int pos = seekBar.getProgress();
            if (pos != 0) {
                pos = pos - 1;
            }
            GenseeLog.d(TAG, "onStopTrackingTouch pos = " + pos + "max: " + videoDuration);
            mGSOLPlayer.seekTo(pos);


        }

    }


    @Override
    public void onCaching(boolean b) {

    }

    @Override
    public void onVideoStart() {
        Log.i(TAG, "onVideoStart: ");
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                ivPlaceholder.setVisibility(View.GONE);
            }
        });

    }

    @Override
    public void onVideoEnd() {
        Log.i(TAG, "onVideoEnd: ");
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                ivPlaceholder.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    public void onFirstFrameNfy() {
        long t = System.currentTimeMillis() - time;
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                View view = getView();
                if (view == null) {
                    return;
                }
                ((TextView) view.findViewById(R.id.firstFrame)).setText("首帧耗时：" +t+"ms");
            }
        });

    }

    @Override
    public void onChat(List<ChatMsg> list) {

    }

    @Override
    public void onDocInfo(List<DocInfo> list) {

    }

    @Override
    public void onChatCensor(String s, String s1) {

    }

    @Override
    public void onBroadCastMsg(List<BroadCastMsg> list) {

    }

    @Override
    public void onLayoutSet(int i, int i1) {

    }

    @Override
    public void onRecordInfo(long l, long l1, long l2) {

    }

    private AbsVodInfoIniter playInfoIniter;

    public void createVodInfoIniters() {

        playInfoIniter = new AbsVodInfoIniter(getContext(), mHandler) {

            @Override
            public void getVodObject(InitParam initParam) {
                //针对播放，取消之前的初始响应，保证响应的是最新一次的播放信息
                if (vodSite != null) {
                    vodSite.setVodListener(null);
                }
                super.getVodObject(initParam);
            }

            @Override
            public void onVodObject(String vodId) {
                //getVodObject响应  可以播放了
//                mHandler.sendMessage(mHandler
//                        .obtainMessage(VodActivity.RESULT.ON_GET_VODOBJ_FOR_PLAY, vodId));
                initPlayer(vodId);
            }
        };


    }


    private String getTime(int time) {
        return String.format("%02d", time / 3600) + ":"
                + String.format("%02d", time % 3600 / 60) + ":"
                + String.format("%02d", time % 3600 % 60);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
//        Log.i(TAG, "onDestroyView: ");
        if (mGSOLPlayer != null) {
            mGSOLPlayer.release();
            mGSOLPlayer = null;
        }
    }

    @Override
    public void onDestroy() {
        ((PageActivity)getActivity()).reducePageNum();
        Log.i(TAG, "onDestroy: " + mOriginalVodId);
        super.onDestroy();

    }

    /**
     * 变速播放
     */
    private void switchSpeed() {
        new AlertDialog.Builder(requireContext())
                .setSingleChoiceItems(R.array.speeds, speedItem,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                speedItem = which;
                                PlaySpeed ps = PlaySpeed.SPEED_NORMAL;
                                switch (which) {
                                    case 0:
                                        ps = PlaySpeed.SPEED_NORMAL;
                                        break;
                                    case 1:
                                        ps = PlaySpeed.SPEED_125;
                                        break;
                                    case 2:
                                        ps = PlaySpeed.SPEED_150;
                                        break;
                                    case 3:
                                        ps = PlaySpeed.SPEED_175;
                                        break;
                                    case 4:
                                        ps = PlaySpeed.SPEED_200;
                                        break;
                                    case 5:
                                        ps = PlaySpeed.SPEED_250;
                                        break;
                                    case 6:
                                        ps = PlaySpeed.SPEED_300;
                                        break;
                                    case 7:
                                        ps = PlaySpeed.SPEED_350;
                                        break;
                                    case 8:
                                        ps = PlaySpeed.SPEED_400;
                                        break;

                                    default:
                                        break;
                                }
                                mGSOLPlayer.setSpeed(ps, null);
                                dialog.dismiss();
                            }
                        }).create().show();
    }
}
