package com.daya.live_teaching.ui.fragmnet;


import android.content.Intent;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.cooleshow.base.ui.fragment.BaseFragment;
import com.cooleshow.base.utils.LogUtils;
import com.cooleshow.base.utils.ToastUtil;
import com.daya.live_teaching.R;
import com.daya.live_teaching.common.ResultCallback;
import com.daya.live_teaching.databinding.FragmentAccompanimentListBinding;
import com.daya.live_teaching.model.ClassMember;
import com.daya.live_teaching.model.Role;
import com.daya.live_teaching.model.UserInfo;
import com.daya.live_teaching.model.VideoClassMemberData;
import com.daya.live_teaching.ui.adapter.AccompanimentDownloadListAdapter;
import com.daya.live_teaching.ui.adapter.AccompanimentListAdapter;
import com.daya.live_teaching.ui.base.BaseRecyclerAdapter;
import com.daya.live_teaching.viewmodel.ClassViewModel;
import com.daya.live_teaching.widget.dialog.AccompanimentDialog;
import com.daya.live_teaching.widget.dialog.LiveCommonDialog;
import com.h6ah4i.android.widget.verticalseekbar.VerticalSeekBar;
import com.h6ah4i.android.widget.verticalseekbar.VerticalSeekBarWrapper;

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

import static android.app.Activity.RESULT_OK;

/**
 * 伴奏播放控制界面
 */
public class AccompanimentListFragment extends BaseFragment<FragmentAccompanimentListBinding> {

    private final int QU_LIBRAY_REQUEST_CODE = 1000;

    private AccompanimentDownloadListAdapter accompanimentDownloadAdapter;
    private List<ClassMember> accompanimentDosnloadMembers;
    private String roomId;
    private ClassViewModel classViewModel;
    private AccompanimentListAdapter accompanimentListAdapter;
    private UserInfo userInfo;
    private String musicScoreAccompanimentDownloadId;
    private boolean isPlayAccompaniment;
    private String fileName;
    private String playFileName;
    private List<ClassMember.ScheduleStudentMusicScoresBean> musicScoresBeans;

    private boolean isPlayMusic = false;
    private ImageView ivPlay;
    private int selectPosition = 0;
    private List<ClassMember> noJoinStuClassMembers = new ArrayList<>();
    boolean isShowDownloadPopu = false;
    private ImageView ivAdd;
    private String currentisACCOMType = "5";
    private String volumeSeekerBarProcess;


    public static AccompanimentListFragment newInstance() {
        return new AccompanimentListFragment();
    }

