package com.cooleshow.student.ui.course;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import io.rong.imkit.utils.helper.OpenChatHelper;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.ui.video.VideoPlayActivity;
import com.cooleshow.base.utils.TimeUtils;
import com.cooleshow.base.utils.ToastUtils;
import com.cooleshow.base.ui.activity.BaseMVPActivity;
import com.cooleshow.base.utils.ActivityUtils;
import com.cooleshow.base.utils.FileUtils;
import com.cooleshow.base.utils.GlideUtils;
import com.cooleshow.base.utils.ToastUtil;
import com.cooleshow.base.utils.UiUtils;
import com.cooleshow.base.utils.helper.QMUIStatusBarHelper;
import com.cooleshow.student.R;
import com.cooleshow.student.adapter.ItemMarkAdapter;
import com.cooleshow.student.adapter.PracticeVideoWorkAdapter;
import com.cooleshow.student.bean.PracticeVideoWorkBean;
import com.cooleshow.student.bean.SparringCourseCommentBean;
import com.cooleshow.student.bean.SparringCourseHomeworkBean;
import com.cooleshow.student.constants.CourseConstants;
import com.cooleshow.student.contract.PracticeCourseDetailContract;
import com.cooleshow.student.databinding.ActivityPracticeCourseDetailLayoutBinding;
import com.cooleshow.student.presenter.course.PracticeCourseDetailPresenter;
import com.cooleshow.student.ui.work.HomeWorkDetailActivity;
import com.tbruyelle.rxpermissions3.RxPermissions;

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

/**
 * 创建日期：2022/5/31 9:40
 *
 * @author Ryan
 * 类说明：陪练课详情
 */

