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.event.ChangeStatus;
import com.wd.workoffice.bean.event.CheckEvent;
import com.wd.workoffice.bean.mesBean.WokrOrderBean;
import com.wd.workoffice.bean.mesBean.WorkOrderSon;
import com.wd.workoffice.bean.mesBean.WorkTaskBean;
import com.wd.workoffice.bean.workEnum.WorkOrder;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.adapter.WorkOrderSonAdapter;
import com.wd.workoffice.ui.adapter.WorkOrderTaskAdapter;
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 flexible.xd.android_base.utils.TimeUtils;
import io.reactivex.disposables.Disposable;

/**
 * 详情计划
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class QualityWorkPlanFragment extends WorkBaseFg {
    @BindView(R.id.tv_no)
    TextView tvNo;
    @BindView(R.id.tv_desc)
    TextView tvDesc;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.rv_son)
    RecyclerView rvSon;
    @BindView(R.id.rv_data)
    RecyclerView rvData;
    @BindView(R.id.tv_add_task)
    TextView tvAddTask;
    @BindView(R.id.tv_save)
    TextView tvSave;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;
    @BindView(R.id.tv_ok)
    TextView tvOk;
    @BindView(R.id.tv_cancel)
    TextView tvCancel;
    @BindView(R.id.tv_finish)
    TextView tvFinish;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    private Map<String, Object> param;
    private List<WorkOrderSon.ListBean> sonList;
    private List<WorkTaskBean.ListBean> taskList;
    private WorkOrderSonAdapter sonAdapter;
    private WorkOrderTaskAdapter taskAdapter;
    private WokrOrderBean.ListBean info;
    private int page = 1;
    private int taskPage = 1;
    private Map<String, Object> paramMap;
    private Map<String, Object> taskParam;
    private Map<String, Object> taskParamMap;

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

    @Override
    protected void initView() {
        ButterKnife.bind(this, getContentView());
        rvData.setLayoutManager(new LinearLayoutManager(getActivity(), RecyclerView.VERTICAL, false));
        rvSon.setLayoutManager(new LinearLayoutManager(getActivity(), RecyclerView.VERTICAL, false));
        switch (info.getStatus()) {// "状态 1草稿 2待审批 3处理中 4已完成待确认 5已关闭 6已驳回
            case 1:
                llBottom.setVisibility(View.VISIBLE);
                tvOk.setVisibility(View.GONE);
                tvCancel.setVisibility(View.GONE);
                tvSave.setVisibility(View.VISIBLE);
                tvSubmit.setVisibility(View.VISIBLE);
                tvFinish.setVisibility(View.GONE);
                tvConfirm.setVisibility(View.GONE);
                break;
            case 2:
                llBottom.setVisibility(View.VISIBLE);
                tvOk.setVisibility(View.VISIBLE);
                tvCancel.setVisibility(View.VISIBLE);
                tvSave.setVisibility(View.GONE);
                tvSubmit.setVisibility(View.GONE);
                tvFinish.setVisibility(View.GONE);
                tvConfirm.setVisibility(View.GONE);
                break;
            case 3:
                llBottom.setVisibility(View.VISIBLE);
                tvOk.setVisibility(View.GONE);
                tvCancel.setVisibility(View.GONE);
                tvSave.setVisibility(View.GONE);
                tvSubmit.setVisibility(View.GONE);
                tvFinish.setVisibility(View.VISIBLE);
                tvConfirm.setVisibility(View.GONE);
                break;
            case 4:
                llBottom.setVisibility(View.VISIBLE);
                tvOk.setVisibility(View.GONE);
                tvCancel.setVisibility(View.GONE);
                tvSave.setVisibility(View.GONE);
                tvSubmit.setVisibility(View.GONE);
                tvFinish.setVisibility(View.GONE);
                tvConfirm.setVisibility(View.VISIBLE);
                break;
            default:
                llBottom.setVisibility(View.GONE);
                break;
        }
        changeView();
    }

    private void changeView() {
        if (!WorkUtils.workCanModify(info.getStatus())){
            tvAddTask.setVisibility(View.GONE);
        }

    }


    @Override
    protected void initData() {
        tvNo.setText(info.getWoCode());
        tvDesc.setText(info.getDescription());
        tvStatus.setText(WorkOrder.getNameByCode(info.getStatus()));
        taskList = new ArrayList<>();
        taskAdapter = new WorkOrderTaskAdapter(R.layout.item_work_order_task, taskList,WorkUtils.workCanModify(info.getStatus()));
        taskAdapter.bindToRecyclerView(rvData);

        sonList = new ArrayList<>();
        sonAdapter = new WorkOrderSonAdapter(R.layout.item_work_order_son, sonList);
        sonAdapter.bindToRecyclerView(rvSon);
        param = WorkUtils.pageMesKey();
        param.put("pageNum", 1);
        paramMap = WorkUtils.simpleParam();
        param.put("paramMap", paramMap);
        paramMap.put("parentId", info.getId());


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

        getData();
        getTask();
    }


    private void getData() {
        RtfUtils.getMesRtf().workOrderChild("1", WorkUtils.convertMapToBody(param)).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<WorkOrderSon.ListBean> getList = JSON.parseObject(data.getData().toString(), WorkOrderSon.class).getList();

                if (page == 1) {
                    sonList.clear();
                    sonList.addAll(getList);
                    sonAdapter.notifyDataSetChanged();
                    sonAdapter.loadMoreComplete();
                } else {
                    sonAdapter.loadMoreComplete();
                    sonList.addAll(getList);
                    sonAdapter.notifyDataSetChanged();
                }
                if (getList.size() == 0) {
                    sonAdapter.loadMoreEnd(true);
                } else {
                    page++;
                }
            }
        });

    }

    private void getTask() {
        RtfUtils.getMesRtf().pageActivity("1", WorkUtils.convertMapToBody(taskParam)).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<WorkTaskBean.ListBean> getList = JSON.parseObject(data.getData().toString(), WorkTaskBean.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() {
        sonAdapter.setOnLoadMoreListener(() -> {
            param.put("pageNum", page);
            getData();
        }, rvSon);
        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(WorkTaskActivity.class, "id", info.getId(),
                                "data", JSON.toJSONString(taskList.get(position)));
                        break;
                }
            }
        });
        taskAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(WorkTaskDetailActivity.class,
                        "plan", "1", "info", JSON.toJSONString(taskList.get(position))
                ,"work", JSON.toJSONString(info));
            }
        });
    }


    @Override
    protected int layoutId() {
        return R.layout.fg_work_order_detail_plan;
    }




    @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().deleteActivity(id, "1"
        ).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("删除成功");
            }
        });
    }


    private void check(int type) {//1 保存 2 提交審核 3 通過 4 駁回 5 完成 6 确认完成
        EventBus.getDefault().post(new CheckEvent(type));
    }

    @OnClick({R.id.tv_save, R.id.tv_submit, R.id.tv_ok, R.id.tv_cancel, R.id.tv_finish, R.id.tv_confirm, R.id.tv_add_task})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_confirm:
                check(6);
                break;
            case R.id.tv_finish:
                check(5);
                break;
            case R.id.tv_ok:
                check(3);
                break;
            case R.id.tv_cancel:
                check(4);
                break;
            case R.id.tv_save:
                check(1);
                break;
            case R.id.tv_submit:
                check(2);
                break;
            case R.id.tv_add_task:
                startActivity(WorkTaskActivity.class, "id", info.getId());
                break;
        }
    }
}