    @Override
    protected FragmentAccompanimentListBinding getLayoutView() {
        return FragmentAccompanimentListBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initView(View rootView) {
        TextView tvTitle = mViewBinding.tvTitle;
        ImageView ivClose = mViewBinding.ivClose;
        ivAdd = mViewBinding.ivAdd;
        RecyclerView rvList = mViewBinding.recyclerView;
        ImageView ivBack = mViewBinding.ivBack;
        ivPlay = mViewBinding.ivPlay;
        ImageView ivNext = mViewBinding.ivNext;
        LinearLayout llGroup = mViewBinding.llGroup;
        llGroup.setOnClickListener(v -> {
        });
        classViewModel = ViewModelProviders.of(getActivity()).get(ClassViewModel.class);
        rvList.setLayoutManager(new LinearLayoutManager(getContext()));
        accompanimentListAdapter = new AccompanimentListAdapter(getContext());
        rvList.setAdapter(accompanimentListAdapter);
        accompanimentListAdapter.setOnSubViewClickListener(new BaseRecyclerAdapter.OnSubViewClickListener() {
            @Override
            public void onSubViewClick(View v, int position) {
                ClassMember.ScheduleStudentMusicScoresBean musicScoresBean = musicScoresBeans.get(position);

                if (v.getId() == R.id.iv_type) {
                    selectPosition = position;
                    if (TextUtils.isEmpty(musicScoresBean.getUrl()) || TextUtils.isEmpty(musicScoresBean.getMp3Url())) {
                        ToastUtil.getInstance().show(getContext(), "该曲目不支持原声/伴奏切换");
                        return;
                    }
                    musicScoresBean.setIsAccompaniment(musicScoresBean.getIsAccompaniment() == 1 ? 0 : 1);
                    currentisACCOMType = musicScoresBean.getIsAccompaniment() == 1 ? "6" : "5";
                    userInfo.setScheduleStudentMusicScores(musicScoresBeans);
                    classViewModel.setMusicScoreAccompanimentId(musicScoresBean.getMusicScoreAccompanimentId());
                    isPlayAccompaniment = musicScoresBean.getIsAccompaniment() == 1;
                    playFileName = musicScoresBean.getMusicScoreName();
                    classViewModel.setAccompaniment(isPlayAccompaniment);
                    playFileName = musicScoresBean.getMusicScoreName();
                    accompanimentListAdapter.setData(musicScoresBeans, classViewModel.getMusicScoreAccompanimentId());
                    setAccompaniment(isPlayMusic);
                }
                if (v.getId() == R.id.tv_status) {
                    fileName = musicScoresBean.getMusicScoreName();
                    showAccompanimentDialog(accompanimentDosnloadMembers, musicScoresBean.getMusicScoreAccompanimentId(), false);
                }
            }
        });

        accompanimentListAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                selectPosition = position;
                ClassMember.ScheduleStudentMusicScoresBean musicScoresBean = musicScoresBeans.get(position);
                isPlayAccompaniment = musicScoresBean.getIsAccompaniment() == 1;
                classViewModel.setMusicScoreAccompanimentId(musicScoresBean.getMusicScoreAccompanimentId());
                classViewModel.setAccompaniment(isPlayAccompaniment);
                playFileName = musicScoresBean.getMusicScoreName();
                accompanimentListAdapter.setData(musicScoresBeans, classViewModel.getMusicScoreAccompanimentId());
                setAccompaniment(isPlayMusic);
            }
        });

        ivClose.setOnClickListener(v -> {
            if (null != listener) {
                isShowDownloadPopu = false;
                setMusicName();
                listener.onClose();
            }
        });

        ivAdd.setOnClickListener(v -> {

            if (null == accompanimentDosnloadMembers || accompanimentDosnloadMembers.size() == 0) {
                ToastUtil.getInstance().show(getActivity(), "房间无学生，伴奏功能无法使用");
                return;
            }
            ivAdd.setEnabled(false);
//            Postcard postcard = ARouter.getInstance()
//                    .build(ARouterConstace.ACTIVITY_ACCOMPANIMENT_LIST)
//                    .withBoolean("isSelect", true);
//            LogisticsCenter.completion(postcard);
//            Intent selectAccompanimentIntent = new Intent(getActivity(), postcard.getDestination());
//            selectAccompanimentIntent.putExtras(postcard.getExtras());
//            startActivityForResult(selectAccompanimentIntent, QU_LIBRAY_REQUEST_CODE);
        });

        ivPlay.setOnClickListener(v -> {
            showAccompanimentPlayDialog();
        });

        ivNext.setOnClickListener(v -> {
            if (musicScoresBeans != null && musicScoresBeans.size() > 0 && selectPosition < musicScoresBeans.size() - 1) {
                selectPosition += 1;
                ClassMember.ScheduleStudentMusicScoresBean musicScoresBean = musicScoresBeans.get(selectPosition);

                isPlayAccompaniment = musicScoresBean.getIsAccompaniment() == 1;
                classViewModel.setMusicScoreAccompanimentId(musicScoresBean.getMusicScoreAccompanimentId());
                classViewModel.setAccompaniment(isPlayAccompaniment);
                accompanimentListAdapter.setData(musicScoresBeans, classViewModel.getMusicScoreAccompanimentId());
                playFileName = musicScoresBean.getMusicScoreName();
                setAccompaniment(isPlayMusic);
            }
        });
        ivBack.setOnClickListener(v -> {
            if (musicScoresBeans != null && musicScoresBeans.size() > 0 && selectPosition > 0) {
                selectPosition -= 1;
                ClassMember.ScheduleStudentMusicScoresBean musicScoresBean = musicScoresBeans.get(selectPosition);
                isPlayAccompaniment = musicScoresBean.getIsAccompaniment() == 1;
                classViewModel.setMusicScoreAccompanimentId(musicScoresBean.getMusicScoreAccompanimentId());
                classViewModel.setAccompaniment(isPlayAccompaniment);
                accompanimentListAdapter.setData(musicScoresBeans, classViewModel.getMusicScoreAccompanimentId());
                playFileName = musicScoresBean.getMusicScoreName();
                setAccompaniment(isPlayMusic);
            }
        });

        initSeekBar();
    }


    @Override
    public void onResume() {
        super.onResume();
        ivAdd.setEnabled(true);
    }

    private void initSeekBar() {

        String userId = classViewModel.getUserInfo().getValue().getUserId();
        //音量按钮
        ImageView ivVolume = mViewBinding.ivVolume;
        TextView tvSeekbarProcess = mViewBinding.tvSeekbarProcess;
        //音量bar
        VerticalSeekBarWrapper seekerBarWrapper = mViewBinding.seekbarWrapper;
        VerticalSeekBar volumeSeekerBar = mViewBinding.seekerBar;
        ivVolume.setOnClickListener(view -> {
            seekerBarWrapper.setVisibility(seekerBarWrapper.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
            tvSeekbarProcess.setVisibility(tvSeekbarProcess.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
        });
        volumeSeekerBar.setProgress(100);

        //音量调节
        volumeSeekerBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                LogUtils.i("volumeSeekerBar", "onProgressChanged" + progress);
                tvSeekbarProcess.setText(progress + "");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                volumeSeekerBarProcess = seekBar.getProgress() + "";
            }
        });
    }

    private void setMusicName() {

        String musicName = "";
        if (!TextUtils.isEmpty(playFileName)) {
            musicName = (playFileName.length() < 8 ? playFileName : playFileName.substring(0, 8) + "...") + "（" + (isPlayAccompaniment ? "伴奏" : "原音") + "）";
        }
        if (listener != null) {
            listener.showMusicNameView(musicName);
        }
    }

    @Override
    protected void initData() {
        classViewModel.getRoomId().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                roomId = s;
            }
        });

        classViewModel.getUserInfo().observe(this, userInfo -> {
            this.userInfo = userInfo;
            musicScoresBeans = userInfo.getScheduleStudentMusicScores();
            if (musicScoresBeans != null && musicScoresBeans.size() > 0) {
                if (TextUtils.isEmpty(classViewModel.getMusicScoreAccompanimentId())) {
                    musicScoreAccompanimentDownloadId = musicScoresBeans.get(0).getMusicScoreAccompanimentId();
                    isPlayAccompaniment = TextUtils.isEmpty(musicScoresBeans.get(0).getUrl()) ? true : false;
                    playFileName = musicScoresBeans.get(0).getMusicScoreName();
                    classViewModel.setMusicScoreAccompanimentId(musicScoreAccompanimentDownloadId);
                    classViewModel.setAccompaniment(isPlayAccompaniment);
                }
                accompanimentListAdapter.setData(musicScoresBeans, classViewModel.getMusicScoreAccompanimentId());
            }

        });

        classViewModel.getExamSongDownloadClassMember().observe(this, new Observer<VideoClassMemberData>() {

            @Override
            public void onChanged(VideoClassMemberData data) {
                if (data != null && data.getMember() != null) {
                    if (accompanimentDosnloadMembers == null) {
                        accompanimentDosnloadMembers = new ArrayList<>();
                    }
                    accompanimentDosnloadMembers.clear();
                    accompanimentDosnloadMembers.addAll(data.getMember());
                    if (accompanimentDownloadAdapter != null && !TextUtils.isEmpty(musicScoreAccompanimentDownloadId)) {
                        accompanimentDownloadAdapter.setData(data.getMember(), musicScoreAccompanimentDownloadId);
                    }
                    if (isShowDownloadPopu) {
                        isShowDownloadPopu = false;
                        showAccompanimentDialog(accompanimentDosnloadMembers, musicScoreAccompanimentDownloadId, false);
                    }

                }
            }
        });

        classViewModel.getMemberList().observe(this, new Observer<List<ClassMember>>() {
            @Override
            public void onChanged(List<ClassMember> classMembers) {

                if (userInfo.getRole() == Role.LECTURER) {
                    if (classMembers == null || classMembers.size() <= 1) {
                        return;
                    }
                    boolean accompaniment = false;
//                    for (ClassMember member : classMembers) {
//                        if (member.getRole() != Role.LECTURER && member.getScheduleStudentMusicScores() != null && member.getScheduleStudentMusicScores().size() > 0) {
//                            for (ClassMember.ScheduleStudentMusicScoresBean bean : member.getScheduleStudentMusicScores()) {
//                                if (bean != null && (bean.getPlayStatus() == 1 || bean.getAccompanimentPlayStatus() == 1)) {
//                                    accompaniment = true;
//                                    continue;
//                                }
//                            }
//
//                        }
//                    }

//                    if (noJoinStuClassMembers != null && noJoinStuClassMembers.size() > 0) {
                    accompaniment = classViewModel.isOnMusicIsPlay();
//                    }
                    if (!accompaniment) {
                        isPlayMusic = false;
                        ivPlay.setImageResource(R.drawable.ic_live_teaching_accompaniment_start);
                    } else if (classViewModel.isOnMusicIsPlay()) {
                        isPlayMusic = true;
                        ivPlay.setImageResource(R.drawable.ic_live_teaching_accompaniment_stop);
                    }

                    if (!accompaniment) {
                        enableRTCAVInputStream(null, true);
                    }
                }
            }
        });
        classViewModel.getQueryNoJoinStu().observe(this, new Observer<List<ClassMember>>() {
            @Override
            public void onChanged(List<ClassMember> classMembers) {
                noJoinStuClassMembers.clear();
                noJoinStuClassMembers.addAll(classMembers);
            }
        });
    }

    public void showAccompanimentDialog() {
        showAccompanimentDialog(accompanimentDosnloadMembers, classViewModel.getMusicScoreAccompanimentId(), true);
    }

    private void showAccompanimentDialog(List<ClassMember> accompanimentDosnloadMembers, String musicScoreAccompanimentId, boolean isFor) {
        AccompanimentDialog accompanimentDialog = new AccompanimentDialog(getContext());
        accompanimentDialog.show();
        if (isFor) {
            for (ClassMember.ScheduleStudentMusicScoresBean musicScoresBean : musicScoresBeans) {
                if (musicScoreAccompanimentId.equals(musicScoresBean.getMusicScoreAccompanimentId())) {
                    fileName = musicScoresBean.getMusicScoreName();
                    LogUtils.e(fileName + "=====================================");
                    continue;
                }
            }
        }
        accompanimentDialog.setTitle(fileName);
        accompanimentDialog.setData(accompanimentDosnloadMembers, musicScoreAccompanimentId);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case QU_LIBRAY_REQUEST_CODE:

                    musicScoreAccompanimentDownloadId = data.getStringExtra("fileId");
                    String url = data.getStringExtra("fileUrl");
                    String mp3Url = data.getStringExtra("mp3Url");
                    fileName = data.getStringExtra("fileName");
                    String speed = data.getStringExtra("speed");

                    if (TextUtils.isEmpty(musicScoreAccompanimentDownloadId) || (TextUtils.isEmpty(url) && TextUtils.isEmpty(mp3Url)) || TextUtils.isEmpty(fileName) || userInfo == null) {
                        ToastUtil.getInstance().show(getContext(), "伴奏信息异常，请重新选择");
                        return;
                    }

                    isShowDownloadPopu = true;
                    classViewModel.pushDownloadexamSongMsg(roomId, musicScoreAccompanimentDownloadId, url, mp3Url, fileName, speed, new ResultCallback<Boolean>() {
                        @Override
                        public void onSuccess(Boolean aBoolean) {

                        }

                        @Override
                        public void onFail(int errorCode, String errorStr) {
                            if (!TextUtils.isEmpty(errorStr)) {
                                ToastUtil.getInstance().show(getContext(), errorStr);
                            } else {
                                ToastUtil.getInstance().show(getContext(), "ERROR；错误码:" + errorCode);
                            }
                        }
                    });
                    break;
            }
        }
    }

    /**
     * 打开伴奏
     */
    private void showAccompanimentPlayDialog() {
        if (TextUtils.isEmpty(classViewModel.getMusicScoreAccompanimentId())) {
            ToastUtil.getInstance().show(getActivity(), "请先选择伴奏");
            return;
        }
        String hint = "";
        List<String> list = new ArrayList<>();
        for (ClassMember member : accompanimentDosnloadMembers) {
            for (ClassMember.ScheduleStudentMusicScoresBean musicScoresBean : member.getScheduleStudentMusicScores()) {
                if (musicScoresBean != null && classViewModel.getMusicScoreAccompanimentId().equals(musicScoresBean.getMusicScoreAccompanimentId()) && musicScoresBean.getDownStatus() != 1)
                    list.add(member.getUserName());
            }

        }
        int nextType = 0;
        if (!isPlayMusic && classViewModel.isOnMetronomeIsPlay()) {
            if (list.size() != 0 && list.size() == accompanimentDosnloadMembers.size()) {
                hint = "学员的节拍器已开启，学员还未下载完成，是否关闭节拍器？";
            } else if (list.size() != 0) {
                hint = "学员的节拍器已开启," + TextUtils.join(",", list) + "还未下载完成，是否关闭节拍器并开启伴奏？";
            } else {
                hint = "学员的节拍器已开启，是否关闭节拍器并开启伴奏？";
            }
            nextType = 1;
        }

        if (nextType == 1) {
            LiveCommonDialog dialog = new LiveCommonDialog(getContext());
            dialog.show();
            dialog.setTitle("提示");
            dialog.setContent(hint);
            dialog.setOnConfirmClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setMetronome(false);
                    List<ClassMember> classMembers = classViewModel.getMemberList().getValue();
                    for (ClassMember member : classMembers) {
                        for (ClassMember.ScheduleStudentMusicScoresBean musicScoresBean : member.getScheduleStudentMusicScores()) {
                            if (musicScoresBean != null && classViewModel.getMusicScoreAccompanimentId().equals(musicScoresBean.getMusicScoreAccompanimentId())) {
                                musicScoresBean.setPlayStatus(!isPlayAccompaniment ? 0 : 1);
                                musicScoresBean.setAccompanimentPlayStatus(isPlayAccompaniment ? 0 : 1);
                            } else {
                                musicScoresBean.setPlayStatus(0);
                                musicScoresBean.setAccompanimentPlayStatus(0);
                            }
                        }
                    }

                    listener.onMetronomeOrAccompanimentIsPlay(!isPlayMusic);
                    setAccompaniment(!isPlayMusic);
                    dialog.dismiss();
                }
            });
            dialog.setOnCancelClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
        } else {
            List<ClassMember> classMembers = classViewModel.getMemberList().getValue();
            for (ClassMember member : classMembers) {
                for (ClassMember.ScheduleStudentMusicScoresBean musicScoresBean : member.getScheduleStudentMusicScores()) {
                    if (musicScoresBean != null && classViewModel.getMusicScoreAccompanimentId().equals(musicScoresBean.getMusicScoreAccompanimentId())) {
                        musicScoresBean.setPlayStatus(!isPlayAccompaniment ? 0 : 1);
                        musicScoresBean.setAccompanimentPlayStatus(isPlayAccompaniment ? 0 : 1);
                    } else {
                        musicScoresBean.setPlayStatus(0);
                        musicScoresBean.setAccompanimentPlayStatus(0);
                    }
                }
            }

            listener.onMetronomeOrAccompanimentIsPlay(!isPlayMusic);
            setAccompaniment(!isPlayMusic);
        }


    }

    public void clearChecked() {
        if (ivPlay != null) {
            ivPlay.setImageResource(R.drawable.ic_live_teaching_accompaniment_start);
        }
        selectPosition = 0;
        isPlayMusic = false;
        isPlayAccompaniment = false;
        isShowDownloadPopu = false;
        musicScoreAccompanimentDownloadId = null;
    }

    public void setAccompaniment(boolean isPlay) {
        classViewModel.setOnMusicIsPlay(isPlay);
        isPlayMusic = isPlay;
        setMusicName();
        if (isPlayMusic) {
            ivPlay.setImageResource(R.drawable.ic_live_teaching_accompaniment_stop);
        } else {
            ivPlay.setImageResource(R.drawable.ic_live_teaching_accompaniment_start);
        }
        String musicScoreOn = null;
        String accompanimentOn = null;
        musicScoreOn = isPlayAccompaniment ? null : String.valueOf(isPlay);
        accompanimentOn = isPlayAccompaniment ? String.valueOf(isPlay) : null;


        classViewModel.batchControlExamSong(roomId, null, musicScoreOn, accompanimentOn, classViewModel.getMusicScoreAccompanimentId(), volumeSeekerBarProcess);
    }

    public void setMetronome(boolean isPlay) {
        classViewModel.setOnMetronomeIsPlay(isPlay);
        List<ClassMember> classMembers = classViewModel.getMemberList().getValue();
        for (ClassMember member : classMembers) {
            ClassMember.PlayMidiJsonBean bean = member.getPlayMidiJson();
            if (bean == null) {
                bean = new ClassMember.PlayMidiJsonBean();
            }
            bean.setEnable(isPlay);
            member.setPlayMidiJson(bean);
        }

        classViewModel.sendImPlayMidiMessage(null, roomId, isPlay, new ResultCallback<Boolean>() {
            @Override
            public void onSuccess(Boolean aBoolean) {

            }

            @Override
            public void onFail(int errorCode, String errorStr) {

            }
        });

    }

    /**
     * 1.打开节拍器默认只播放第一个学生的流 学生member ，false;
     * 2.关闭节拍器，打开所有人的流null ，true;
     * 3.老师点击切换时，关闭上一个学生的音频，打开现在的学生的音频 newMember ，false
     * 是否播放其它人员音频流
     *
     * @param member
     * @param enable
     */
    private void enableRTCAVInputStream(ClassMember member, boolean enable) {

        if (null != classViewModel) {
            List<ClassMember> memberList = classViewModel.getMemberList().getValue();
            if (Role.LECTURER == userInfo.getRole()) {
                for (ClassMember listMemberMode : memberList) {
                    if (listMemberMode.getRole() != Role.LECTURER) {
                        if (null == member) {
                            classViewModel.enableRTCAVInputStream(listMemberMode.getUserId(), enable);
                        } else if (member.getRole() != Role.LECTURER && !member.getUserId().equals(listMemberMode.getUserId())) {
                            classViewModel.enableRTCAVInputStream(listMemberMode.getUserId(), enable);
                        } else if (member.getRole() != Role.LECTURER) {
                            classViewModel.enableRTCAVInputStream(listMemberMode.getUserId(), !enable);
                        }

                    }
                }
            }
        }
    }


    public OnListener listener;

    /**
     * 设置 Button 选择监听
     */
    public void setOnClickListener(OnListener listener) {
        this.listener = listener;
    }


    /**
     * Button 选择监听
     */
    public interface OnListener {

        /**
         * 隐藏
         */
        void onClose();

        /**
         * 是否播放
         */
        void onMetronomeOrAccompanimentIsPlay(boolean isPlay);

        void showMusicNameView(String musicName);

    }

}