package com.zztrapp.zztrapp.ui.currency.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.netease.yunxin.kit.meeting.sdk.NECallback;
import com.netease.yunxin.kit.meeting.sdk.NEJoinMeetingOptions;
import com.netease.yunxin.kit.meeting.sdk.NEJoinMeetingParams;
import com.netease.yunxin.kit.meeting.sdk.NEMeetingCode;
import com.netease.yunxin.kit.meeting.sdk.NEMeetingError;
import com.netease.yunxin.kit.meeting.sdk.NEMeetingIdDisplayOption;
import com.netease.yunxin.kit.meeting.sdk.NEMeetingKit;
import com.netease.yunxin.kit.meeting.sdk.NEMeetingStatus;
import com.netease.yunxin.kit.meeting.sdk.NEMeetingStatusListener;
import com.netease.yunxin.kit.meeting.sdk.NEWindowMode;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.zztrapp.zztrapp.R;
import com.zztrapp.zztrapp.base.BaseActivity;
import com.zztrapp.zztrapp.bean.HttpResult;
import com.zztrapp.zztrapp.bean.MeetListBean;
import com.zztrapp.zztrapp.constant.Constant;
import com.zztrapp.zztrapp.databinding.ActivityVideoconferencingBinding;
import com.zztrapp.zztrapp.http.HttpMethods;
import com.zztrapp.zztrapp.http.ISubscriberOnNextListener;
import com.zztrapp.zztrapp.http.ProgressSubscriber;
import com.zztrapp.zztrapp.http.RxApiManager;
import com.zztrapp.zztrapp.ui.currency.adapter.VideoconferencingAdapter;
import com.zztrapp.zztrapp.utilcode.klogs.KLog;
import com.zztrapp.zztrapp.utilcode.util.SPUtils;
import com.zztrapp.zztrapp.utilcode.util.ToastUtils;

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

/**
 * Describe 视频会议
 * Created by Bby on 2022/6/23
 * Email bby0856@163.com
 */
public class VideoconferencingActivity extends BaseActivity {
    private Dialog mDialog;

    private int pageNo = 1;//页数
    private int total = 0;//总共多少页
    private boolean isShowDialog = true;
    private boolean isRefresh = true;//true 刷新 false 加载
    private int zt = 0;//进行中 zt=1  历史 zt =2  在加个预约会议 zt=0
    private List<MeetListBean.RecordsBean> list = new ArrayList<>();
    private VideoconferencingAdapter adapter;

    private ActivityVideoconferencingBinding binding;
    private String accountId;
    private String accountToken;


    @Override
    public View getLayoutId() {
        return binding.getRoot();
    }

    @Override
    protected void initBinding() {
        binding = ActivityVideoconferencingBinding.inflate(getLayoutInflater());
    }

    @Override
    public void onResume() {
        super.onResume();
        isShowDialog = true;
        isRefresh = true;
        pageNo = 1;
        loadList();
    }

