package com.daya.live_teaching.ui.fragmnet;

import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckBox;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.cooleshow.base.ui.fragment.BaseFragment;
import com.cooleshow.base.utils.LogUtils;
import com.cooleshow.base.utils.SizeUtils;
import com.cooleshow.base.utils.ToastUtil;
import com.daya.live_teaching.widget.dialog.LiveCommonDialog;
import com.daya.live_teaching.R;
import com.daya.live_teaching.common.ResultCallback;
import com.daya.live_teaching.databinding.FragmentTeachingToolsBinding;
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.viewmodel.ClassViewModel;
import com.daya.live_teaching.widget.OnOperateItemListener;
import com.daya.live_teaching.widget.OperateButtonGroupView;
import com.daya.live_teaching.widget.OperateItem;

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

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
public class TeachingToolsFragment extends BaseFragment<FragmentTeachingToolsBinding> {

    private UserInfo userInfoValue;
    private OperateButtonGroupView operateView;
    private boolean isPlayMetronme = false;
    private boolean isPlayMusic = false;
    private ClassViewModel classViewModel;
    public OperateControlListener listener;
    private String roomId;

    private List<ClassMember> accompanimentDosnloadMembers;
    private List<ClassMember> noJoinStuClassMembers = new ArrayList<>();

    public TeachingToolsFragment() {
        // Required empty public constructor
    }

    public enum Operate { // 控制按钮类型
        /**
         * 白板
         */
        SHARE_WHITE_BOARD(0),
        /**
         * 视频
         */
        SHARE_VIDEO(1),

        /**
         * 伴奏
         */
        ACCOMPANIMENT_SETTING(2),

        /**
         * 伴奏播放
         */
        ACCOMPANIMENT(3),

        /**
         * 节拍器
         */
        METRONOME_SETTING(4),

        /**
         * 节拍器播放
         */
        METRONOME(5);


        private int value;

        Operate(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }

        public static Operate getType(int value) {
            for (Operate type : Operate.values()) {
                if (value == type.getValue()) {
                    return type;
                }
            }
            return SHARE_VIDEO;
        }
    }

    //    // 按钮的资源布局
    private int[] leftbBtnBgResIds = new int[]{
            R.drawable.fragment_top_operate_white_board_selector,
            R.drawable.fragment_top_operate_share_video_selector,
            R.drawable.ic_top_operate_accompaniment_setting,
            R.drawable.fragment_top_accompaniment_selector,
            R.drawable.ic_metronome_setting,
            R.drawable.fragment_top_operate_metronome_selector,
    };

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

    @Override
    protected void initView(View rootView) {
        operateView = mViewBinding.operateView;
        initOperateItem();
    }


