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

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
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.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.TaskPeopleBean;
import com.wd.workoffice.bean.mesBean.WokrOrderBean;
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.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.core.widget.NestedScrollView;
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 WorkTaskPeopleFragment extends WorkBaseFg {
    @BindView(R.id.rv_data)
    RecyclerView rvData;
    @BindView(R.id.tv_add)
    TextView tvAdd;
    @BindView(R.id.tv_agree)
    TextView tvAgree;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R.id.srl_refresh)
    NestedScrollView srlRefresh;
    private List<TaskPeopleBean.ListBean> taskList;
    private WorkTaskPeopleAdapter taskAdapter;
    private WorkTaskBean.ListBean info;
    private int taskPage = 1;
    private Map<String, Object> taskParam;
    private Map<String, Object> taskParamMap;
    private String plan;
    private boolean canModify =true;
    private WokrOrderBean.ListBean work;

    @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);
            work = JSON.parseObject(arguments.getString("work"), WokrOrderBean.ListBean.class);
            plan = arguments.getString("plan");
        }
    }

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

    private void changeView() {
        if (TextUtils.equals(plan, "1")) {
            if (!WorkUtils.workCanModify(work.getStatus())) {
                tvAdd.setVisibility(View.GONE);
                tvAgree.setVisibility(View.GONE);
                canModify = false;
            }
        } else {
            if (info.getStatus() != 3) {
                tvAdd.setVisibility(View.GONE);
                tvAgree.setVisibility(View.GONE);
                canModify = false;
            }
        }
    }


    @Override
    protected void initData() {
        taskList = new ArrayList<>();
        taskAdapter = new WorkTaskPeopleAdapter
                (R.layout.item_work_task_people, taskList,canModify);
        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());
        taskParamMap.put("delete", false);
        taskParamMap.put("actNum", "");
        taskParamMap.put("userCode", "");
        taskParamMap.put("userName", "");
        taskParamMap.put("craftName", "");
        taskParamMap.put("skillName", "");
        getTask();
    }


    private void getTask() {
        Observable<BaseMesBean> baseMesBeanObservable =
                TextUtils.equals("1", plan) ?
                        RtfUtils.getMesRtf().pagePlanLabor("aa8faf47c93311e98334fa163e1166bd", WorkUtils.convertMapToBody(taskParam))
                        : RtfUtils.getMesRtf().pageLabor("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<TaskPeopleBean.ListBean> getList = JSON.parseObject(data.getData().toString(), TaskPeopleBean.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:

                        if (TextUtils.equals(plan, "1")) {
                            startActivity(WorkTaskPeopleActivity.class, "id", info.getId(),
                                    "data", JSON.toJSONString(taskList.get(position))
                                    , "info", JSON.toJSONString(info));
                        } else {
                            startActivity(WorkTruePeopleActivity.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;
    }


    @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) {
        Observable<BaseMesBean> baseMesBeanObservable = RtfUtils.getMesRtf().deletePlanLabor(id, "1");
        if (TextUtils.equals(plan, "1")) {
            baseMesBeanObservable = RtfUtils.getMesRtf().deletePlanLabor(id, "1");
        } else {
            baseMesBeanObservable = RtfUtils.getMesRtf().deleteLabor(id, "1");
        }
        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;
                }
                taskPage = 1;
                taskParam.put("pageNum", 1);
                getTask();
                toast("删除成功");
            }
        });
    }

    @OnClick({R.id.tv_add, R.id.tv_agree})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_add:
                if (TextUtils.equals(plan, "1")) {
                    startActivity(WorkTaskPeopleActivity.class, "info", JSON.toJSONString(info));
                } else {
                    startActivity(WorkTruePeopleActivity.class, "info", JSON.toJSONString(info));
                }
                break;
            case R.id.tv_agree:
                startActivity(WorkTrueChoosePeopleActivity.class, "info", JSON.toJSONString(info));
                break;
        }
    }
}