    @Override
    protected void init() {
        accountId = SPUtils.getInstance().getString("accountId");
        accountToken = SPUtils.getInstance().getString("accountToken");
        NEMeetingKit.getInstance().login(accountId, accountToken, new NECallback<Void>() {
            @Override
            public void onResult(int resultCode, String resultMsg, Void result) {
                if (resultCode == NEMeetingError.ERROR_CODE_SUCCESS) {
                    //登录成功
                    KLog.e("--------登录成功");
                } else {
                    //登录失败
                    KLog.e("--------登录失败");
                    KLog.e(resultCode + "--------登录失败" + resultMsg);
                }
            }
        });
        mDialog = initProgressDialog(VideoconferencingActivity.this, "");
        binding.navView.navTitle.setText("视频会议");
        binding.navView.navBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        binding.refresh.setRefreshHeader(new ClassicsHeader(this));
        binding.refresh.setRefreshFooter(new ClassicsFooter(this));
        binding.refresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isShowDialog = false;
                isRefresh = false;
                pageNo += 1;
                if (pageNo <= total) {
                    loadList();
                }
                refreshLayout.finishLoadMore();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                isShowDialog = false;
                isRefresh = true;
                pageNo = 1;
                loadList();
                refreshLayout.finishRefresh();
            }
        });
        binding.rv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        adapter = new VideoconferencingAdapter(this);
        binding.rv.setAdapter(adapter);
        adapter.setOnItemClickListener(new VideoconferencingAdapter.OnItemClickListener() {
            @Override
            public void onJoinClick(int position) {
                if (!mDialog.isShowing()) {
                    mDialog.show();
                }
                SPUtils.getInstance().put("sphyId", list.get(position).getId());
                jrhy(position);
            }
        });
        NEMeetingStatusListener listener = new NEMeetingStatusListener() {
            @Override
            public void onMeetingStatusChanged(Event event) {
                //处理会议状态变更事件
                if (event.status == NEMeetingStatus.MEETING_STATUS_DISCONNECTING) {
                    //当前正在从会议中断开，原因为自己作为主持人主动结束了会议
                    if (event.arg == NEMeetingCode.MEETING_DISCONNECTING_CLOSED_BY_SELF_AS_HOST) {
                        String sphyId = SPUtils.getInstance().getString("sphyId");
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("id", sphyId);
                        closeHy(map);
                    }
                }

            }
        };
        NEMeetingKit.getInstance().getMeetingService().addMeetingStatusListener(listener);
    }

    //加入会议
    private void jrhy(int position) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("sphyId", list.get(position).getId());
        map.put("jrfs", "app");
        ISubscriberOnNextListener<HttpResult<String>> iSubscriberOnNextListener = new ISubscriberOnNextListener<HttpResult<String>>() {
            @Override
            public void onNext(HttpResult<String> httpResult) {
                if (httpResult.getCode() == 200) {
                    NEJoinMeetingParams params = new NEJoinMeetingParams();     //会议参数
                    params.meetingId = list.get(position).getHyh();                             //会议号
                    params.displayName = list.get(position).getHymc();           //会议昵称
//                    params.password = "123456";                                 //会议密码
                    NEJoinMeetingOptions options = new NEJoinMeetingOptions();   //会议选项，可自定义会中的 UI 显示、菜单、行为等
                    options.noVideo = true;                                      //入会时关闭视频，默认为 true
                    options.noAudio = true;                                      //入会时关闭音频，默认为 true
                    options.noInvite = false;                                    //入会隐藏"邀请"按钮，默认为 false
                    options.noChat = false;                                      //入会隐藏"聊天"按钮，默认为 false
                    options.noWhiteBoard = false;                                //入会隐藏白板入口，默认为 false
                    options.noGallery = false;                                //入会隐藏设置"画廊模式"入口，默认为 false
                    options.noSwitchCamera = false;                                //入会隐藏"切换摄像头"功能入口，默认为 false
                    options.noSwitchAudioMode = false;                               //入会隐藏"切换音频模式"功能入口，默认为 false
                    options.noRename = false;                                //入会隐藏"改名"功能入口，默认为 false
                    options.showMeetingTime = false;                                //设置入会后是否显示会议持续时间，默认为 false
//                    options.noCloudRecord = true;                                //入会隐藏"录制中"显示，默认为 true
                    options.noMinimize = true;                                   //入会是否允许最小化会议页面，默认为 true
                    options.defaultWindowMode = NEWindowMode.normal;             //入会默认会议视图模式
                    options.meetingIdDisplayOption = NEMeetingIdDisplayOption.DISPLAY_ALL;   //设置会议中会议 ID 的显示规则，默认为全部显示
                    NEMeetingKit.getInstance().getMeetingService().joinMeeting(VideoconferencingActivity.this, params, options, new NECallback<Void>() {
                        @Override
                        public void onResult(int resultCode, String resultMsg, Void result) {
                            if (resultCode == NEMeetingError.ERROR_CODE_SUCCESS) {
                                if (mDialog != null && mDialog.isShowing()) {
                                    mDialog.dismiss();
                                }
                                //加入会议成功
                                KLog.e("加入会议成功");
                            } else {
                                if (mDialog != null && mDialog.isShowing()) {
                                    mDialog.dismiss();
                                }
                                NEMeetingKit.getInstance().login(accountId, accountToken, new NECallback<Void>() {
                                    @Override
                                    public void onResult(int resultCode, String resultMsg, Void result) {
                                        if (resultCode == NEMeetingError.ERROR_CODE_SUCCESS) {
                                            //登录成功
                                            KLog.e("--------登录成功");
                                        } else {
                                            //登录失败
                                            KLog.e("--------登录失败");
                                            KLog.e(resultCode + "--------登录失败" + resultMsg);
                                        }
                                    }
                                });
                                //加入会议失败
                                KLog.e("加入会议失败" + resultCode + resultMsg);
                                ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show("加入会议失败");
                            }
                        }
                    });
                } else {
                    if (mDialog != null && mDialog.isShowing()) {
                        mDialog.dismiss();
                    }
                    ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show(httpResult.getMessage());
                }
            }

            @Override
            public void onError(int code, String message) {
                if (mDialog != null && mDialog.isShowing()) {
                    mDialog.dismiss();
                }
                ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show(message);
            }
        };
        ProgressSubscriber<HttpResult<String>> httpResultProgressSubscriber = new ProgressSubscriber<>(iSubscriberOnNextListener, this, false);
        RxApiManager.get().add("jrhy", httpResultProgressSubscriber);
        HttpMethods.getInstance(this).jrhy(httpResultProgressSubscriber, map);
    }


    //结束视频会议
    private void closeHy(HashMap<String, Object> map) {
        ISubscriberOnNextListener<HttpResult<String>> iSubscriberOnNextListener = new ISubscriberOnNextListener<HttpResult<String>>() {
            @Override
            public void onNext(HttpResult<String> httpResult) {
                if (httpResult.getCode() == 200) {
                    isShowDialog = true;
                    isRefresh = true;
                    pageNo = 1;
                    loadList();
                } else {
                    ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show(httpResult.getMessage());
                }
            }

            @Override
            public void onError(int code, String message) {
                ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show(message);
            }
        };
        ProgressSubscriber<HttpResult<String>> httpResultProgressSubscriber = new ProgressSubscriber<>(iSubscriberOnNextListener, this, true);
        RxApiManager.get().add("closeHy", httpResultProgressSubscriber);
        HttpMethods.getInstance(this).closeHy(httpResultProgressSubscriber, map);
    }

    @Override
    protected void initOnClick() {
        binding.nav0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                binding.nav0Name.getPaint().setFakeBoldText(true);
                binding.nav1Name.getPaint().setFakeBoldText(false);
                binding.nav2Name.getPaint().setFakeBoldText(false);
                binding.nav0Name.setTextColor(getResources().getColor(R.color.color2C86FF));
                binding.nav1Name.setTextColor(getResources().getColor(R.color.color232323));
                binding.nav2Name.setTextColor(getResources().getColor(R.color.color232323));
                binding.line0.setBackgroundColor(getResources().getColor(R.color.color2C86FF));
                binding.line1.setBackgroundColor(getResources().getColor(R.color.colorTransparent));
                binding.line2.setBackgroundColor(getResources().getColor(R.color.colorTransparent));
                isShowDialog = true;
                isRefresh = true;
                zt = 0;
                pageNo = 1;
                loadList();
            }
        });
        binding.nav1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                binding.nav0Name.getPaint().setFakeBoldText(false);
                binding.nav1Name.getPaint().setFakeBoldText(true);
                binding.nav2Name.getPaint().setFakeBoldText(false);
                binding.nav0Name.setTextColor(getResources().getColor(R.color.color232323));
                binding.nav1Name.setTextColor(getResources().getColor(R.color.color232323));
                binding.nav2Name.setTextColor(getResources().getColor(R.color.color232323));
                binding.line0.setBackgroundColor(getResources().getColor(R.color.colorTransparent));
                binding.line1.setBackgroundColor(getResources().getColor(R.color.color2C86FF));
                binding.line2.setBackgroundColor(getResources().getColor(R.color.colorTransparent));
                isShowDialog = true;
                isRefresh = true;
                pageNo = 1;
                zt = 1;
                loadList();
            }
        });
        binding.nav2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                binding.nav0Name.getPaint().setFakeBoldText(false);
                binding.nav1Name.getPaint().setFakeBoldText(false);
                binding.nav2Name.getPaint().setFakeBoldText(true);
                binding.nav0Name.setTextColor(getResources().getColor(R.color.color232323));
                binding.nav1Name.setTextColor(getResources().getColor(R.color.color232323));
                binding.nav2Name.setTextColor(getResources().getColor(R.color.color2C86FF));
                binding.line0.setBackgroundColor(getResources().getColor(R.color.colorTransparent));
                binding.line1.setBackgroundColor(getResources().getColor(R.color.colorTransparent));
                binding.line2.setBackgroundColor(getResources().getColor(R.color.color2C86FF));
                isShowDialog = true;
                isRefresh = true;
                pageNo = 1;
                zt = 2;
                loadList();
            }
        });
        binding.addAppointmentMeeting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(VideoconferencingActivity.this, AddAppointmentMeetingActivity.class));
            }
        });
        binding.quickMeeting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(VideoconferencingActivity.this, QuickMeetingActivity.class));
            }
        });
    }


    //列表
    private void loadList() {
        ISubscriberOnNextListener<HttpResult<MeetListBean>> iSubscriberOnNextListener = new ISubscriberOnNextListener<HttpResult<MeetListBean>>() {
            @Override
            public void onNext(HttpResult<MeetListBean> httpResult) {
                if (httpResult.getCode() == 200) {
                    total = httpResult.getResult().getPages();
                    if (isRefresh) {
                        list.clear();
                    }
                    list.addAll(httpResult.getResult().getRecords());
                    KLog.e(list);
                    adapter.setData(list);
                } else {
                    ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show(httpResult.getMessage());
                }
            }

            @Override
            public void onError(int code, String message) {
                ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show(message);
            }
        };
        ProgressSubscriber<HttpResult<MeetListBean>> httpResultProgressSubscriber = new ProgressSubscriber<>(iSubscriberOnNextListener, this, isShowDialog);
        RxApiManager.get().add("sphyPageList", httpResultProgressSubscriber);
        HttpMethods.getInstance(this).sphyPageList(httpResultProgressSubscriber, pageNo, Constant.PAGE_SIZE, zt);
    }

    public Dialog initProgressDialog(Context context, String title) {
        if (mDialog == null) {
            mDialog = new Dialog(context, R.style.LoadingDialogStyle);
            mDialog.setContentView(R.layout.layout_dialog);
            mDialog.setCancelable(true);
            mDialog.setCanceledOnTouchOutside(false);
            mDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
            TextView msg = mDialog.findViewById(R.id.id_tv_loadingmsg);
            msg.setText(title);
            msg.setVisibility(View.GONE);
            mDialog.setCancelable(false);
        }
        return mDialog;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
        RxApiManager.get().cancel("sphyPageList");
        RxApiManager.get().cancel("closeHy");
    }
}