    @Override
    protected void initData() {
        classViewModel = ViewModelProviders.of(getActivity()).get(ClassViewModel.class);

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

            }
        });

        // 自己用户信息
        classViewModel.getUserInfo().observe(this, new Observer<UserInfo>() {


            @Override
            public void onChanged(UserInfo userInfo) {
                if (userInfo != null) {
                    userInfoValue = userInfo;

                }
            }
        });


        classViewModel.getMemberList().observe(this, new Observer<List<ClassMember>>() {
            @Override
            public void onChanged(List<ClassMember> classMembers) {
                if (userInfoValue.getRole() == Role.LECTURER) {
                    if (classMembers.size() <= 1) {
                        return;
                    }
                    boolean metronme = false;
                    boolean accompaniment = false;
                    for (ClassMember member : classMembers) {
                        if (member.getRole() != Role.LECTURER && member.getPlayMidiJson() != null && member.getPlayMidiJson().isEnable()) {
                            metronme = true;
                            classViewModel.setOnMetronomeIsPlay(true);
                        }

//                        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;
//                                }
//                            }
//
//                        }


                    }

                    if (noJoinStuClassMembers != null && noJoinStuClassMembers.size() > 0) {
                        metronme = classViewModel.isOnMetronomeIsPlay();
                    }
                    accompaniment = classViewModel.isOnMusicIsPlay();

                    LogUtils.e(metronme + ":" + accompaniment);
                    if (!metronme) {
                        isPlayMetronme = false;
                        CheckBox button = operateView.getView(Operate.METRONOME.getValue());
                        button.setChecked(false);
                        classViewModel.setOnMetronomeIsPlay(false);
                    }
                    if (!accompaniment) {
                        isPlayMusic = false;
                        CheckBox button = operateView.getView(Operate.ACCOMPANIMENT.getValue());
                        if (button != null) {
                            button.setChecked(false);
                        }
//                        classViewModel.setOnMusicIsPlay(false);
                    } else {
                        isPlayMusic = true;
                        CheckBox button = operateView.getView(Operate.ACCOMPANIMENT.getValue());
                        if (button != null) {
                            button.setChecked(true);
                        }
                    }

                    if (!metronme && !accompaniment) {
                        enableRTCAVInputStream(null, true);
                    }
                }
            }
        });
        classViewModel.getQueryNoJoinStu().observe(this, new Observer<List<ClassMember>>() {
            @Override
            public void onChanged(List<ClassMember> classMembers) {
                if (noJoinStuClassMembers != null) {
                    noJoinStuClassMembers.clear();
                    noJoinStuClassMembers.addAll(classMembers);
                }
            }
        });
        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());

                }
            }
        });


    }

    private void initOperateItem() {
        // 初始化动态添加控制按钮
        List<OperateItem> items = new ArrayList<>();
        int value = SizeUtils.dp2px(44);
        int marginLeft = SizeUtils.dp2px(10);
        for (Operate operate : Operate.values()) {
            if (operate == Operate.ACCOMPANIMENT || operate == Operate.ACCOMPANIMENT_SETTING) {
                //暂时隐藏伴奏和伴奏下载
                continue;
            }
            OperateItem item = new OperateItem();
            item.id = operate.getValue();
            item.bgResId = leftbBtnBgResIds[operate.getValue()];
            item.width = value;
            item.height = value;
//            item.right = marginLeft;
            if (operate == Operate.SHARE_WHITE_BOARD || operate == Operate.SHARE_VIDEO) {
                item.type = OperateItem.Type.CHECKBOX;
            } else {
                item.type = OperateItem.Type.CHECKBOX;
            }
            items.add(item);
        }

        // 初始化操作布局
        operateView.initView(items, new OnOperateItemListener() {
            @Override
            public void onItemClicked(View v, OperateItem item) {
                if (listener == null) {
                    ToastUtil.getInstance().show(getActivity(), "请稍后");
                    return;
                }
                Operate type = Operate.getType(item.id);
                switch (type) {

                    default:
                        break;
                }
            }

            @Override
            public void onCheckedChanged(View v, OperateItem item, boolean isChecked) {
                Operate type = Operate.getType(item.id);

                if (v.isPressed()) {
                    if (null == listener) {
                        CheckBox box = operateView.getView(type.getValue());
                        box.setChecked(!isChecked);
                        ToastUtil.getInstance().show(getActivity(), "请稍后");
                        return;
                    }
                    switch (type) {
                        case SHARE_WHITE_BOARD:
                        case SHARE_VIDEO:
                            listener.onShareWhiteBoardOrVideo(type);
                            checkButton(item.id);
                            break;
                        case METRONOME:
                            showMetronomeDialog(type);
                            break;
                        case ACCOMPANIMENT:
                            showAccompanimentPlayDialog(type);
                            break;
                        case ACCOMPANIMENT_SETTING:
                            listener.showAccompaniment();
                            break;
                        case METRONOME_SETTING:
                            MetronomeFragmentDialog fragment = new MetronomeFragmentDialog();
                            fragment.setGravity(Gravity.CENTER);
                            fragment.show(getChildFragmentManager(), "");
                            break;
                    }
                }
            }
        });
        clearChecked();
    }

    private void showAccompanimentPlayDialog(Operate type) {
        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;
        } else if (!isPlayMusic) {
            if (list.size() != 0 && list.size() == accompanimentDosnloadMembers.size()) {
                hint = "学员还未下载完成，确定开启伴奏吗？";
            } else if (list.size() != 0) {
                hint = "学员：" + TextUtils.join(",", list) + "还未下载完成，确定开启伴奏吗？";
            } else {
                hint = "确定要开启全员的伴奏吗?";
            }
        }
        int finalNextType = nextType;
        LiveCommonDialog dialog = new LiveCommonDialog(getContext());
        dialog.show();
        dialog.setTitle("提示");
        dialog.setContent(hint);
        dialog.setOnCancelClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setOnConfirmClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (finalNextType == 1) {
                    setMetronome(false, Operate.METRONOME);
                }
                if (isPlayMusic) {
                    listener.onMetronomeOrAccompanimentIsPlay(false);
                    setAccompaniment(false, type);
                } else {
                    listener.onMetronomeOrAccompanimentIsPlay(true);
                    setAccompaniment(true, type);
                }
                dialog.dismiss();
            }
        });
    }

    public void setAccompaniment(boolean isPlay, Operate type) {
        CheckBox button = operateView.getView(type.getValue());
        classViewModel.setOnMusicIsPlay(isPlay);
        isPlayMusic = isPlay;

        if (isPlayMusic) {
            button.setChecked(true);
        } else {
            button.setChecked(false);
        }
        String musicScoreOn = null;
        String accompanimentOn = null;
        musicScoreOn = classViewModel.isAccompaniment() ? null : String.valueOf(isPlay);
        accompanimentOn = classViewModel.isAccompaniment() ? String.valueOf(isPlay) : null;

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


    public void checkButton(int id) {
        Operate operate = Operate.getType(id);
        if (null != operateView && operate == Operate.SHARE_VIDEO) {
            //            leftOperateView.setItemEnabled(id, false);
            CheckBox box = operateView.getView(Operate.SHARE_WHITE_BOARD.getValue());
            box.setChecked(false);
            CheckBox videoBox = operateView.getView(Operate.SHARE_VIDEO.getValue());
            videoBox.setChecked(true);
        }
        if (null != operateView && operate == Operate.SHARE_WHITE_BOARD) {
            CheckBox box = operateView.getView(Operate.SHARE_VIDEO.getValue());
            box.setChecked(false);
            CheckBox whiteBoardBox = operateView.getView(Operate.SHARE_WHITE_BOARD.getValue());
            whiteBoardBox.setChecked(true);
        }
    }

    /**
     * 清除当前所选择的状态，默认选择视频列表选项
     */
    public void clearChecked() {
        if (operateView != null) {
            CheckBox box = operateView.getView(Operate.SHARE_VIDEO.getValue());
            box.setChecked(true);
            CheckBox box1 = operateView.getView(Operate.SHARE_WHITE_BOARD.getValue());
            box1.setChecked(false);
        }
        CheckBox accompaniment = operateView.getView(Operate.ACCOMPANIMENT.getValue());
        isPlayMusic = false;
        if (accompaniment != null) {
            accompaniment.setChecked(false);
        }
        CheckBox metronome = operateView.getView(Operate.METRONOME.getValue());
        isPlayMetronme = false;
        metronome.setChecked(false);
    }


    private void showMetronomeDialog(Operate type) {
        String hint;
        int nextType = 0;
        if (!isPlayMetronme && classViewModel.isOnMusicIsPlay()) {
            hint = "学员的伴奏已开启，是否关闭伴奏并开启节拍器？";
            nextType = 1;
        } else {
            hint = isPlayMetronme ? "确定要关闭全员的节拍器吗？" : "确定要打开全员的节拍器吗?";
        }
        int finalNextType = nextType;

        LiveCommonDialog dialog = new LiveCommonDialog(getContext());
        dialog.show();
        dialog.setTitle("提示");
        dialog.setContent(hint);
        dialog.setOnCancelClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setOnConfirmClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (finalNextType == 1) {
                    setAccompaniment(false, Operate.ACCOMPANIMENT);
                }
                if (isPlayMetronme) {
                    listener.onMetronomeOrAccompanimentIsPlay(false);
                    setMetronome(false, type);
                } else {
                    listener.onMetronomeOrAccompanimentIsPlay(true);
                    setMetronome(true, type);
                }
                dialog.dismiss();
            }
        });
    }

    public void setMetronome(boolean isPlay, Operate type) {
        CheckBox button = operateView.getView(type.getValue());
        classViewModel.setOnMetronomeIsPlay(isPlay);
        isPlayMetronme = 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);
        }
        if (isPlayMetronme) {
            button.setChecked(true);
        } else {
            button.setChecked(false);
        }
        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 == userInfoValue.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);
                        }

                    }
                }
            }
        }
    }


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

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

        /**
         * 白板
         */
        void onShareWhiteBoardOrVideo(Operate Operate);

        /**
         * 节拍器
         */
        void onMetronomeOrAccompanimentIsPlay(boolean isPlay);


        /**
         * 显示伴奏列表
         */
        void showAccompaniment();

    }

}