package com.beanpodtech.allinone.activity;

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aliyun.svideo.common.utils.ToastUtils;
import com.beanpodtech.allinone.R;
import com.beanpodtech.allinone.adapter.RecordVideoAdapter;
import com.beanpodtech.allinone.bean.BaseRequestBean;
import com.beanpodtech.allinone.bean.RecordVideoBean;
import com.beanpodtech.allinone.http.UrlConfig;
import com.beanpodtech.allinone.utils.Contants;
import com.beanpodtech.allinone.utils.HttpUtils;
import com.beanpodtech.allinone.utils.OkGoBuilder;
import com.beanpodtech.allinone.utils.OkGoUtil;
import com.beanpodtech.allinone.utils.SpUtil;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.lzy.okgo.model.Response;

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

public class RecordActivity extends BaseActivity {

    private static final String KEYWORD = "keyWord";
    /**
     * 删除选中
     */
    private static final int TYPE_DELETE_SELECT = 2;
    /**
     * 删除全部
     */
    private static final int TYPE_DELETE_ALL = 1;
    private ImageView ivBack;
    private TextView tvTitle;
    private List<RecordVideoBean.ListBean> listRecommend = new ArrayList<>();
    private RecordVideoAdapter recommendVideoAdapter;
    private String userId;
    private XRecyclerView idRecyclerview;
    private TextView tvDelete;
    private LinearLayout llCommit;
    private TextView tvSave;
    private TextView tvDeleteall;

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, RecordActivity.class);
        context.startActivity(intent);
    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_delete:
                showDeleteMenu();
                recommendVideoAdapter.setIsDelete(true);
                break;
            case R.id.tv_save:
                dealDeleteData();
                break;
            case R.id.tv_deleteall:
                showDeleteDialog(TYPE_DELETE_ALL, "");
                break;
        }
    }

    /**
     * 删除全部记录
     */
    private void deleteAllVideo() {
        OkGoBuilder.getInstance().url(UrlConfig.DELETEALLRECORD).Builder(this).requestBody(HttpUtils.getRequestJson(initAllMap())).cls(BaseRequestBean.class).method(OkGoBuilder.PSOT).callback(new OkGoUtil<BaseRequestBean>(BaseRequestBean.class) {
            @Override
            public void onSuccess(Response<BaseRequestBean> response) {
                BaseRequestBean body = response.body();
                if (body != null) {
                    if (body.getStatus() == 0) {
                        ToastUtils.show(mContext, getResources().getString(R.string.delete_success));
                        showDeleteMenu();
                        recommendVideoAdapter.setIsDelete(false);
                        listRecommend.clear();
                        recommendVideoAdapter.notifyDataSetChanged();
                    } else {
                        ToastUtils.show(mContext, getResources().getString(R.string.delete_fail));
                    }
                }
            }
        }).build();
    }

    private HashMap<String, String> initAllMap() {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", SpUtil.getInstace().getString(Contants.USER_ID, null));
        return map;
    }

    /**
     * 处理选中的数据
     */
    private void dealDeleteData() {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < listRecommend.size(); i++) {
            if (listRecommend.get(i).isCheck()) {
                stringBuilder.append(listRecommend.get(i).getId()).append(",");
            }
        }
        if (stringBuilder.length() == 0) {
            ToastUtils.show(mContext, getResources().getString(R.string.select_delete_item));
            recommendVideoAdapter.setIsDelete(false);
            showDeleteMenu();
            return;
        }
        String substring = stringBuilder.toString().substring(0, stringBuilder.toString().length() - 1);
        showDeleteDialog(TYPE_DELETE_SELECT, substring);

    }

    /**
     * 整理数据并删除学习记录
     */
    private void deleteVideo(String substring) {

        OkGoBuilder.getInstance().url(UrlConfig.DELETERECORD).Builder(this).requestBody(HttpUtils.getRequestJson(initMap(substring))).cls(BaseRequestBean.class).method(OkGoBuilder.PSOT).callback(new OkGoUtil<BaseRequestBean>(BaseRequestBean.class) {
            @Override
            public void onSuccess(Response<BaseRequestBean> response) {
                BaseRequestBean body = response.body();
                if (body != null) {
                    if (body.getStatus() == 0) {
                        ToastUtils.show(mContext, getResources().getString(R.string.delete_success));
                        showDeleteMenu();
                        recommendVideoAdapter.setIsDelete(false);
                        getRecommendVideo();
                    } else {
                        ToastUtils.show(mContext, getResources().getString(R.string.delete_fail));
                    }
                }
            }
        }).build();

    }

    /**
     * @param deleteRecords 选中的要删除的记录的id  用,隔开
     * @return
     */
    private HashMap<String, String> initMap(String deleteRecords) {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", SpUtil.getInstace().getString(Contants.USER_ID, null));
        map.put("recordIds", deleteRecords);
        return map;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_record;
    }

    @Override
    public void initView(View view) {
        ivBack = findViewById(R.id.iv_back);
        tvTitle = findViewById(R.id.tv_title);
        tvDelete = findViewById(R.id.tv_delete);
        llCommit = findViewById(R.id.ll_commit);
        tvSave = findViewById(R.id.tv_save);
        tvDeleteall = findViewById(R.id.tv_deleteall);
        tvDelete.setVisibility(View.VISIBLE);
        tvTitle.setText(getResources().getString(R.string.record));
        idRecyclerview = findViewById(R.id.id_recyclerview);
        idRecyclerview.setPullRefreshEnabled(false);
        idRecyclerview.setLayoutManager(new GridLayoutManager(this, 5));
        idRecyclerview.setItemAnimator(new DefaultItemAnimator());
        recommendVideoAdapter = new RecordVideoAdapter(listRecommend, mContext);
        View inflate = getLayoutInflater().inflate(R.layout.course_record, null);
        idRecyclerview.setAdapter(recommendVideoAdapter);
    }

    @Override
    public void initListener() {
        ivBack.setOnClickListener(this);
        tvDelete.setOnClickListener(this);
        tvSave.setOnClickListener(this);
        tvDeleteall.setOnClickListener(this);
        idRecyclerview.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {

            }

            @Override
            public void onLoadMore() {
//                if (page == totalPages) {
//                    Toast.makeText(mContext, "无更多数据", Toast.LENGTH_SHORT).show();
                resetRecycleViewState();

//                } else {
//                    page++;
//                    getRecommendVideo();
//                }

            }
        });
    }

    /**
     * 重置RecycleView 刷新状态
     */
    private void resetRecycleViewState() {
        idRecyclerview.refreshComplete();
        idRecyclerview.loadMoreComplete();
    }

    /**
     * 获取学习记录
     */
    private void getRecommendVideo() {
        OkGoBuilder.getInstance().url(UrlConfig.STUDYRECORD).Builder(this).requestBody(HttpUtils.getRequestJson(initRequestJson(userId/*, keyWord, page + "", number + ""*/))).cls(RecordVideoBean.class).method(OkGoBuilder.PSOT).callback(new OkGoUtil<RecordVideoBean>(RecordVideoBean.class) {
            @Override
            public void onSuccess(Response<RecordVideoBean> response) {
                if (response.body() != null && response.body().getList() != null) {
                    if (response.body() instanceof RecordVideoBean) {
                        RecordVideoBean body = response.body();

                        List<RecordVideoBean.ListBean> list = body.getList();
                        listRecommend.clear();
                        listRecommend.addAll(list);
                        recommendVideoAdapter.notifyDataSetChanged();
                        resetRecycleViewState();
                    }
                }/* else {
                    ToastUtils.show(mContext, "网络请求异常");
                }*/

//                progressDialog.dismiss();

            }

            @Override
            public void onError(Response<RecordVideoBean> response) {
                super.onError(response);
            }

            @Override
            public void onFinish() {
                super.onFinish();

            }
        }).build();
    }

    /**
     * @param userId 用户Id
     * @return 返回处理好的请求requestBody
     */
    private HashMap<String, String> initRequestJson(String userId/*, String keyWord, String page, String number*/) {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", userId);
        return map;
    }

    @Override
    public void initData(Context mContext) {
        userId = SpUtil.getInstace().getString(Contants.USER_ID, null);
//        keyWord = getIntent().getStringExtra(KEYWORD);
        getRecommendVideo();
    }

    /**
     * 右上角是否显示保存编辑和全部删除
     */
    private void showDeleteMenu() {
        if (tvDelete.getVisibility() == View.VISIBLE) {
            tvDelete.setVisibility(View.GONE);
            llCommit.setVisibility(View.VISIBLE);
        } else {
            tvDelete.setVisibility(View.VISIBLE);
            llCommit.setVisibility(View.GONE);
        }
    }

    /**
     * @param type 1 删除全部记录  2删除选中记录
     */
    private void showDeleteDialog(final int type, final String subString) {
        String title = null;
        if (type == 1) {
            title = getResources().getString(R.string.makesure_deleteall);
        } else {
            title = getResources().getString(R.string.makesure_delete_selete);
        }
        AlertDialog alertDialog = new AlertDialog.Builder(mContext)
                .setTitle(getResources().getString(R.string.tip))
                .setMessage(title)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {//添加"Yes"按钮
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (type == 1) {
                            deleteAllVideo();
                        } else {
                            deleteVideo(subString);
                        }
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {//添加取消
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                })
                .create();
        alertDialog.show();
    }
}
