package com.beanpodtech.allinone.activity;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;

import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.aliyun.svideo.common.utils.ToastUtils;
import com.beanpodtech.allinone.R;
import com.beanpodtech.allinone.adapter.CourseArrangingAdapter;
import com.beanpodtech.allinone.bean.CourseArrangingInfoBean;
import com.beanpodtech.allinone.bean.FaceToFaceInfoBean;
import com.beanpodtech.allinone.http.UrlConfig;
import com.beanpodtech.allinone.utils.Contants;
import com.beanpodtech.allinone.utils.HttpUtils;
import com.beanpodtech.allinone.utils.OkGoBuilder;
import com.beanpodtech.allinone.utils.OkGoUtil;
import com.beanpodtech.allinone.utils.SpUtil;
import com.lzy.okgo.model.Response;

import org.jetbrains.annotations.NotNull;

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


import cn.eeo.classinsdk.ClassInSdkManager;
import cn.eeo.classinsdk.support.ScreenOrientation;

public class FaceToFaceVideoActivity extends Activity implements View.OnClickListener {

    private Context mContext = this;
    private RecyclerView mRecyclerView;
    private CourseArrangingAdapter mAdapter;
    private List<CourseArrangingInfoBean.ListBean> mList = new ArrayList<>();

    private static final String[] REQUESTED_PERMISSIONS = {
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    private static final int PERMISSION_REQ_ID = 302;

    private boolean checkSelfPermission(String permission, int requestCode) {
        if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, REQUESTED_PERMISSIONS, requestCode);
            return false;
        }

        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions, @NonNull int[] grantResults) {

        if (requestCode == PERMISSION_REQ_ID) {
            if (grantResults[0] != PackageManager.PERMISSION_GRANTED ||
                    grantResults[1] != PackageManager.PERMISSION_GRANTED ||
                    grantResults[2] != PackageManager.PERMISSION_GRANTED) {
                showToast("Need permissions " + Manifest.permission.RECORD_AUDIO +
                        "/" + Manifest.permission.CAMERA + "/" + Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
        }
    }

    private void showToast(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
            }
        });
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_face_to_face_video);
        TextView tvTitle = findViewById(R.id.tv_title);
        tvTitle.setText(R.string.course_schedule);
        ImageView back = findViewById(R.id.iv_back);
        back.setOnClickListener(this);

        initView();
    }

    private void initView() {

        mRecyclerView = findViewById(R.id.id_course_arranging_recyclerview);
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        mAdapter = new CourseArrangingAdapter(mList, this);
        mAdapter.setOnBtnClickListener(new CourseArrangingAdapter.OnBtnClickListener() {
            @Override
            public void onBtnClick(int pos) {

                if (isFastClick()) return;

                mAdapter.notifyItemChanged(pos);// 改变按钮颜色

                CourseArrangingInfoBean.ListBean bean = mList.get(pos);

                //提前10分钟
                long startTime = (bean.getStartTime() * 1000) - (10 * 60 * 1000);
                long endTime = bean.getEndTime() * 1000;
//                Log.e("AAAAAAAAAAAAA", "startTime :" + startTime + " endTime: " + endTime);
//
                if (System.currentTimeMillis() >= startTime && System.currentTimeMillis() < endTime) { //进入教室
                    if (checkSelfPermission(REQUESTED_PERMISSIONS[0], PERMISSION_REQ_ID) &&
                            checkSelfPermission(REQUESTED_PERMISSIONS[1], PERMISSION_REQ_ID) &&
                            checkSelfPermission(REQUESTED_PERMISSIONS[2], PERMISSION_REQ_ID)) {
                        requestFaceToFaceVideoCourse(bean.getFaceToFacLessonId(), bean.getStartTime());
                    }
                } else if (endTime < System.currentTimeMillis()) { // 过期

                } else {// 未到上课时间
//                    刷新单个UI
                    Toast.makeText(FaceToFaceVideoActivity.this, "不在上课时间内~", Toast.LENGTH_LONG).show();
                }
            }
        });
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());

        getCourseArrangingInfos();
    }


    /*
     *  进入教室
     * */
    private void requestFaceToFaceVideoCourse(String faceToFaceLessonId, long startTimeSeconds) {

        OkGoBuilder.getInstance()
                .url(UrlConfig.GET_FACETOFACE_INFO)
                .Builder((Activity) mContext)
                .method(OkGoBuilder.PSOT)
                .cls(FaceToFaceInfoBean.class)
                .requestBody(HttpUtils.getRequestJson(getRequestBodyForFaceToFaceInfo(faceToFaceLessonId)))
                .callback(new OkGoUtil<FaceToFaceInfoBean>(FaceToFaceInfoBean.class) {
                    @Override
                    public void onSuccess(Response<FaceToFaceInfoBean> response) {

                        FaceToFaceInfoBean body = response.body();
                        if (body != null) {
                            if (!"0".equals(body.getState())) {
                                // state  0 待上课 1 已上完  2 没上课
                            } else {
                                if (TextUtils.isEmpty(body.getAccount())) {
                                    ToastUtils.show(mContext, R.string.no_account);
                                    return;
                                }

                                String stuName = SpUtil.getInstace().getString(Contants.USER_NICKNAME, null);

                                try {
                                    ClassInSdkManager.setEnableEvalPage(true);
                                    ClassInSdkManager.setEnableSoftDecoder(true);
                                    ClassInSdkManager.setEnableUdp(false);
                                    ClassInSdkManager.setDefaultScreenOrientation(ScreenOrientation.LANDSCAPE);

//                                    Log.e("AAAAAAAAAA",
//                                            "account:" + body.getAccount()
//                                                    + " schoolid:" + body.getSchoolId()
//                                                    + " courseId:" + body.getCourseId()
//                                                    + " lessonId:" + body.getLessonId());

                                    ClassInSdkManager.openClassRoom((Activity) mContext,
                                            body.getAccount(),
                                            Long.parseLong(body.getSchoolId()),
                                            Long.parseLong(body.getCourseId()),
                                            Long.parseLong(body.getLessonId()),
                                            stuName == null ? "学生" : stuName,
                                            new ClassInSdkManager.OnEnterRoomStateListener() {

                                                //ClassInSdkManager.openClassRoom((Activity) mContext, "17740028532", 101110l, 42451, 37449, "dd", new ClassInSdkManager.OnEnterRoomStateListener() {

                                                @Override
                                                public void onExitRoom(int i, @NotNull String s) {
                                                    long timeSpan = (System.currentTimeMillis() - startTimeSeconds * 1000) / 1000;
                                                    String timeSpanStr = "";
                                                    if (timeSpan < 60) {
                                                        timeSpanStr = timeSpan + "秒";
                                                    } else if (timeSpan < 3600) {
                                                        timeSpanStr = (timeSpan / 60) + "分" + (timeSpan % 60) + "秒";
                                                    } else if (timeSpan > 3600) {
                                                        timeSpanStr = (timeSpan / (3600)) + "小时" + ((timeSpan / 60) % 60) + "分" + (timeSpan % 60) + "秒";
                                                    }
                                                    Toast.makeText(mContext, "Code:" + i + " | " + s + " 耗费时长：" + timeSpanStr, Toast.LENGTH_SHORT).show();
                                                    //overClassinQA();
                                                }

                                                @Override
                                                public void onEnterSuccess() {
                                                    Toast.makeText(mContext, "进入成功", Toast.LENGTH_SHORT).show();
//                                                    classinStartTime = System.currentTimeMillis();
//                                                    entryClassinRoom();
                                                }

                                                @Override
                                                public void onEnterFailed(@NotNull String s) {
                                                    Toast.makeText(mContext, s, Toast.LENGTH_SHORT).show();
                                                }
                                            });
                                } catch (Exception e) {
                                    Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_LONG).show();
                                }
                            }
                        } else {
                            ToastUtils.show(mContext, R.string.neterror);
                        }
                    }

                    @Override
                    public void onError(Response<FaceToFaceInfoBean> response) {
                        super.onError(response);
                    }
                }).build();
    }


    /*
     *  获取排课列表
     * */
    private void getCourseArrangingInfos() {
        OkGoBuilder.getInstance().url(UrlConfig.GET_COURSE_ARRANGING_LIST).Builder((Activity) mContext)
                .method(OkGoBuilder.PSOT).cls(CourseArrangingInfoBean.class)
                .requestBody(HttpUtils.getRequestJson(getRequestBodyForCourseArranging()))
                .callback(new OkGoUtil<CourseArrangingInfoBean>(CourseArrangingInfoBean.class) {
                    @Override
                    public void onSuccess(Response<CourseArrangingInfoBean> response) {
                        CourseArrangingInfoBean body = response.body();
                        mList.clear();
                        if (body != null) {
                            List<CourseArrangingInfoBean.ListBean> list = body.getList();
                            if (list != null && list.size() > 0) {
                                mList.addAll(list);
                            }
                        } else {
                            ToastUtils.show(mContext, R.string.neterror);
                        }
                        mAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(Response<CourseArrangingInfoBean> response) {
                        super.onError(response);
                        mList.clear();
                        mAdapter.notifyDataSetChanged();
                        ToastUtils.show(mContext, R.string.neterror);
                    }
                }).build();
    }

    private HashMap<String, String> getRequestBodyForFaceToFaceInfo(String faceToFaceLessonId) {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", SpUtil.getInstace().getString(Contants.USER_ID, null));
        map.put("faceToFacLessonId", faceToFaceLessonId);
        return map;
    }

    private HashMap<String, String> getRequestBodyForCourseArranging() {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", SpUtil.getInstace().getString(Contants.USER_ID, null));
        return map;
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
        }
    }

    private static final int MIN_CLICK_DELAY_TIME = 1000;
    private static long lastClickTime;

    // 使用 if (isFastClick()) return;
    public static boolean isFastClick() {

        long curClickTime = System.currentTimeMillis();

        if ((curClickTime - lastClickTime) < MIN_CLICK_DELAY_TIME) {
            return true;
        }
        lastClickTime = curClickTime;

        return false;

    }


    //假数据
    /*private void setFakeData() {

        mList.clear();
        for (int i = 0; i < 10; i++) {

            CourseArrangingInfoBean.ListBean bean = new CourseArrangingInfoBean.ListBean();
            bean.setEndTime(System.currentTimeMillis());
            bean.setStartTime(System.currentTimeMillis());
            bean.setTimeSpan("120分钟");
            bean.setFaceToFacLessonIntroduce("数学");
            bean.setTeacherName("张梓琳");

            mList.add(bean);
        }

        mAdapter.notifyDataSetChanged();
    }*/
}