package com.wisewoods.eduandroid.ui;

import android.content.Intent;
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.GsonUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.wisewoods.base.bean.BaseEvent;
import com.wisewoods.base.bean.MsgCount;
import com.wisewoods.base.bean.Results;
import com.wisewoods.base.bean.TaskList;
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.ActivityTaskBinding;
import com.wisewoods.eduandroid.ui.adapter.TaskAdapter;

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

import java.util.Calendar;
import java.util.HashMap;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Response;

public class TaskActivity extends BaseListActivity<ActivityTaskBinding>
        implements OnItemChildClickListener {


    private TaskAdapter mAdapter;
    private int state;

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

    //0 是 待办   1 是 完成
    public static void start(String title, int state) {
        Intent intent = new Intent(ActivityUtils.getTopActivity(), TaskActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("state", state);
        ActivityUtils.startActivity(intent);
    }

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

        String title = getIntent().getStringExtra("title");
        state = getIntent().getIntExtra("state", 0);
        showBarBack(binding.bar.tvTitle, title, binding.bar.ivBack);

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

        mAdapter = new TaskAdapter(state);
        mAdapter.setOnItemChildClickListener(this);
        getNumData();
    }

    @Override
    public void onRefresh() {
        super.onRefresh();
        getNumData();
    }

    private void getNumData() {
        App.api.queryMessageCount().enqueue(new JCallback<MsgCount>() {
            @Override
            public void onS(Response<MsgCount> response, MsgCount msgCount) {
                binding.tvTotal.setText(msgCount.data.allTask + "");
            }
        });
    }

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

    @Override
    protected void getData(long page, long size) {
        String time = binding.tvTime.getText().toString().trim();
        if ("全部".equals(time)) {
            time = "";
        }
        if (state == 0) {
            binding.llTotal.setVisibility(View.VISIBLE);
            App.api.queryAppAgencyTasks(time, time, page, size)
                    .enqueue(new JCallback<TaskList>() {
                        @Override
                        public void onS(Response<TaskList> response, TaskList taskList) {
                            getDataSuccess(taskList.data.rows, taskList.data.total);
                        }

                        @Override
                        public void onFailure(Call<TaskList> call, Throwable t) {
                            super.onFailure(call, t);
                            getDataFail();
                        }
                    });
        } else {
            binding.llTotal.setVisibility(View.GONE);
            App.api.queryCompleteTasks(time, time, page, size)
                    .enqueue(new JCallback<TaskList>() {
                        @Override
                        public void onS(Response<TaskList> response, TaskList taskList) {
                            getDataSuccess(taskList.data.rows, taskList.data.total);
                        }

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

    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
    protected boolean hasEvent() {
        return true;
    }

    @Override
    public void onItemChildClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
        if (view.getId() == R.id.tv_car_put) {
            TaskList.TaskBean item = mAdapter.getItem(position);
            CarPlanActivity.start(item.id + "", 0, item.taskContent);
        } else if (view.getId() == R.id.tv_complete) {
            DialogUtils.showCommon(
                    "确认当前待办已经完成？", (DialogUtils.IDialogOnOKListener) dialog -> {
                        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
                        HashMap<String, String> map = new HashMap<>();
                        map.put("id", mAdapter.getItem(position).id + "");
                        map.put("taskStatus", "3");
                        RequestBody body = RequestBody.create(GsonUtils.toJson(map), JSON);

                        App.api.handleTask(body).enqueue(new JDCallback<Results>() {
                            @Override
                            public void onS(Response<Results> response, Results results) {
                                $.toast("提交成功");
                                onRefresh();
                            }
                        });
                    });

        } else if (view.getId() == R.id.tv_plan) {
            TaskList.TaskBean item = mAdapter.getItem(position);
            CarPlanActivity.start(item.id + "", 1, item.taskContent);
        }
    }
}
