package com.wd.workoffice.ui.activity.mes.work;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.wd.workoffice.R;
import com.wd.workoffice.app.BaseMesBean;
import com.wd.workoffice.app.Config;
import com.wd.workoffice.app.WorkBaseFg;
import com.wd.workoffice.bean.event.AddTaskEvent;
import com.wd.workoffice.bean.mesBean.TaskMaterials;
import com.wd.workoffice.bean.mesBean.TaskPeopleBean;
import com.wd.workoffice.bean.mesBean.WorkTaskBean;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.adapter.WorkTaskMaterialsAdapter;
import com.wd.workoffice.ui.adapter.WorkTaskPeopleAdapter;
import com.wd.workoffice.util.DialogUtils;
import com.wd.workoffice.util.WorkUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

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

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import flexible.xd.android_base.network.rtfhttp.Transformer;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;

/**
 * 物料
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class WorkTaskMaterialsFragment extends WorkBaseFg {
    @BindView(R.id.rv_data)
    RecyclerView rvData;
    @BindView(R.id.tv_add)
    TextView tvAdd;
    private List<TaskMaterials.ListBean> taskList;
    private WorkTaskMaterialsAdapter taskAdapter;
    private WorkTaskBean.ListBean info;
    private int taskPage = 1;
    private Map<String, Object> taskParam;
    private Map<String, Object> taskParamMap;
    private String plan;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arguments = getArguments();
        if (arguments != null) {
            info = JSON.parseObject(arguments.getString("info"), WorkTaskBean.ListBean.class);
            plan = arguments.getString("plan");
        }
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this, getContentView());
        rvData.setLayoutManager(new LinearLayoutManager(getActivity(), RecyclerView.VERTICAL, false));
    }


    @Override
    protected void initData() {
        taskList = new ArrayList<>();
        taskAdapter = new WorkTaskMaterialsAdapter(R.layout.item_work_task_materials, taskList);
        taskAdapter.setEmptyView(R.layout.view_empty_content, rvData);
        taskAdapter.bindToRecyclerView(rvData);

        taskParam = WorkUtils.pageMesKey();
        taskParam.put("pageNum", 1);
        taskParamMap = WorkUtils.simpleParam();
        taskParam.put("paramMap", taskParamMap);
        taskParamMap.put("woId", info.getWoId());
        taskParamMap.put("actId", info.getId());
        getTask();
    }



    private void getTask() {
        Observable<BaseMesBean> baseMesBeanObservable =
                TextUtils.equals("1",plan)?
                        RtfUtils.getMesRtf().pagePlanMaterial("1", WorkUtils.convertMapToBody(taskParam))
        :RtfUtils.getMesRtf().pageMaterial("1", WorkUtils.convertMapToBody(taskParam));
        baseMesBeanObservable.compose(Transformer.schedule()).subscribe(new WorkObserver<BaseMesBean>() {
            @Override
            public void doOnSubscribe(Disposable d) {
            }

            @Override
            public void onFail(String errorMsg) {
                hideLoading();
                toast(errorMsg);
            }

            @Override
            public void onSuccess(BaseMesBean data) {
                hideLoading();
                if (!data.isSuccess()) {
                    toast(data.getMessage());
                    return;
                }
                List<TaskMaterials.ListBean> getList = JSON.parseObject(data.getData().toString(), TaskMaterials.class).getList();

                if (taskPage == 1) {
                    taskList.clear();
                    taskList.addAll(getList);
                    taskAdapter.notifyDataSetChanged();
                    taskAdapter.loadMoreComplete();
                } else {
                    taskAdapter.loadMoreComplete();
                    taskList.addAll(getList);
                    taskAdapter.notifyDataSetChanged();
                }
                if (getList.size() == 0||getList.size()< Config.SIZE) {
                    taskAdapter.loadMoreEnd(true);
                } else {
                    taskPage++;
                }
            }
        });

    }

    @Override
    protected void initEvent() {
        taskAdapter.setOnLoadMoreListener(() -> {
            taskParam.put("pageNum", taskPage);
            getTask();
        }, rvData);
        taskAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.tv_delete:
                        QMUIDialog.MessageDialogBuilder dialog = DialogUtils.okAndCancelDialog(getActivity());
                        dialog.setMessage("此操作将永久删除该条信息, 是否继续?").addAction("取消", new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                dialog.dismiss();
                            }
                        }).addAction("确定", new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                dialog.dismiss();
                                delete(taskList.get(position).getId());
                            }
                        }).show();
                        break;
                    case R.id.tv_edit:
                        startActivity(WorkTaskMaterialsActivity.class, "id", info.getId(),
                                "data", JSON.toJSONString(taskList.get(position))
                                , "info", JSON.toJSONString(info));
                        break;
                }
            }
        });
    }


    @Override
    protected int layoutId() {
        return R.layout.activity_work_people;
    }
    @OnClick(R.id.tv_add)
    public void onClick() {
        startActivity(WorkTaskMaterialsActivity.class, "info", JSON.toJSONString(info));
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void refresh(AddTaskEvent event) {
        taskPage = 1;
        taskParam.put("pageNum", 1);
        getTask();
    }
    private void delete(String id) {
        RtfUtils.getMesRtf().deletePlanMaterial(id, "aa8faf47c93311e98334fa163e1166bd"
        ).compose(Transformer.schedule()).subscribe(new WorkObserver<BaseMesBean>() {
            @Override
            public void doOnSubscribe(Disposable d) {
            }

            @Override
            public void onFail(String errorMsg) {
                hideLoading();
                toast(errorMsg);
            }

            @Override
            public void onSuccess(BaseMesBean data) {
                hideLoading();
                if (!data.isSuccess()) {
                    toast(data.getMessage());
                    return;
                }
                taskPage = 1;
                taskParam.put("pageNum", 1);
                getTask();
                toast("删除成功");
            }
        });
    }

}