public class PracticeCourseDetailActivity extends BaseMVPActivity<ActivityPracticeCourseDetailLayoutBinding, PracticeCourseDetailPresenter> implements PracticeCourseDetailContract.PracticeCourseDetailView, View.OnClickListener {
    private final int CHOOSE_VIDEO = 1002;
    public static final String COURSE_ID = "course_id";
    public static final String COURSE_GROUP_ID = "course_group_id";
    private String mCourseId;
    private String mCourseGroupId;
    private String courseStatus = "";
    private RecyclerView rvVideo;
    private PracticeVideoWorkAdapter practiceVideoWorkAdapter;
    private SparringCourseHomeworkBean mInfoBean;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_do:
                switch (courseStatus) {
                    case CourseConstants.COURSE_STATUS_NOT_START:
                        //课程未开始
                        ToastUtil.getInstance().showShort("课程还未开始，请在上课前5分钟进入");
                        break;
                    case CourseConstants.COURSE_STATUS_ING:
                        //课程进行中
                        break;
                    case CourseConstants.COURSE_STATUS_COMPLETE:
                        //课程已结束
                        String submitContent = "";
                        for (PracticeVideoWorkBean listDatum : listData) {
                            if (!TextUtils.isEmpty(listDatum.videoUrl)) {
                                submitContent = listDatum.videoUrl + ",";
                            }
                        }
                        if (submitContent.contains(",")) {
                            submitContent = submitContent.substring(0, submitContent.length() - 1);
                            presenter.submitSparringCourseHomework(submitContent, mCourseId);
                        }
                        break;
                }
                break;
            case R.id.tv_evaluate:
                if (mInfoBean == null) {
                    return;
                }
                if (!TextUtils.equals(mInfoBean.courseStatus, CourseConstants.COURSE_STATUS_COMPLETE)) {
                    ToastUtil.getInstance().show(this, "课程结束之后才可以评价哦～");
                    return;
                }
                //评价老师
                ARouter.getInstance()
                        .build(RouterPath.CourseCenter.SPARRING_EVALUATE_TEACHER)
                        .withString("course_id", mCourseId)
                        .withString("course_group_id", mCourseGroupId)
                        .navigation();
                break;
            case R.id.iv_go_chat:
                //聊天
                if (mInfoBean != null) {
                    OpenChatHelper.goChat(PracticeCourseDetailActivity.this, mInfoBean.teacherId, mInfoBean.teacherName);
                }
                break;
        }
    }


    @Override
    protected void initView() {
        QMUIStatusBarHelper.setStatusBarLightMode(this);
        initMidTitleToolBar(viewBinding.toolbarInclude.toolbar, "课程详情");
        mCourseId = getIntent().getStringExtra(COURSE_ID);
        mCourseGroupId = getIntent().getStringExtra(COURSE_GROUP_ID);
        viewBinding.tvDo.setOnClickListener(this);
        viewBinding.tvEvaluate.setOnClickListener(this);
        viewBinding.ivGoChat.setOnClickListener(this);

        rvVideo = viewBinding.rvVideo;
        GridLayoutManager manager = new GridLayoutManager(this, 3);
        rvVideo.setLayoutManager(manager);
        practiceVideoWorkAdapter = new PracticeVideoWorkAdapter(listData);
        rvVideo.setAdapter(practiceVideoWorkAdapter);
        practiceVideoWorkAdapter.setItemAddClickAction(new PracticeVideoWorkAdapter.ItemAddClickAction() {
            @Override
            public void add() {
                getVideoPermission();
            }

            @Override
            public void previewVideo(String url) {
                if (!TextUtils.isEmpty(url)) {
                    VideoPlayActivity.start(PracticeCourseDetailActivity.this, url);
                }
            }

            @Override
            public void delVideo(int pos) {
                if (practiceVideoWorkAdapter != null && pos < listData.size()) {
                    listData.remove(pos);
                    practiceVideoWorkAdapter.notifyDataSetChanged();
                }
            }
        });

    }

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

    @Override
    protected PracticeCourseDetailPresenter createPresenter() {
        return new PracticeCourseDetailPresenter();
    }

    @Override
    public void initData() {
        super.initData();

    }

    @Override
    protected void onResume() {
        super.onResume();
        refresh();
    }

    private void refresh() {
        if (presenter != null) {
            presenter.getSparringCourseHomework(mCourseId);
            presenter.getSparringCourseComment(mCourseId, mCourseGroupId);
        }
    }

    @Override
    public void getSparringCourseHomeworkSuccess(SparringCourseHomeworkBean infoBean) {
        if (infoBean == null) {
            return;
        }
        mInfoBean = infoBean;
        viewBinding.tvCourseTime.setText(UiUtils.getCourseTimeString(infoBean.startTime, infoBean.endTime));

        //时间
        //老师头像
        GlideUtils.INSTANCE.loadImage(this, infoBean.teacherAvatar, viewBinding.ivAvatar, R.drawable.icon_teacher_default_head);
        //title
        viewBinding.tvTitle.setText(infoBean.teacherName);
        //声部名称
        RecyclerView rv_mark = viewBinding.rvCourseName;
        if (!TextUtils.isEmpty(infoBean.subjectName)) {
            rv_mark.setVisibility(View.VISIBLE);
            List<String> markList = new ArrayList<>();
            if (infoBean.subjectName.contains(",")) {
                String[] split = infoBean.subjectName.split(",");
                for (String s : split) {
                    markList.add(s);
                }
            } else {
                markList.add(infoBean.subjectName);
            }
            LinearLayoutManager manager = new LinearLayoutManager(this);
            manager.setOrientation(LinearLayoutManager.HORIZONTAL);
            rv_mark.setLayoutManager(manager);
            ItemMarkAdapter itemMarkAdapter = new ItemMarkAdapter(markList);
            rv_mark.setAdapter(itemMarkAdapter);
        } else {
            rv_mark.setVisibility(View.GONE);
        }
        courseStatus = infoBean.courseStatus;
        switch (courseStatus) {
            case CourseConstants.COURSE_STATUS_NOT_START:
                //课程未开始
                viewBinding.tvCourseStatus.setText(getString(R.string.course_not_start_str));
                viewBinding.tvCourseStatus.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_ff802c));
                viewBinding.tvDo.setTextColor(getResources().getColor(R.color.white));
                viewBinding.tvDo.setText("进入教室");
                viewBinding.tvDo.setBackgroundResource(R.drawable.shape_course_status_ing);
                break;
            case CourseConstants.COURSE_STATUS_ING:
                //课程进行中
                viewBinding.tvCourseStatus.setText(R.string.course_ing_str);
                viewBinding.tvCourseStatus.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_2dc7aa));
                viewBinding.tvDo.setTextColor(getResources().getColor(R.color.white));
                viewBinding.tvDo.setText("进入教室");
                viewBinding.tvDo.setBackgroundResource(R.drawable.shape_course_status_ing);
                break;
            case CourseConstants.COURSE_STATUS_COMPLETE:
                //课程已结束
                viewBinding.tvCourseStatus.setText(R.string.course_is_completed);
                viewBinding.tvCourseStatus.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_999999));
                viewBinding.tvDo.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_666666));
                viewBinding.tvDo.setText("确认提交");
                viewBinding.tvDo.setBackgroundResource(R.drawable.shape_e5e5e5_radius);
                break;
        }
        //课后作业
        handleHomeworkData(infoBean);
        //作业视频
        handleHomeworkStudentSubmit(infoBean);
        //作业点评
        handleHomeworkComment(infoBean);
    }

    private void handleHomeworkComment(SparringCourseHomeworkBean infoBean) {
        if (infoBean == null) {
            return;
        }
        if (infoBean.reviewHomework == 1) {
            //老师已点评作业
            viewBinding.tvWorkReview.setGravity(Gravity.LEFT | Gravity.TOP);
            viewBinding.tvWorkReview.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_333333));
            viewBinding.tvWorkReview.setText(infoBean.teacherReplied);
        } else {
            viewBinding.tvWorkReview.setGravity(Gravity.CENTER);
            viewBinding.tvWorkReview.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_999999));
            viewBinding.tvWorkReview.setText("课程结束后上传作业视频会得倒老师点评喔～");
        }
    }

    private List<PracticeVideoWorkBean> listData = new ArrayList<>();

    private void handleHomeworkStudentSubmit(SparringCourseHomeworkBean infoBean) {
        switch (courseStatus) {
            case CourseConstants.COURSE_STATUS_NOT_START:
                //课程未开始
            case CourseConstants.COURSE_STATUS_ING:
                //课程进行中
                rvVideo.setVisibility(View.GONE);
                viewBinding.tvVideoWork.setVisibility(View.VISIBLE);
                break;
            case CourseConstants.COURSE_STATUS_COMPLETE:
                //课程已结束
                if (infoBean.submitHomework == CourseConstants.COURSE_HOMEWORK_SET) {
                    rvVideo.setVisibility(View.VISIBLE);
                    viewBinding.tvVideoWork.setVisibility(View.GONE);
                    listData.clear();
                    if (!TextUtils.isEmpty(infoBean.studentAttachments)) {
                        String[] results = TextUtils.split(infoBean.studentAttachments, ",");
                        for (String result : results) {
                            listData.add(new PracticeVideoWorkBean(result, 0));
                        }
                    }
                    listData.add(new PracticeVideoWorkBean("", 1));
                    if (null != practiceVideoWorkAdapter) {
                        practiceVideoWorkAdapter.notifyDataSetChanged();
                    }
                } else {
                    rvVideo.setVisibility(View.GONE);
                    viewBinding.tvVideoWork.setVisibility(View.VISIBLE);
                }
                break;
        }
    }

    private void getVideoPermission() {
        new RxPermissions(this)
                .request(Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(granted -> {
                    if (granted) {
                        chooseVideo();
                    } else {
                        ToastUtil.getInstance().show(this, "请选择存储和相机权限！");
                    }
                });
    }

    private void chooseVideo() {
        Intent intent = new Intent();
        intent.setType("video/*"); //选择视频 (mp4 3gp 是android支持的视频格式)
        intent.setAction(Intent.ACTION_GET_CONTENT);
        /* 取得相片后返回本画面 */
        ActivityUtils.startActivityForResult(this, intent, CHOOSE_VIDEO);

    }

    private void handleHomeworkData(SparringCourseHomeworkBean infoBean) {
        if (infoBean == null) {
            return;
        }
        if (infoBean.decorateHomework == CourseConstants.COURSE_HOMEWORK_SET) {
            //已布置课后作业
            viewBinding.tvHomework.setGravity(Gravity.LEFT | Gravity.TOP);
            viewBinding.tvHomework.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_333333));
            viewBinding.tvHomework.setText(infoBean.content);
        } else {
            //未布置课后作业
            viewBinding.tvHomework.setGravity(Gravity.CENTER);
            viewBinding.tvHomework.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_999999));
            viewBinding.tvHomework.setText("课程结束后老师会布置作业喔～");
        }
    }


    @Override
    public void getSparringCourseCommentSuccess(SparringCourseCommentBean commentBean) {
        if (isFinishing() || isDestroyed()) {
            return;
        }
        if (commentBean != null && !TextUtils.isEmpty(commentBean.teacherReplied)) {
            //老师已评价 tv_set_teacher_comment
            viewBinding.tvTeacherAppraisal.setGravity(Gravity.LEFT | Gravity.TOP);
            viewBinding.tvTeacherAppraisal.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_333333));
            viewBinding.tvTeacherAppraisal.setText(commentBean.teacherReplied);
        } else {
            //老师未评价
            viewBinding.tvTeacherAppraisal.setGravity(Gravity.CENTER);
            viewBinding.tvTeacherAppraisal.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_999999));
            viewBinding.tvTeacherAppraisal.setText("课程结束之后老师会对您的学习进行点评喔～");
        }

        if (commentBean != null && !TextUtils.isEmpty(commentBean.studentReplied)) {
            //学生已评价 tv_stu_comment
            //评分星级
            viewBinding.ratingBarForStudent.setVisibility(View.VISIBLE);
            viewBinding.ratingBarForStudent.setRating(commentBean.score);
            viewBinding.tvStuComment.setGravity(Gravity.LEFT | Gravity.TOP);
            viewBinding.tvStuComment.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_333333));
            viewBinding.tvStuComment.setText(commentBean.studentReplied);

        } else {
            //学员未评价
            viewBinding.ratingBarForStudent.setVisibility(View.GONE);
            viewBinding.tvStuComment.setGravity(Gravity.CENTER);
            viewBinding.tvStuComment.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_999999));
            viewBinding.tvStuComment.setText("课程结束之后记得对老师的教学进行评价哦！");
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == CHOOSE_VIDEO) {
                showLoading();
                Uri uri = data.getData();
                String v_path = FileUtils.getFilePathForN(uri, PracticeCourseDetailActivity.this);
                presenter.upLoadVideo(PracticeCourseDetailActivity.this, v_path);
            }
        }
    }

    @Override
    public void upLoadVideoSuccess(String url) {
        listData.add(listData.size() - 1, new PracticeVideoWorkBean(url, 0));
        if (null != practiceVideoWorkAdapter) {
            practiceVideoWorkAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void submitSparringCourseHomeworkSuccess() {
        //提交成功
        if (isFinishing() || isDestroyed()) {
            return;
        }
        refresh();
    }


}
