package com.cooleshow.student.ui.work;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.ui.activity.BaseMVPActivity;
import com.cooleshow.base.ui.video.VideoPlayActivity;
import com.cooleshow.base.utils.ActivityUtils;
import com.cooleshow.base.utils.FileUtils;
import com.cooleshow.base.utils.GlideUtils;
import com.cooleshow.base.utils.SizeUtils;
import com.cooleshow.base.utils.ToastUtil;
import com.cooleshow.base.utils.UiUtils;
import com.cooleshow.base.utils.helper.QMUIStatusBarHelper;
import com.cooleshow.base.widgets.VideoThumbnailView;
import com.cooleshow.student.R;
import com.cooleshow.student.adapter.PracticeVideoWorkAdapter;
import com.cooleshow.student.bean.HomeworkDetailBean;
import com.cooleshow.student.bean.PianoRoomCourseHomeworkBean;
import com.cooleshow.student.bean.PracticeVideoWorkBean;
import com.cooleshow.student.constants.CourseConstants;
import com.cooleshow.student.contract.HomeWorkDetailContract;
import com.cooleshow.student.databinding.ActivityHomeworkDetailLayoutBinding;
import com.cooleshow.student.presenter.homework.HomeWorkADetailPresenter;
import com.cooleshow.student.ui.course.PianoRoomCourseDetailActivity;
import com.cooleshow.student.ui.course.PracticeCourseDetailActivity;
import com.tbruyelle.rxpermissions3.RxPermissions;

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

import androidx.annotation.NonNull;
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;

/**
 * Author by pq, Date on 2022/7/6.
 * 学生端作业详情页面(包括琴房课,陪练课)
 */
