package com.wisewoods.eduandroid.ui;

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

import androidx.annotation.NonNull;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.TimeUtils;
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.ScheduleInfo;
import com.wisewoods.base.net.JCallback;
import com.wisewoods.base.page.BaseListActivity;
import com.wisewoods.base.utils.$;
import com.wisewoods.eduandroid.R;
import com.wisewoods.eduandroid.app.App;
import com.wisewoods.eduandroid.databinding.ActivityTeacherScheduleBinding;
import com.wisewoods.eduandroid.ui.adapter.ScheduleAdapter;

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

import java.util.Calendar;

import retrofit2.Call;
import retrofit2.Response;

public class TeacherScheduleActivity extends BaseListActivity<ActivityTeacherScheduleBinding>
        implements OnItemChildClickListener {

    private int type;
    private ScheduleAdapter scheduleAdapter;

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

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

    public static void start(String title, int type) {
        Intent intent = new Intent(ActivityUtils.getTopActivity(), TeacherScheduleActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("type", type);
        ActivityUtils.startActivity(intent);
    }

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

        type = getIntent().getIntExtra("type", 0);
        String title = getIntent().getStringExtra("title");
        if (TextUtils.isEmpty(title)) {
            title = "课程状态";
        }
        showBarBack(binding.bar.tvTitle, title, binding.bar.ivBack);

        binding.tvTime.setOnClickListener(v -> selectTime());
        binding.tvReset.setOnClickListener(v -> {
            binding.tvTime.setText("全部");
            onRefresh();
        });

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

    private void selectTime() {
        Calendar startDate = Calendar.getInstance();
        startDate.add(Calendar.HOUR, 0);
        startDate.add(Calendar.MINUTE, 0);
        startDate.add(Calendar.SECOND, 0);
        startDate.add(Calendar.MILLISECOND, 0);

        TimePickerView pvTime = new TimePickerBuilder(this, (date, v12) -> {//选中事件回调
            binding.tvTime.setText(TimeUtils.date2String(date, "yyyy-MM-dd"));
            onRefresh();
        })
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setDate(startDate)//起始终止年月日设定
                .build();
        pvTime.show();
    }

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

    @Override
    protected void getData(long page, long size) {
        String time = binding.tvTime.getText().toString().trim();
        if ("全部".equals(time)) {
            time = "";
        }
        if (type == 0) {
            App.api.getTeacherScheduleList("2", time, 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();
                        }

                    });
        } else {
            App.api.getTeacherHistoryScheduleList("2", time, 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_detail:
                CourseActivity.start(scheduleAdapter.getItem(position).scheduleId + "");
                break;
            case R.id.tv_student:
                StudentActivity.start(scheduleAdapter.getItem(position).teamId + "", false);
                break;
            case R.id.tv_go_live:
                goLive(scheduleAdapter.getItem(position));
                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();
            }
        });
    }


}
