package com.wisewoods.eduandroid.ui;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.Utils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.tencent.liteav.live.model.TRTCMeeting;
import com.wisewoods.base.app.BaseApp;
import com.wisewoods.base.app.UserManager;
import com.wisewoods.base.bean.BaseEvent;
import com.wisewoods.base.bean.IMToken;
import com.wisewoods.base.bean.Results;
import com.wisewoods.base.bean.ScheduleInfo;
import com.wisewoods.base.net.ApiService;
import com.wisewoods.base.net.JCallback;
import com.wisewoods.base.net.JDCallback;
import com.wisewoods.base.page.BaseListActivity;
import com.wisewoods.base.utils.$;
import com.wisewoods.base.utils.DialogUtils;
import com.wisewoods.eduandroid.R;
import com.wisewoods.eduandroid.app.App;
import com.wisewoods.eduandroid.databinding.ActivityScheduleBinding;
import com.wisewoods.eduandroid.ui.adapter.ScheduleAdapter;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import retrofit2.Call;
import retrofit2.Response;


public class ScheduleActivity extends BaseListActivity<ActivityScheduleBinding>
        implements OnItemChildClickListener {

    private String id;
    private String startTime;
    private String endTime;
    private ScheduleAdapter scheduleAdapter;

    public static void start(String id, String startTime, String endTime) {
        Intent intent = new Intent(ActivityUtils.getTopActivity(), ScheduleActivity.class);
        intent.putExtra("id", id);
        intent.putExtra("startTime", startTime);
        intent.putExtra("endTime", endTime);
        ActivityUtils.startActivity(intent);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void liveEvent(BaseEvent.LiveRrefreshEvent event) {
        onRefresh();
    }

    @Override
    protected boolean hasEvent() {
        return true;
    }


    @Override
    protected void initListData() {
        rv = binding.rvSchedule;
        srf = binding.srf;

        id = getIntent().getStringExtra("id");
        startTime = getIntent().getStringExtra("startTime");
        endTime = getIntent().getStringExtra("endTime");
        String title = getIntent().getStringExtra("title");
        if (TextUtils.isEmpty(title)) {
            title = "课程状态";
        }
        showBarBack(binding.bar.tvTitle, title, binding.bar.ivBack);
        binding.ts.setDate(startTime, endTime);

        binding.ts.setTimeListener((timeStrStart, timeStrEnd) -> {
            scheduleAdapter.setNewInstance(null);
            super.onRefresh();
        });


        scheduleAdapter = new ScheduleAdapter();
        scheduleAdapter.setOnItemChildClickListener(this);
    }

    @Override
    public BaseQuickAdapter getAdapter() {
        return scheduleAdapter;
    }

    @Override
    protected void getData(long page, long size) {
        App.api.getScheduleList(id, binding.ts.getTimeStrStart(), page, size)
                .enqueue(new JCallback<ScheduleInfo>() {
                    @Override
                    public void onS(Response<ScheduleInfo> response, ScheduleInfo scheduleInfo) {
                        getDataSuccess(scheduleInfo.data.rows, scheduleInfo.data.total);
                    }

                    @Override
                    public void onFailure(Call<ScheduleInfo> call, Throwable t) {
                        super.onFailure(call, t);
                        getDataFail();
                    }
                });

    }


    @Override
    public void onItemChildClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
        switch (view.getId()) {
            case R.id.tv_course_start:
                DialogUtils.showCommon(
                        "确认" + scheduleAdapter.getItem(position).courseCeremoneyName + "开始上课？",
                        (DialogUtils.IDialogOnOKListener) dialog -> {
                            updateData(scheduleAdapter.getItem(position).scheduleId + "", "1", position);
                        });
                break;
            case R.id.tv_course_end:
                DialogUtils.showCommon(
                        "确认" + scheduleAdapter.getItem(position).courseCeremoneyName + "下课？",
                        (DialogUtils.IDialogOnOKListener) dialog -> {
                            updateData(scheduleAdapter.getItem(position).scheduleId + "", "2", position);
                        });
                break;
            case R.id.tv_course_detail:
                CourseActivity.start(scheduleAdapter.getItem(position).scheduleId + "");
                break;
            case R.id.tv_student:
                StudentActivity.start(scheduleAdapter.getItem(position).scheduleId + "", id);
                break;
            case R.id.tv_go_live:
                goLive(scheduleAdapter.getItem(position));
                break;
            case R.id.tv_download:
                WebActivity.start(ApiService.KEYNOTE_ADDRESS + scheduleAdapter.getItem(position).keynoteId, "主持词详情");
                break;
        }
    }

    private void goLive(ScheduleInfo.DataBean item) {
        showLoading();
        BaseApp.api.genUserSig(UserManager.getEduUid()).enqueue(new JCallback<IMToken>() {
            @Override
            public void onS(Response<IMToken> response, IMToken imToken) {
                BaseApp.SDKAPPID = imToken.data.appID;
                TRTCMeeting.sharedInstance(Utils.getApp())
                        .login(imToken.data.appID, UserManager.getEduUid(), imToken.data.userSig,
                                (code, msg) -> {
                                    hideLoading();
                                    LogUtils.d("code: " + code + " msg:" + msg);
                                    if (code == 0) {
                                        ShowLiveActivity.start(item.scheduleId + "", item.scheduleIdStr + "", item.liveStatus);
                                    } else {
                                        $.toast(msg);
                                    }
                                });
            }

            @Override
            public void onFailure(Call<IMToken> call, Throwable t) {
                super.onFailure(call, t);
                hideLoading();
            }
        });
    }

    private void updateData(String scheduleId, String courseStatus, int position) {
        App.api.updateCourseStartEnd(scheduleId, courseStatus)
                .enqueue(new JDCallback<Results>() {
                    @Override
                    public void onS(Response<Results> response, Results results) {
                        scheduleAdapter.getItem(position).courseStatus = Integer.parseInt(courseStatus);
                        scheduleAdapter.notifyItemChanged(position);
                        $.toast(results.msg);
                    }
                });
    }
}
