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

import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
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.WorkToolBarActivity;
import com.wd.workoffice.bean.event.ChangeStatus;
import com.wd.workoffice.bean.mesBean.ServiceBean;
import com.wd.workoffice.bean.mesBean.ServiceCheckBean;
import com.wd.workoffice.bean.mesBean.ServiceStandardBean;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.util.DialogUtils;
import com.wd.workoffice.util.MathUtils;
import com.wd.workoffice.util.WorkUtils;

import org.greenrobot.eventbus.EventBus;

import androidx.annotation.Nullable;
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 ServiceStandardDetailActivity extends WorkToolBarActivity {

    @BindView(R.id.tv_process_standard)
    TextView tvProcessStandard;
    @BindView(R.id.tv_num_a)
    TextView tvNumA;
    @BindView(R.id.tv_num_b)
    TextView tvNumB;
    @BindView(R.id.tv_num_c)
    TextView tvNumC;
    @BindView(R.id.tv_measurement_unit)
    TextView tvMeasurementUnit;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.tv_failure_code)
    TextView tvFailureCode;
    @BindView(R.id.tv_desc)
    EditText tvDesc;
    @BindView(R.id.tv_remark)
    EditText tvRemark;
    @BindView(R.id.ll_status)
    LinearLayout llStatus;
    @BindView(R.id.tv_error)
    TextView tvError;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    private ServiceStandardBean.ListBean info;
    private QMUIDialog.MenuDialogBuilder statusDialog;
    private String[] statusList = new String[]{"正常", "异常"};
    private Integer[] statusValue = new Integer[]{0, 1};//0正常 1异常
    private Integer[] normalValue = new Integer[]{1, 0};//0异常 1正常
    private int chooseStatus;
    private int chooseNormal;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
    }

    @Override
    protected void initData() {
        info = JSON.parseObject(getIntent().getStringExtra("info"), ServiceStandardBean.ListBean.class);
        changeView();
        statusDialog = DialogUtils.listDialog(this);
        statusDialog.addItems(statusList, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                tvStatus.setText(statusList[which]);
                chooseStatus = statusValue[which];
                chooseNormal = normalValue[which];
                if (canModify()) {
                    if (statusValue[which] == 1) {
                        llBottom.setVisibility(View.VISIBLE);
                        QMUIDialog.MessageDialogBuilder ok = DialogUtils.okAndCancelDialog(ServiceStandardDetailActivity.this);
                        ok.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();
                                startActivityForResult(ServiceFaultActivity.class, 10001,
                                        "data", getIntent().getStringExtra("data"),
                                        "info", getIntent().getStringExtra("info"),
                                        "machine", getIntent().getStringExtra("machine"),
                                        "type", getIntent().getStringExtra("type"));
                            }
                        }).show();
                    } else {
                        llBottom.setVisibility(View.GONE);
                    }
                }

            }
        });

    }

    private void changeView() {
        if (TextUtils.isEmpty(getIntent().getStringExtra("type"))) {
            tvDesc.setText(info.getDescription());
            tvFailureCode.setText(info.getFailureCode());
            tvMeasurementUnit.setText(info.getMeasurementUnit());
            tvNumA.setText(MathUtils.converData(info.getNumA(), 3));
            tvNumB.setText(MathUtils.converData(info.getNumB(), 3));
            tvNumC.setText(MathUtils.converData(info.getNumC(), 3));
            tvProcessStandard.setText(info.getProcessStandard());
            if (!TextUtils.isEmpty(info.getStatus())) {
                tvStatus.setText(TextUtils.equals(info.getStatus(), "1") ? "异常" : "正常");//1 异常 0正常
            }
            if (canModify()) {
                if (TextUtils.equals(info.getStatus(), "1")) {
                    llBottom.setVisibility(View.VISIBLE);
                } else {
                    llBottom.setVisibility(View.GONE);
                }
            }

            tvRemark.setText(info.getRemarks());
        } else {
            setTitle("检修标准");
            tvDesc.setText(info.getDescription());
            tvFailureCode.setText(info.getReportCode());
            tvMeasurementUnit.setText(info.getUint());
            tvNumA.setText(MathUtils.converData(info.getNumA(), 3));
            tvNumB.setText(MathUtils.converData(info.getNumB(), 3));
            tvNumC.setText(MathUtils.converData(info.getNumC(), 3));
            tvProcessStandard.setText(info.getProcessStandard());
            if (!TextUtils.isEmpty(info.getNormal())) {
                tvStatus.setText(TextUtils.equals(info.getNormal(), "0") ? "异常" : "正常");//1 异常 0正常
            }
            if (TextUtils.equals(info.getStatus(), "1")) {
                llBottom.setVisibility(View.VISIBLE);
            } else {
                llBottom.setVisibility(View.GONE);
            }
            tvRemark.setText(info.getRemarks());
        }
    }


    @Override
    protected void initEvent() {
    }


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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (canModify()) {
            getMenuInflater().inflate(R.menu.menu_save, menu);
        } else {
            return super.onCreateOptionsMenu(menu);
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.save:
                save();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void save() {
//        Map<String, Object> param = WorkUtils.simpleParam();
//        param.put("remarks", tvRemark.getText().toString());
//        param.put("status", chooseStatus);
//        param.put("id", info.getId());
//        param.put("projectId", info.getProjectId());
//        param.put("numA", "");
//        param.put("numB", "");
//        param.put("numC", "");
        info.setStatus(chooseStatus + "");
        info.setNormal(chooseNormal + "");
        info.setFailureCode(tvFailureCode.getText().toString());
//        WorkUtils.convertMapToBody(JSON.parseObject(JSON.toJSONString(info))))
        Observable<BaseMesBean> baseMesBeanObservable;
        if (TextUtils.isEmpty(getIntent().getStringExtra("type"))) {
            info.setRemarks(tvRemark.getText().toString());
            baseMesBeanObservable = RtfUtils.getMesRtf().spotCheckBillStandard("00d12c310f4411ea8334fa163e1166bd", 3,
                    WorkUtils.convertMapToBody(JSON.parseObject(JSON.toJSONString(info))));
        } else {
            info.setDescription(tvDesc.getText().toString());
            baseMesBeanObservable = RtfUtils.getMesRtf().modinspoproject("00d12c310f4411ea8334fa163e1166bd", 3,
                    WorkUtils.convertMapToBody(JSON.parseObject(JSON.toJSONString(info))));
        }
        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;
                }
                EventBus.getDefault().post(new ChangeStatus());
                toast("保存成功");
                finish();
            }
        });
    }

    @OnClick({R.id.tv_error, R.id.ll_status})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_error:
                startActivityForResult(ServiceFaultActivity.class, 10001,
                        "data", getIntent().getStringExtra("data"),
                        "info", getIntent().getStringExtra("info"),
                        "machine", getIntent().getStringExtra("machine"),
                        "type", getIntent().getStringExtra("type"));
                break;
            case R.id.ll_status:
                if (canModify()) {
                    statusDialog.show();
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 10001:
                if (requestCode == 10001 && resultCode == 10001) {
                    tvFailureCode.setText(data.getStringExtra("data"));
                    llBottom.setVisibility(View.GONE);
                }
                break;
        }
    }

    private boolean canModify() {
        if (TextUtils.isEmpty(getIntent().getStringExtra("type"))) {//点检//2待执行  3 已完成
            ServiceCheckBean.ListBean data = JSON.parseObject(getIntent().getStringExtra("data"), ServiceCheckBean.ListBean.class);//最外层
            if (data.getStatus() != null && 3 == data.getStatus()) {
                return false;
            } else {
                return true;
            }
        } else {
            ServiceBean.ListBean data = JSON.parseObject(getIntent().getStringExtra("data"), ServiceBean.ListBean.class);//最外层
            if (data.getStatus() != null && 1 == data.getStatus()) {//   1 待执行   2已完成
                return true;
            } else {
                return false;
            }
        }
    }
}
