package com.stu.assistant.activity;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;

import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.stu.assistant.R;
import com.stu.assistant.adapter.TableListAdapter;
import com.stu.assistant.base.BaseActivity;
import com.stu.assistant.base.BaseApplion;
import com.stu.assistant.bean.AllTableListBean;
import com.stu.assistant.bean.TableBean;
import com.stu.assistant.constants.ConstansTableItemManager;
import com.stu.assistant.uitls.CalendarUtil;
import com.stu.assistant.uitls.DividerItemDecoration0Util;
import com.stu.assistant.uitls.LogUtils;
import com.stu.assistant.uitls.MyToast;
import com.stu.assistant.uitls.SharedConfig;
import com.stu.assistant.uitls.SharedNoClearUtil;
import com.stu.assistant.uitls.SharedUtil;
import com.stu.assistant.view.MySwipeRefreshLayout;

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

//添加课程表的页面
public class AddTableActivity extends BaseActivity {
    private RecyclerView mrv;
    private TableListAdapter adapter;
    private MySwipeRefreshLayout swip;
    private Handler handler;
    private ArrayList<TableBean> mList1;
    private ArrayList<TableBean> mList2;
    private ArrayList<TableBean> mList3;
    private ArrayList<TableBean> mList4;
    private ArrayList<TableBean> mList5;
    private TextView okBtn;
    private AllTableListBean bean;
    private int index = -1;//是否存在课程表id 的下标
    private LinearLayout backLay, lay;
    private TextView titleTv;
    private String tableIdMsg;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_table;
    }

    @Override
    protected void initView() {
        Intent intent = getIntent();
        bean = (AllTableListBean) intent.getSerializableExtra("bean");

        swip = findViewById(R.id.swip_rf);
        mrv = findViewById(R.id.mrv);
        okBtn = findViewById(R.id.other_tv);
        titleTv = findViewById(R.id.title_tv);
        backLay = findViewById(R.id.back_lay);
        lay = findViewById(R.id.lay);
        handler = new Handler();

        if (bean == null) {
            titleTv.setText("新建课表");
            tableIdMsg = CalendarUtil.getInstance().getYMDHMSLine();
        } else {
            titleTv.setText("课表详情");
            tableIdMsg = bean.getTableIdMsg();
        }
    }

    @Override
    protected void initData() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mrv.addItemDecoration(new DividerItemDecoration0Util(this, false));
        mrv.setLayoutManager(manager);
        String string = SharedNoClearUtil.create(BaseApplion.application).getString(SharedConfig.isBg, SharedConfig.isBg_1);
        if (string.equals(SharedConfig.isBg_1)) {
            lay.setBackgroundResource(R.mipmap.ic_bg_1);
        }
        if (string.equals(SharedConfig.isBg_2)) {
            lay.setBackgroundResource(R.mipmap.ic_bg_2);
        }
        if (string.equals(SharedConfig.isBg_3)) {
            lay.setBackgroundResource(R.mipmap.ic_bg_3);
        }
        if (string.equals(SharedConfig.isBg_4)) {
            lay.setBackgroundResource(R.mipmap.ic_bg_4);
        }
        getData();
    }

    @Override
    protected void initListener() {
        // 刷新数据
        swip.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // 这里的作用是防止下拉刷新的时候还可以上拉加载
                getData();
            }
        });
        okBtn.setOnClickListener(new View.OnClickListener() {

            private String tableIdMsg;

            @Override
            public void onClick(View view) {
                saveData(2);
            }
        });
        backLay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showBackDialog();
            }
        });
    }

    //保存数据
    private void saveData(int num) {
        ArrayList<TableBean> allList = new ArrayList<>();
        allList.addAll(mList1);
        allList.addAll(mList2);
        allList.addAll(mList3);
        allList.addAll(mList4);
        allList.addAll(mList5);

        for (int i = 0; i < allList.size(); i++) {
            String tableIdMsg = allList.get(i).getTableIdMsg();
            if (!TextUtils.isEmpty(tableIdMsg)) {
                index = i;
                break;
            }
        }

        if (num == 2) {
            if (index == -1) {
                MyToast.show("请添加课程");
                return;
            }
        } else {
            if (index == -1) {
                finish();
                return;
            }
        }

        if (index != -1) {
            String tableIdMsg = allList.get(index).getTableIdMsg();
            showProDialog("正在提交");
            AllTableListBean allTableListBean = new AllTableListBean();
            allTableListBean.setTableIdMsg(tableIdMsg);
            allTableListBean.setStuId(SharedUtil.create(BaseApplion.application).getString(SharedConfig.objectId));
            allTableListBean.save(new SaveListener<String>() {
                @Override
                public void done(String s, BmobException e) {
                    dismissProDialog();
                    if (e == null) {
                        MyToast.show("成功");
                        setResult(12);
                        finish();
                    } else {
                        MyToast.show("失败：" + e.getMessage() + "," + e.getErrorCode());
                    }
                }
            });
        }
    }

    private void getData() {
        getNewData();//初始化课程表数据
        if (bean == null) {//新建
            setAdapter(mList1, mList2, mList3, mList4, mList5);
        } else {//查看详情
            showProDialog("正在查询");
            BmobQuery<TableBean> query = new BmobQuery<>();
            query.addWhereEqualTo("tableIdMsg", bean.getTableIdMsg());
            query.findObjects(new FindListener<TableBean>() {
                @Override
                public void done(List<TableBean> list, BmobException e) {
                    LogUtils.i("list", "-stuId-findObjects-->" + new Gson().toJson(list));
                    dismissProDialog();
                    if (list == null) {
                        MyToast.show("暂无数据");
                    } else {
                        optList(list);
                    }
                }
            });
        }
    }

    //初始化数据
    private void getNewData() {
        mList1 = new ArrayList<>();
        mList2 = new ArrayList<>();
        mList3 = new ArrayList<>();
        mList4 = new ArrayList<>();
        mList5 = new ArrayList<>();

        TableBean tableBean = new TableBean();
        tableBean.setTableNameMsg("");
        tableBean.setTeacherName("");
        tableBean.setAddress("");
        tableBean.setTeacherId("");
        for (int i = 0; i < 8; i++) {
            mList1.add(tableBean);
            mList2.add(tableBean);
            mList3.add(tableBean);
            mList4.add(tableBean);
            mList5.add(tableBean);
        }
    }

    // 拼装成课程表需要的格式
    private void optList(List<TableBean> list) {
        for (int i = 0; i < list.size(); i++) {
            TableBean bean = list.get(i);
            if (bean.getDay() == ConstansTableItemManager.item_1) {
                mList1.set(bean.getPos(), bean);
            }
            if (bean.getDay() == ConstansTableItemManager.item_2) {
                mList2.set(bean.getPos(), bean);
            }
            if (bean.getDay() == ConstansTableItemManager.item_3) {
                mList3.set(bean.getPos(), bean);
            }
            if (bean.getDay() == ConstansTableItemManager.item_4) {
                mList4.set(bean.getPos(), bean);
            }
            if (bean.getDay() == ConstansTableItemManager.item_5) {
                mList5.set(bean.getPos(), bean);
            }
        }

        setAdapter((ArrayList<TableBean>) mList1, (ArrayList<TableBean>) mList2, (ArrayList<TableBean>) mList3, (ArrayList<TableBean>) mList4, (ArrayList<TableBean>) mList5);
    }

    public void setAdapter(ArrayList<TableBean> mList1, ArrayList<TableBean> mList2, ArrayList<TableBean> mList3, ArrayList<TableBean> mList4, ArrayList<TableBean> mList5) {

        if (adapter == null) {
            adapter = new TableListAdapter(this);
            adapter.setList(mList1, mList2, mList3, mList4, mList5);
            mrv.setAdapter(adapter);
            adapter.setOnItemClickListeners(new TableListAdapter.OnItemClickListeners() {
                @Override
                public void itemBean(int pos, TableBean tableBean, int day) {
                    tableBean.setDay(day);
                    tableBean.setPos(pos);
                    Intent intent = new Intent(AddTableActivity.this, AddTableDialogActivity.class);
                    if (bean == null) {//新增 是相对课程表说的
                        intent.putExtra("title", "1");
                    } else {//编辑
                        intent.putExtra("title", "2");
                    }
                    if (TextUtils.isEmpty(tableBean.getTableNameMsg())) {//新增  相当于 item说的
                        intent.putExtra("item", "1");
                    } else {//编辑
                        intent.putExtra("item", "2");
                    }
                    tableBean.setTableIdMsg(tableIdMsg);
                    intent.putExtra("bean", tableBean);
                    startActivityForResult(intent, 202);
                }
            });
        } else {
            adapter.setList(mList1, mList2, mList3, mList4, mList5);
            adapter.notifyDataSetChanged();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    swip.setRefreshing(false);
                }
            }, 1000);
        }
    }


    @Override
    public void onBackPressed() {
        showBackDialog();
    }

    private void showBackDialog() {
        if (bean != null) {
            finish();
            return;
        }
        saveData(1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 202) {
            if (resultCode == 12) {
                TableBean bean = (TableBean) data.getSerializableExtra("bean");
                int day = bean.getDay();
                int pos = bean.getPos();
                if (day == ConstansTableItemManager.item_1) {
                    mList1.set(pos, bean);
                }
                if (day == ConstansTableItemManager.item_2) {
                    mList2.set(pos, bean);
                }
                if (day == ConstansTableItemManager.item_3) {
                    mList3.set(pos, bean);
                }
                if (day == ConstansTableItemManager.item_4) {
                    mList4.set(pos, bean);
                }
                if (day == ConstansTableItemManager.item_5) {
                    mList5.set(pos, bean);
                }
                setAdapter(mList1, mList2, mList3, mList4, mList5);
            }
        }
    }
}