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

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.blankj.utilcode.util.LogUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.wd.workoffice.R;
import com.wd.workoffice.app.BaseMesBean;
import com.wd.workoffice.app.WorkBaseFg;
import com.wd.workoffice.bean.event.AddFaultEvent;
import com.wd.workoffice.bean.event.ChangeStatus;
import com.wd.workoffice.bean.event.CheckEvent;
import com.wd.workoffice.bean.event.CheckMoneytEvent;
import com.wd.workoffice.bean.mesBean.FaultTypeBean;
import com.wd.workoffice.bean.mesBean.OpmreportErrorBean;
import com.wd.workoffice.bean.mesBean.WokrOrderBean;
import com.wd.workoffice.bean.mesBean.WorkFactoryBean;
import com.wd.workoffice.bean.mesBean.WorkLocationBean;
import com.wd.workoffice.bean.mesBean.WorkMachineBean;
import com.wd.workoffice.bean.workEnum.WorkOrder;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.activity.mes.repair.MesFaultCodeSearchActivity;
import com.wd.workoffice.ui.activity.mes.repair.MesFaultSearchActivity;
import com.wd.workoffice.ui.adapter.WorkOrderErrorAdapter;
import com.wd.workoffice.util.DialogUtils;
import com.wd.workoffice.util.PickTimeUtils;
import com.wd.workoffice.util.WorkUtils;

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

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
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 QualityWorkFragment extends WorkBaseFg {
    @BindView(R.id.tv_save)
    TextView tvSave;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R.id.tv_no)
    TextView tvNo;
    @BindView(R.id.tv_name)
    EditText tvName;
    @BindView(R.id.tv_parent)
    TextView tvParent;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.tv_position)
    TextView tvPosition;
    @BindView(R.id.tv_position_code)
    TextView tvPositionCode;
    @BindView(R.id.tv_machine_code)
    TextView tvMachineCode;
    @BindView(R.id.tv_machine_name)
    TextView tvMachineName;
    @BindView(R.id.tv_fault)
    TextView tvFault;
    @BindView(R.id.tv_problem_code)
    TextView tvProblemCode;
    @BindView(R.id.tv_work_type)
    TextView tvWorkType;
    @BindView(R.id.tv_link_no)
    TextView tvLinkNo;
    @BindView(R.id.tv_create_by)
    TextView tvCreateBy;
    @BindView(R.id.tv_create_time)
    TextView tvCreateTime;
    @BindView(R.id.tv_off)
    TextView tvOff;
    @BindView(R.id.tv_grant)
    TextView tvGrant;
    @BindView(R.id.tv_detail_info)
    TextView tvDetailInfo;
    @BindView(R.id.tv_off_time)
    TextView tvOffTime;
    @BindView(R.id.tv_on_time)
    TextView tvOnTime;
    @BindView(R.id.tv_plan_star_time)
    TextView tvPlanStarTime;
    @BindView(R.id.tv_plan_end_time)
    TextView tvPlanEndTime;
    @BindView(R.id.tv_true_star_time)
    TextView tvTrueStarTime;
    @BindView(R.id.tv_true_end_time)
    TextView tvTrueEndTime;
    @BindView(R.id.rv_data)
    RecyclerView rvData;
    @BindView(R.id.ll_location)
    LinearLayout llLocation;
    @BindView(R.id.ll_position)
    LinearLayout llPosition;
    @BindView(R.id.ll_machine_code)
    LinearLayout llMachineCode;
    @BindView(R.id.ll_fault)
    LinearLayout llFault;
    @BindView(R.id.ll_problem_code)
    LinearLayout llProblemCode;
    @BindView(R.id.ll_work_type)
    LinearLayout llWorkType;
    @BindView(R.id.ll_link_no)
    LinearLayout llLinkNo;
    @BindView(R.id.ll_off)
    LinearLayout llOff;
    @BindView(R.id.ll_grant)
    LinearLayout llGrant;
    @BindView(R.id.ll_plan_star_time)
    LinearLayout llPlanStarTime;
    @BindView(R.id.ll_plan_end_time)
    LinearLayout llPlanEndTime;
    @BindView(R.id.tv_ok)
    TextView tvOk;
    @BindView(R.id.tv_cancel)
    TextView tvCancel;
    @BindView(R.id.ll_off_time)
    LinearLayout llOffTime;
    @BindView(R.id.ll_on_time)
    LinearLayout llOnTime;
    @BindView(R.id.tv_finish)
    TextView tvFinish;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;
    private Map<String, Object> param;
    private List<OpmreportErrorBean.ListBean> dataList;
    private WorkOrderErrorAdapter dataAdapter;
    private WokrOrderBean.ListBean info;
    private int page = 1;
    private Map<String, Object> paramMap;
    private WorkFactoryBean.SitesBean chooseFactory;
    private WorkLocationBean.ListBean chooseLocation;
    private WorkMachineBean.ListBean chooseMachine;
    private FaultTypeBean.ListBean chooseFaultTypeBean;
    private FaultTypeBean.ListBean chooseFaultCode;
    private String[] levelList = new String[]{"检修", "点检", "故障", "项目"};
    private QMUIDialog.MenuDialogBuilder levelDialog;
    private int chooseType;
    private String[] okList = new String[]{"是", "否"};
    private int chooseGrant = -1;
    private QMUIDialog.MenuDialogBuilder grantDialog;
    private QMUIDialog.MenuDialogBuilder shutDownDialog;
    private JSONObject chooseLinkNo;
    private boolean addReason = false;
    private boolean addSolve = false;

    @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));
        levelDialog = DialogUtils.listDialog(getActivity());
        levelDialog.addItems(levelList, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                tvWorkType.setText(levelList[which]);
                chooseType = which + 1;
                chooseLinkNo = null;
                tvLinkNo.setText("");
            }
        });

        grantDialog = DialogUtils.listDialog(getActivity());
        grantDialog.addItems(okList, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                tvGrant.setText(okList[which]);
                info.setMateriel(which == 0);
//                chooseGrant = which;
            }
        });


        shutDownDialog = DialogUtils.listDialog(getActivity());
        shutDownDialog.addItems(okList, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                tvOff.setText(okList[which]);
                info.setShutDown(which == 0);
                if (which == 0) {

                } else {
                    tvOffTime.setText("");
                    tvOnTime.setText("");
                }
//                chooseGrant = which;
            }
        });
        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;
        }
    }


    @Override
    protected void initData() {
        if (!TextUtils.isEmpty(info.getSiteId())) {
            chooseFactory = new WorkFactoryBean.SitesBean();
            chooseFactory.setSiteName(info.getSiteName());
            chooseFactory.setSiteCode(info.getSiteCode());
            chooseFactory.setId(info.getSiteId());
        }
        if (!TextUtils.isEmpty(info.getLocationId())) {
            chooseLocation = new WorkLocationBean.ListBean();
            chooseLocation.setLocationCode(info.getLocationCode());
            chooseLocation.setLocationName(info.getLocationName());
            chooseLocation.setId(info.getLocationId());
        }

        if (!TextUtils.isEmpty(info.getAssetId())) {
            chooseMachine = new WorkMachineBean.ListBean();
            chooseMachine.setAssetCode(info.getAssetCode());
            chooseMachine.setId(info.getAssetId());
            chooseMachine.setDescription(info.getAssetName());
        }

        if (!TextUtils.isEmpty(info.getFailureCodeId())) {
            chooseFaultTypeBean = new FaultTypeBean.ListBean();
            chooseFaultTypeBean.setFailureCode(info.getFailureCode());
            chooseFaultTypeBean.setId(info.getFailureCodeId());
            chooseFaultTypeBean.setDescription(info.getFailureName());
        }

        if (!TextUtils.isEmpty(info.getQuestionId())) {
            chooseFaultCode = new FaultTypeBean.ListBean();
            chooseFaultCode.setFailureCode(info.getQuestionCode());
            chooseFaultCode.setId(info.getQuestionId());
            chooseFaultCode.setDescription(info.getQuestionName());
        }
        if (!TextUtils.isEmpty(info.getLinkedNumberId())) {
            chooseLinkNo = new JSONObject();
            chooseLinkNo.put("code", info.getLinkedNumber());
            chooseLinkNo.put("id", info.getLinkedNumberId());
        }
        chooseType = info.getWorkType();


        tvNo.setText(info.getWoCode());
        tvName.setText(info.getDescription());
        tvParent.setText(info.getParentName());
        tvType.setText("计划工单");
        tvStatus.setText(WorkOrder.getNameByCode(info.getStatus()));
        tvLocation.setText(info.getSiteName());
        tvPosition.setText(info.getLocationName());
        tvPositionCode.setText(info.getLocationCode());
        tvMachineCode.setText(info.getAssetCode());
        tvMachineName.setText(info.getAssetName());

        tvFault.setText(info.getFailureName());
        tvProblemCode.setText(info.getQuestionName());
        tvWorkType.setText(getWorkType(info.getWorkType()));// 1 2 4  5
        tvLinkNo.setText(info.getLinkedNumber());


        tvCreateBy.setText(info.getCreateName());
        tvCreateTime.setText(TimeUtils.millis2String(info.getCreateDateTime(), new SimpleDateFormat("yyyy-MM-dd")));
        tvOff.setText(info.isShutDown() ? "是" : "否");
        tvGrant.setText(info.isMateriel() ? "是" : "否");

        tvDetailInfo.setText(info.getDetailedInformation());

        tvOffTime.setText(getTimeString(info.getShutdownTime()));
        tvOnTime.setText(getTimeString(info.getRecoveryTime()));
        tvPlanStarTime.setText(getTimeString(info.getSchedStart()));
        tvPlanEndTime.setText(getTimeString(info.getSchedFinish()));


//        tvPlanStarTime.setText(info.getSchedStart() == 0L ? "" :
//                TimeUtils.millis2String(info.getSchedStart(), new SimpleDateFormat("yyyy-MM-dd")));
//        tvPlanEndTime.setText(info.getSchedFinish() == 0L ? "" : TimeUtils.millis2String(info.getSchedFinish(), new SimpleDateFormat("yyyy-MM-dd")));
        tvTrueStarTime.setText(info.getActStart() == 0L ? "" : TimeUtils.millis2String(info.getActStart(), new SimpleDateFormat("yyyy-MM-dd")));
        tvTrueEndTime.setText(info.getActFinish() == 0L ? "" : TimeUtils.millis2String(info.getActFinish(), new SimpleDateFormat("yyyy-MM-dd")));


        dataList = new ArrayList<>();
        dataAdapter = new WorkOrderErrorAdapter(R.layout.item_work_order_error, dataList);
        dataAdapter.bindToRecyclerView(rvData);
        param = WorkUtils.pageMesKey();
        param.put("pageNum", 1);
        paramMap = WorkUtils.simpleParam();
        param.put("paramMap", paramMap);
        paramMap.put("assetId", info.getAssetId());

        getData();
    }

    /**
     * 获取工作类型
     *
     * @param workType
     * @return
     */
    private String getWorkType(int workType) {
        String name = "";
        switch (workType) {
            case 1:
                name = "检修";
                break;
            case 2:
                name = "点检";
                break;
            case 4:
                name = "故障";
                break;
            case 5:
                name = "项目";
                break;
        }
        return name;
    }


    private void getData() {
        RtfUtils.getMesRtf().opmreportError("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<OpmreportErrorBean.ListBean> getList = JSON.parseObject(data.getData().toString(), OpmreportErrorBean.class).getList();

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

    @Override
    protected void initEvent() {
        dataAdapter.setOnLoadMoreListener(() -> {
            param.put("pageNum", page);
            getData();
        }, rvData);
    }


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


    @OnClick({R.id.rl_true_end_time, R.id.rl_true_star_time, R.id.tv_confirm, R.id.tv_finish, R.id.tv_ok, R.id.tv_cancel, R.id.ll_off_time, R.id.ll_on_time, R.id.tv_save, R.id.tv_submit, R.id.ll_location, R.id.ll_position, R.id.ll_machine_code, R.id.ll_fault, R.id.ll_problem_code, R.id.ll_work_type, R.id.ll_link_no, R.id.ll_off, R.id.ll_grant, R.id.ll_plan_star_time, R.id.ll_plan_end_time})
    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.ll_location:
                if (!canModify()) {
                    return;
                }
                startActivityForResult(WorkOrderFacotySearchActivity.class, 10001);
                break;
            case R.id.ll_position:
                if (!canModify()) {
                    return;
                }
                if (chooseFactory == null) {
                    toast("请先选择工厂");
                    return;
                }
                startActivityForResult(WorkOrderLocationSearchActivity.class, 10002
                        , "id", chooseFactory.getId());
                break;
            case R.id.ll_machine_code:
                if (!canModify()) {
                    return;
                }
                if (chooseLocation == null) {
                    toast("请先选择位置");
                    return;
                }
                startActivityForResult(WorkOrderMachineSearchActivity.class, 10003
                        , "id", chooseLocation.getId());
                break;
            case R.id.ll_fault:
                if (!canModify()) {
                    return;
                }
                startActivityForResult(MesFaultSearchActivity.class, 10004);
                break;
            case R.id.ll_problem_code:
                if (!canModify()) {
                    return;
                }
                if (null == chooseFaultTypeBean) {
                    toast("请先选择故障类");
                    return;
                }
                startActivityForResult(MesFaultCodeSearchActivity.class, 10005,
                        "id", chooseFaultTypeBean.getId());
                break;
            case R.id.ll_work_type:
                if (!canModify()) {
                    return;
                }
                levelDialog.show();
                break;
            case R.id.ll_link_no:
                if (!canModify()) {
                    return;
                }
                if (chooseType == 0) {
                    toast("请先选择工作类型");
                    return;
                }
                startActivityForResult(WorkOrderNoSearchActivity.class, 10006,
                        "type", chooseType + "");
                break;
            case R.id.ll_off:
                if (!canModify()) {
                    return;
                }
                shutDownDialog.show();
                break;
            case R.id.ll_grant:
                if (!canModify()) {
                    return;
                }
                grantDialog.show();
                break;
            case R.id.rl_true_end_time:
                if (info.getStatus() != 3) {
                    return;
                }
                PickTimeUtils.showPick(getActivity(), new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        String time = TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
                        tvTrueEndTime.setText(time);
                    }
                }).show();
                break;
            case R.id.rl_true_star_time:
                if (info.getStatus() != 3) {
                    return;
                }
                PickTimeUtils.showPick(getActivity(), new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        String time = TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
                        tvTrueStarTime.setText(time);
                    }
                }).show();
                break;
            case R.id.ll_on_time:
                if (!canModify() && info.getStatus() != 3) {
                    return;
                }
                if (!info.isShutDown()) {
                    toast("非停机状态无需选择");
                    return;
                }
                PickTimeUtils.showPick(getActivity(), new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        String time = TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
                        tvOnTime.setText(time);
                    }
                }).show();
                break;
            case R.id.ll_off_time:
                if (!canModify() && info.getStatus() != 3) {
                    return;
                }
                if (!info.isShutDown()) {
                    toast("非停机状态无需选择");
                    return;
                }
                PickTimeUtils.showPick(getActivity(), new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        String time = TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
                        tvOffTime.setText(time);
                    }
                }).show();
                break;
            case R.id.ll_plan_star_time:
                if (!canModify()) {
                    return;
                }
                PickTimeUtils.showPick(getActivity(), new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        String time = TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
                        tvPlanStarTime.setText(time);
                    }
                }).show();
                break;
            case R.id.ll_plan_end_time:
                if (!canModify()) {
                    return;
                }
                PickTimeUtils.showPick(getActivity(), new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        String time = TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
                        tvPlanEndTime.setText(time);
                    }
                }).show();
                break;
        }
    }

    private void check(int type) {//1 保存 2 提交審核 3 通過 4 駁回 5 完成 6 确认完成
        String name = tvName.getText().toString();
        String detailInfo = tvDetailInfo.getText().toString();
        String offTime = tvOffTime.getText().toString();
        String onTime = tvOnTime.getText().toString();
        String planStart = tvPlanStarTime.getText().toString();
        String planEnd = tvPlanEndTime.getText().toString();
        String trueStart = tvTrueStarTime.getText().toString();
        String trueEnd = tvTrueEndTime.getText().toString();
        if (TextUtils.isEmpty(name)) {
            toast("工单名称不能为空");
            return;
        }

        if (chooseFactory == null) {
            toast("请选择工厂");
            return;
        }
        if (chooseLocation == null) {
            toast("请选择位置名称");
            return;
        }
        if (chooseType == 0) {
            toast("请选择工作类型");
            return;
        }
        if (chooseLinkNo == null) {
            toast("请选择关联单号");
            return;
        }
        if (info.getStatus() == 3 && info.getWorkType() == 4 && (!addReason || !addSolve)) {
            toast("请填写故障原因、解决措施");
            return;
        }
        info.setSiteName(chooseFactory.getSiteName());
        info.setSiteCode(chooseFactory.getSiteCode());
        info.setSiteId(chooseFactory.getId());

        info.setLocationCode(chooseLocation.getLocationCode());
        info.setLocationName(chooseLocation.getLocationName());
        info.setLocationId(chooseLocation.getId());

        info.setLinkedNumber(chooseLinkNo.getString("code"));
        info.setLinkedNumberId(chooseLinkNo.getString("id"));


        if (chooseMachine != null) {
            info.setAssetCode(chooseMachine.getAssetCode());
            info.setAssetId(chooseMachine.getId());
            info.setAssetName(chooseMachine.getDescription());
        }
        if (chooseFaultTypeBean != null) {
            info.setFailureCode(chooseFaultTypeBean.getFailureCode());
            info.setFailureCodeId(chooseFaultTypeBean.getId());
            info.setFailureName(chooseFaultTypeBean.getDescription());
        }
        if (chooseFaultCode != null) {
            info.setQuestionCode(chooseFaultCode.getFailureCode());
            info.setQuestionId(chooseFaultCode.getId());
            info.setQuestionName(chooseFaultCode.getDescription());
        }
        info.setWorkType(chooseType);

        if (!TextUtils.isEmpty(trueStart)) {
            info.setActStart(TimeUtils.string2Millis(trueStart));
        }
        if (!TextUtils.isEmpty(trueEnd)) {
            info.setActFinish(TimeUtils.string2Millis(trueEnd));
        }
        if (!TextUtils.isEmpty(offTime)) {
            info.setShutdownTime(TimeUtils.string2Millis(offTime));
        }
        if (!TextUtils.isEmpty(onTime)) {
            info.setRecoveryTime(TimeUtils.string2Millis(onTime));
        }
        if (!TextUtils.isEmpty(planStart)) {
            info.setSchedStart(TimeUtils.string2Millis(planStart));
        }
        if (!TextUtils.isEmpty(planEnd)) {
            info.setSchedFinish(TimeUtils.string2Millis(planEnd));
        }
        info.setDescription(name);
        info.setDetailedInformation(detailInfo);
        switch (type) {//1 保存 2 提交審核 3 通過 4 駁回 5完成  6 确认完成
            case 1:
                info.setStatus(1);
                info.setIsSave(1);
                break;
            case 2:
                info.setIsSave(2);
                info.setStatus(2);
                break;
            case 3:
                info.setStatus(2);
                break;
            case 4:
                info.setIsSave(3);
                info.setStatus(6);
                break;
            case 5:
                info.setStatus(3);
                break;
            case 6:
                info.setStatus(4);
                break;
        }
        RtfUtils.getMesRtf().workOrderUpdate("1",
                WorkUtils.convertMapToBody(JSON.parseObject(JSON.toJSONString(info)))).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;
                }
                EventBus.getDefault().post(new ChangeStatus());
                toast("操作成功");
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 10001:
                if (resultCode == 10001) {
                    chooseFactory = JSON.parseObject(data.getStringExtra("data"), WorkFactoryBean.SitesBean.class);
                    tvLocation.setText(chooseFactory.getSiteName());
                    chooseLocation = null;
                    chooseMachine = null;
                    tvPosition.setText("");
                    tvPositionCode.setText("");
                    tvMachineCode.setText("");
                    tvMachineName.setText("");
                }
                break;
            case 10002:
                if (resultCode == 10001) {
                    chooseLocation = JSON.parseObject(data.getStringExtra("data"), WorkLocationBean.ListBean.class);
                    tvPosition.setText(chooseLocation.getLocationName());
                    tvPositionCode.setText(chooseLocation.getLocationCode());
                    chooseMachine = null;
                    tvMachineCode.setText("");
                    tvMachineName.setText("");
                }
                break;
            case 10003:
                if (resultCode == 10001) {
                    chooseMachine = JSON.parseObject(data.getStringExtra("data"), WorkMachineBean.ListBean.class);
                    tvMachineCode.setText(chooseMachine.getAssetCode());
                    tvMachineName.setText(chooseMachine.getDescription());
                }
                break;
            case 10004:
                if (resultCode == 10001) {
                    chooseFaultTypeBean = JSON.parseObject(data.getStringExtra("data"), FaultTypeBean.ListBean.class);
                    tvFault.setText(chooseFaultTypeBean.getDescription());
                    chooseFaultCode = null;
                    tvProblemCode.setText("");
                }
                break;
            case 10005:
                if (resultCode == 10001) {
                    chooseFaultCode = JSON.parseObject(data.getStringExtra("data"), FaultTypeBean.ListBean.class);
                    tvProblemCode.setText(chooseFaultCode.getDescription());
                }
                break;
            case 10006:
                if (resultCode == 10001) {
                    chooseLinkNo = JSON.parseObject(data.getStringExtra("data"));
                    tvLinkNo.setText(chooseLinkNo.getString("code"));
                }
                break;
        }
    }

    private String getTimeString(long time) {
        return time == 0L ? "" : TimeUtils.millis2String(time);
    }

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

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

    @Subscribe
    public void refresh(CheckEvent event) {
        check(event.getType());
    }

    @Subscribe
    public void AddFaultEvent(AddFaultEvent event) {
        LogUtils.e("------------" + JSON.toJSONString(event));
        addReason = event.isAddReason();
        addSolve = event.isAddSolve();
    }

    private boolean canModify() {
        boolean canModify = false;
        tvName.setFocusable(false);
        tvDetailInfo.setFocusable(false);
        switch (info.getStatus()) {// "状态 1草稿 2待审批 3处理中 4已完成待确认 5已关闭 6已驳回
            case 1:
                canModify = true;
                tvName.setFocusable(true);
                tvDetailInfo.setFocusable(true);
                break;
            case 2:
                canModify = false;
                break;
            case 3:
                break;
            case 4:
                break;
            case 6:
                canModify = true;
                tvName.setFocusable(true);
                tvDetailInfo.setFocusable(true);
                break;
        }
        return canModify;
    }

}