@Route(path = RouterPath.WorkCenter.STUDENT_HOMEWORK_DETAIL)
public class HomeWorkDetailActivity extends BaseMVPActivity<ActivityHomeworkDetailLayoutBinding, HomeWorkADetailPresenter> implements HomeWorkDetailContract.HomeWorkDetailView, View.OnClickListener {
    public static final String COURSE_ID_KEY = "course_id";
    private final int CHOOSE_VIDEO = 1002;
    private String courseId;
    private HomeworkDetailBean mInfoBean;
    private List<PracticeVideoWorkBean> homeworkVideoData = new ArrayList<>();
    private PracticeVideoWorkAdapter mVideoWorkAdapter;
    private boolean teacherIsReply = false;//老师是否已点评
    private boolean isChangeHomeWork = false;//是否变更过作业

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        QMUIStatusBarHelper.setStatusBarLightMode(this);
    }

    @Override
    protected void initView() {
        courseId = getIntent().getStringExtra(COURSE_ID_KEY);
        if (TextUtils.isEmpty(courseId)) {
            finish();
            return;
        }
        initMidTitleToolBar(viewBinding.toolbarInclude.toolbar, "作业详情");
        viewBinding.tvCommit.setOnClickListener(this);
        viewBinding.ivGoChat.setOnClickListener(this);
    }

    @Override
    public void initData() {
        super.initData();
        mVideoWorkAdapter = new PracticeVideoWorkAdapter(homeworkVideoData);
        homeworkVideoData.add(PracticeVideoWorkBean.defaultInstance());
        viewBinding.rvVideo.setLayoutManager(new GridLayoutManager(this, 3));
        viewBinding.rvVideo.setAdapter(mVideoWorkAdapter);
        mVideoWorkAdapter.setItemAddClickAction(new PracticeVideoWorkAdapter.ItemAddClickAction() {
            @Override
            public void add() {
                if (UiUtils.isFastClick()) {
                    return;
                }
                isChangeHomeWork = true;
                getVideoPermission();
            }

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

            @Override
            public void delVideo(int pos) {
                isChangeHomeWork = true;
                if (mVideoWorkAdapter != null && pos < homeworkVideoData.size()) {
                    homeworkVideoData.remove(pos);
                    checkVideoList();
                    mVideoWorkAdapter.notifyDataSetChanged();
                }
            }
        });
        refresh();
    }

    private void checkVideoList() {
        if (homeworkVideoData.size() < CourseConstants.COURSE_HOMEWORK_MAX_VIDEO_COUNT) {
            if (!teacherIsReply && !checkAddItemExist()) {
                //老师未点评的情况下才添加add按钮
                homeworkVideoData.add(PracticeVideoWorkBean.defaultInstance());
            }
        }
    }

    private boolean checkAddItemExist() {
        for (int i = 0; i < homeworkVideoData.size(); i++) {
            PracticeVideoWorkBean videoWorkBean = homeworkVideoData.get(i);
            if (videoWorkBean.type == 1) {
                return true;
            }
        }
        return false;
    }

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

    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);

    }

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

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

    @Override
    public void getDetailInfoSuccess(HomeworkDetailBean infoBean) {
        if (isFinishing() || isDestroyed()) {
            return;
        }
        this.mInfoBean = infoBean;
        //时间
        viewBinding.tvCourseTime.setText(UiUtils.getCourseTimeString(infoBean.startTime, infoBean.endTime));
        //学生头像
        if (TextUtils.equals(infoBean.courseType, CourseConstants.OTHER_COURSE)) {
            GlideUtils.INSTANCE.loadImage(this, infoBean.teacherAvatar, viewBinding.ivAvatar, R.drawable.icon_teacher_default_head);
            //title
            viewBinding.tvTitle.setText(infoBean.teacherName);
        } else {
            viewBinding.ivAvatar.setImageResource(R.drawable.icon_piano_room_course);
            //title
            viewBinding.tvTitle.setText(infoBean.courseGroupName);
        }

        //subjectName
        viewBinding.tvCourseName.setText(infoBean.subjectName);

        String status = infoBean.courseStatus;
        if (TextUtils.equals(CourseConstants.COURSE_STATUS_NOT_START, status)) {
            //课程未开始
            viewBinding.tvCourseStatus.setText(getString(R.string.course_not_start_str));
            viewBinding.tvCourseStatus.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_ff802c));
        }
        if (TextUtils.equals(CourseConstants.COURSE_STATUS_ING, status)) {
            //课程进行中
            viewBinding.tvCourseStatus.setText(R.string.course_ing_str);
            viewBinding.tvCourseStatus.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_2dc7aa));
        }
        if (TextUtils.equals(CourseConstants.COURSE_STATUS_COMPLETE, status)) {
            //课程已结束
            viewBinding.tvCourseStatus.setText(R.string.course_is_completed);
            viewBinding.tvCourseStatus.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_999999));
        }
        //课后作业
        handleHomeworkData(infoBean);
        //作业点评
        handleHomeworkComment(infoBean);
        //作业视频
        handleHomeworkStudentSubmit(infoBean);
    }

    @Override
    public void upLoadVideoSuccess(String url) {
        if (!checkActivityExist()) {
            return;
        }
        if (mVideoWorkAdapter != null) {
            addVideoData(PracticeVideoWorkBean.createNormalInstance(url));
            mVideoWorkAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void submitCourseHomeworkSuccess() {
        if (!checkActivityExist()) {
            return;
        }
        isChangeHomeWork = false;
        ToastUtil.getInstance().showShort("提交成功");
        refresh();
    }

    private void refresh() {
        if (presenter != null) {
            presenter.queryHomeworkDetail(courseId);
        }
    }

    private void addVideoData(PracticeVideoWorkBean videoWorkBean) {
        if (homeworkVideoData.size() < CourseConstants.COURSE_HOMEWORK_MAX_VIDEO_COUNT) {
            homeworkVideoData.add(homeworkVideoData.size() - 1, videoWorkBean);
        } else {
            homeworkVideoData.set(homeworkVideoData.size() - 1, videoWorkBean);
        }
    }


    /**
     * 学生提交的作业
     *
     * @param bean
     */
    private void handleHomeworkStudentSubmit(HomeworkDetailBean bean) {
        if (bean == null) {
            return;
        }
        homeworkVideoData.clear();
        if (bean.submitHomework == CourseConstants.COURSE_HOMEWORK_STU_SUBMIT) {
            viewBinding.csTeacherReply.setVisibility(View.VISIBLE);
            if (bean.homeworkExpire == CourseConstants.COURSE_HOMEWORK_NO_EXPIRED) {
                //未过期
                //学员已提交课后作业
                addVideoThumbnailView(bean.studentAttachments);
                viewBinding.viewHomeworkVideoContentBg.setVisibility(View.GONE);
            } else {
                //作业视频已过期
                viewBinding.viewHomeworkVideoContentBg.setVisibility(View.VISIBLE);
                viewBinding.tvHomeworkVideoEmptyText.setVisibility(View.VISIBLE);
                viewBinding.tvHomeworkVideoEmptyText.setText("作业已过期无法提交和查看！");
            }
        } else {
            //学员未提交课后作业
            homeworkVideoData.add(PracticeVideoWorkBean.defaultInstance());
            viewBinding.csTeacherReply.setVisibility(View.GONE);
        }
        if (mVideoWorkAdapter != null) {
            mVideoWorkAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 添加视频缩略图
     *
     * @param videoUrls
     */
    private void addVideoThumbnailView(String videoUrls) {
        try {
            if (!TextUtils.isEmpty(videoUrls)) {
                String[] results = TextUtils.split(videoUrls, ",");
                for (int i = 0; i < results.length; i++) {
                    String videoPath = results[i];
                    PracticeVideoWorkBean videoWorkBean = new PracticeVideoWorkBean(videoPath, 0);
                    if (teacherIsReply) {
                        videoWorkBean.status = 1;//不可删除
                    }
                    homeworkVideoData.add(videoWorkBean);
                }
                checkVideoList();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 课后作业
     */
    private void handleHomeworkData(HomeworkDetailBean bean) {
        if (bean == null) {
            return;
        }
        if (bean.decorateHomework == CourseConstants.COURSE_HOMEWORK_SET) {
            //已布置课后作业
            viewBinding.tvHomeworkEmptyText.setVisibility(View.GONE);
            viewBinding.tvHomeworkContent.setVisibility(View.VISIBLE);
            viewBinding.tvHomeworkContent.setText(bean.content);
            viewBinding.tvSetHomework.setVisibility(View.GONE);
        } else {
            //未布置课后作业
            viewBinding.tvHomeworkEmptyText.setVisibility(View.VISIBLE);
            viewBinding.tvHomeworkContent.setVisibility(View.GONE);
            viewBinding.tvSetHomework.setVisibility(View.GONE);
        }
    }


    /**
     * 作业点评
     */
    private void handleHomeworkComment(HomeworkDetailBean bean) {
        //tv_homework_comment_content
        if (bean == null) {
            return;
        }
        teacherIsReply = !TextUtils.isEmpty(bean.teacherReplied);
        if (teacherIsReply) {
            //老师已点评作业
            viewBinding.tvCommit.setClickable(false);
            viewBinding.tvCommit.setEnabled(false);
            viewBinding.tvHomeworkCommentEmptyText.setVisibility(View.GONE);
            viewBinding.tvHomeworkSetComment.setVisibility(View.GONE);
            viewBinding.tvHomeworkCommentContent.setVisibility(View.VISIBLE);
            viewBinding.tvHomeworkCommentContent.setText(bean.teacherReplied);
        } else {
            viewBinding.tvCommit.setClickable(true);
            viewBinding.tvCommit.setEnabled(true);
            viewBinding.tvHomeworkCommentEmptyText.setVisibility(View.VISIBLE);
            viewBinding.tvHomeworkSetComment.setVisibility(View.GONE);
            viewBinding.tvHomeworkCommentContent.setVisibility(View.GONE);
        }
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_commit) {
            if (UiUtils.isFastClick()) {
                return;
            }
            //提交
            if (!isChangeHomeWork) {
                ToastUtil.getInstance().showShort("请选择视频文件");
                return;
            }
            String result = getVideoHomeworkResult();
            if (!TextUtils.isEmpty(result)) {
                presenter.submitCourseHomework(result, courseId);
            } else {
                ToastUtil.getInstance().showShort("请选择视频文件");
            }
        }

        if (id == R.id.iv_go_chat) {
            if (mInfoBean == null) {
                return;
            }
            if (TextUtils.equals(mInfoBean.courseType, CourseConstants.OTHER_COURSE)) {
                //陪练课
                OpenChatHelper.goChat(HomeWorkDetailActivity.this, mInfoBean.teacherId, mInfoBean.teacherName);
            } else {
                //琴房课或者直播课
                OpenChatHelper.goGroupChat(HomeWorkDetailActivity.this, mInfoBean.imGroupId, "");
            }
        }
    }

    private String getVideoHomeworkResult() {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < homeworkVideoData.size(); i++) {
            PracticeVideoWorkBean videoWorkBean = homeworkVideoData.get(i);
            if (!TextUtils.isEmpty(videoWorkBean.videoUrl)) {
                if (i != 0) {
                    stringBuilder.append(",");
                }
                stringBuilder.append(videoWorkBean.videoUrl);
            }
        }
        return stringBuilder.toString();
    }

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

}
