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

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.wd.workoffice.R;
import com.wd.workoffice.app.BaseMesBean;
import com.wd.workoffice.app.WorkBaseFg;
import com.wd.workoffice.bean.event.CheckEvent;
import com.wd.workoffice.bean.mesBean.FaultBean;
import com.wd.workoffice.bean.mesBean.SolveBean;
import com.wd.workoffice.bean.mesBean.WokrOrderBean;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.adapter.WorkOrderFaultAdapter;
import com.wd.workoffice.util.WorkUtils;

import org.greenrobot.eventbus.EventBus;

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.disposables.Disposable;

/**
 * 故障
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class QualityWorkFaultFragment extends WorkBaseFg {
    @BindView(R.id.tv_no)
    TextView tvNo;
    @BindView(R.id.tv_desc)
    TextView tvDesc;
    @BindView(R.id.rv_data)
    RecyclerView rvData;
    @BindView(R.id.tv_delete)
    TextView tvDelete;
    @BindView(R.id.tv_code)
    TextView tvCode;
    @BindView(R.id.tv_solve_desc)
    TextView tvSolveDesc;
    @BindView(R.id.tv_solve_delete)
    TextView tvSolveDelete;
    @BindView(R.id.tv_solve_code)
    TextView tvSolveCode;
    @BindView(R.id.ll_code)
    LinearLayout llCode;
    @BindView(R.id.ll_solve_code)
    LinearLayout llSolveCode;
    @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 List<FaultBean.ListBean> taskList;
    private WorkOrderFaultAdapter taskAdapter;
    private WokrOrderBean.ListBean info;
    private int page = 1;
    private int taskPage = 1;
    private Map<String, Object> taskParam;
    private Map<String, Object> taskParamMap;
    private FaultBean.ListBean chooseReason;
    private FaultBean.ListBean chooseSolve;

    @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));
    }


    @Override
    protected void initData() {
//        tvNo.setText(info.getWoCode());
//        tvDesc.setText(info.getDescription());
//        taskList = new ArrayList<>();
//        taskAdapter = new WorkOrderFaultAdapter(R.layout.item_work_order_fault, taskList);
//        taskAdapter.bindToRecyclerView(rvData);
//        taskParam = WorkUtils.pageMesKey();
//        taskParam.put("pageNum", 1);
//        taskParamMap = WorkUtils.simpleParam();
//        taskParam.put("paramMap", taskParamMap);
//        taskParamMap.put("woId", info.getId());
//        getTask();
        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;
        }
        getFault();
    }


    private void getTask() {
        RtfUtils.getMesRtf().pageFailure("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<FaultBean.ListBean> getList = JSON.parseObject(data.getData().toString(), FaultBean.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) {
                    taskAdapter.loadMoreEnd(true);
                } else {
                    taskPage++;
                }
            }
        });

    }

    private void getFault() {

        Map<String, Object> param = WorkUtils.pageMesKey();
        param.put("pageNum", 1);
        Map<String, Object> paramMap = WorkUtils.simpleParam();
        paramMap.put("parentId", info.getQuestionId());
        paramMap.put("woId", info.getId());
        param.put("paramMap", paramMap);
        RtfUtils.getMesRtf().grandson("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<FaultBean.ListBean> getList = JSON.parseObject(data.getData().toString(), FaultBean.class).getList();
                if (getList.size() != 0) {
                    FaultBean.ListBean fault = getList.get(0);
                    if (chooseReason == null) {
                        chooseReason = new FaultBean.ListBean();
                        chooseReason.setId(fault.getFailureId());
                        chooseReason.setFailureId(fault.getFailureId());
                        chooseReason.setFailureCode(fault.getFailureCode());
                        chooseReason.setDescription(fault.getFailureName());
                    }
                    chooseReason.setDataId(fault.getId());
                    getSolveFault(fault.getFailureId());
                    tvCode.setText(fault.getFailureCode());
                    tvDesc.setText(fault.getFailureName());

                }
            }
        });

    }

    private void getSolveFault(String id) {
        Map<String, Object> param = WorkUtils.pageMesKey();
        param.put("pageNum", 1);
        Map<String, Object> paramMap = WorkUtils.simpleParam();
        param.put("paramMap", paramMap);
        paramMap.put("parentId", id);
//        paramMap.put("woId", info.getId());
        RtfUtils.getMesRtf().greatgrandson("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<SolveBean.ListBean> getList = JSON.parseObject(data.getData().toString(), SolveBean.class).getList();
                if (getList.size() != 0) {
                    SolveBean.ListBean fault = getList.get(0);

                    if (chooseSolve == null) {
                        chooseSolve = new FaultBean.ListBean();
                        chooseSolve.setId(fault.getFailureId());
                        chooseSolve.setFailureId(fault.getFailureId());
                        chooseSolve.setFailureCode(fault.getFailureCode());
                        chooseSolve.setDescription(fault.getFailureName());
                    }
                    chooseSolve.setDataId(fault.getId());
                    tvSolveCode.setText(fault.getFailureCode());
                    tvSolveDesc.setText(fault.getFailureName());
                }
            }
        });

    }

    @Override
    protected void initEvent() {
//        taskAdapter.setOnLoadMoreListener(() -> {
//            taskParam.put("pageNum", taskPage);
//            getTask();
//        }, rvData);
//        taskAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                startActivity(WorkTaskDetailActivity.class,
//                        "plan", "0", "info", JSON.toJSONString(taskList.get(position)));
//            }
//        });
    }


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


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 10001:
                if (resultCode == 10001) {
                    chooseReason = JSON.parseObject(data.getStringExtra("data"), FaultBean.ListBean.class);
//                    tvCode.setText(chooseReason.getFailureCode());
//                    tvDesc.setText(chooseReason.getDescription());
                    addReason();
                }
                break;
            case 10002:
                if (resultCode == 10001) {
                    chooseSolve = JSON.parseObject(data.getStringExtra("data"), FaultBean.ListBean.class);
//                    tvSolveCode.setText(chooseSolve.getFailureCode());
//                    tvSolveDesc.setText(chooseSolve.getDescription());
                    addSolve();
                }
                break;
        }
    }

    private void addReason() {
        Map<String, Object> param = WorkUtils.pageMesKey();
        param.put("woId", info.getId());
        param.put("parentId", info.getQuestionId());
        param.put("failureId", chooseReason.getId());
        param.put("failureCode", chooseReason.getFailureCode());
        param.put("failureName", chooseReason.getDescription());
        RtfUtils.getMesRtf().grandsonOption("1", "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;
                }
                toast("操作成功");
                getFault();
//                tvCode.setText(chooseReason.getFailureCode());
//                tvDesc.setText(chooseReason.getDescription());
            }
        });
    }

    private void addSolve() {
        Map<String, Object> param = WorkUtils.pageMesKey();
        param.put("woId", info.getId());
        param.put("parentId", chooseReason.getId());
        param.put("failureId", chooseSolve.getFailureId());
        param.put("failureCode", chooseSolve.getFailureCode());
        param.put("failureName", chooseSolve.getDescription());
        RtfUtils.getMesRtf().greatgrandsonOption("1", "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;
                }
                toast("操作成功");
                getSolveFault(chooseReason.getId());
//                tvCode.setText(chooseReason.getFailureCode());
//                tvDesc.setText(chooseReason.getDescription());
            }
        });

    }

    private void deleteReason() {
        Map<String, Object> param = WorkUtils.simpleParam();
        param.put("id", chooseReason.getDataId());
        RtfUtils.getMesRtf().grandsonOption("1", "2", 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;
                }
                toast("操作成功");
                tvCode.setText("");
                tvDesc.setText("");
                chooseReason = null;
            }
        });
    }

    private void deleteSolve() {
        Map<String, Object> param = WorkUtils.simpleParam();
        param.put("id", chooseSolve.getDataId());
        RtfUtils.getMesRtf().greatgrandsonOption("1", "2", 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;
                }
                toast("操作成功");
                tvSolveCode.setText("");
                tvSolveDesc.setText("");
                chooseSolve = null;
            }
        });
    }


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

    @OnClick({R.id.tv_delete, R.id.ll_code, R.id.tv_solve_delete, R.id.ll_solve_code, R.id.tv_save, R.id.tv_submit, R.id.tv_ok, R.id.tv_cancel, R.id.tv_finish, R.id.tv_confirm})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_delete:
                if (chooseSolve != null) {
                    toast("请先删除解决措施");
                    return;
                }
                deleteReason();
                break;
            case R.id.ll_code:
                if (chooseReason != null) {
                    toast("请先删除后,在重新选择");
                    return;
                }
                startActivityForResult(WorkFaultChooseReasonActivity.class, 10001
                        , "id", info.getQuestionId());
                break;
            case R.id.tv_solve_delete:
                if (chooseReason == null) {
                    toast("您还未选择");
                    return;
                }
                if (chooseSolve == null) {
                    toast("您还未选择");
                    return;
                }
                deleteSolve();
                break;
            case R.id.ll_solve_code:
                if (chooseReason == null) {
                    toast("请选择故障原因");
                    return;
                }
                if (chooseSolve != null) {
                    toast("请先删除后,在重新选择");
                    return;
                }
                startActivityForResult(WorkFaultChooseSolveActivity.class, 10002
                        , "id", chooseReason.getId());
                break;
            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;
        }
    }
}
