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

import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.wd.workoffice.R;
import com.wd.workoffice.app.BaseMesBean;
import com.wd.workoffice.app.WorkToolBarActivity;
import com.wd.workoffice.bean.event.AddFactoryEvent;
import com.wd.workoffice.bean.event.AddUserDataEvent;
import com.wd.workoffice.bean.event.ModifyFactoryEvent;
import com.wd.workoffice.bean.event.ModifyUserDataEvent;
import com.wd.workoffice.bean.mesBean.FactoryDetailBean;
import com.wd.workoffice.bean.mesBean.UserDataBean;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.adapter.UserDataAdd3AddAdapter;
import com.wd.workoffice.ui.adapter.UserDataAdd3LabelAddAdapter;
import com.wd.workoffice.ui.adapter.UserDataAdd3RefAddAdapter;
import com.wd.workoffice.util.PickTimeUtils;
import com.wd.workoffice.util.WorkUtils;

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

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

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;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 用户数据采集，编辑炼钢厂
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class MesChooseFactoryModifyActivity extends WorkToolBarActivity {
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_sum)
    EditText etSum;
    @BindView(R.id.et_type)
    EditText etType;
    @BindView(R.id.rv_data1)
    RecyclerView rvData1;
    @BindView(R.id.tv_add1)
    TextView tvAdd1;
    @BindView(R.id.rv_data2)
    RecyclerView rvData2;
    @BindView(R.id.tv_add2)
    TextView tvAdd2;
    @BindView(R.id.rv_data3)
    RecyclerView rvData3;
    @BindView(R.id.tv_add3)
    TextView tvAdd3;
    @BindView(R.id.rl_factory)
    RelativeLayout rlFactory;
    private List<FactoryDetailBean.SteelFurnListBean> data1List;
    private List<FactoryDetailBean.SteelRefFurnListBean> data2List;
    private List<FactoryDetailBean.SteelLadleListBean> data3List;
    private UserDataAdd3AddAdapter data1Adapter;
    private UserDataAdd3RefAddAdapter data2Adapter;
    private UserDataAdd3LabelAddAdapter data3Adapter;
    private UserDataBean.ListBean data;
    private FactoryDetailBean factoryDetailBean;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        rlFactory.setVisibility(View.GONE);
        rvData1.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rvData2.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rvData3.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));

    }

    @Override
    protected void initData() {
        data = JSON.parseObject(getIntent().getStringExtra("data"), UserDataBean.ListBean.class);
        data1List = new ArrayList<>();
        data2List = new ArrayList<>();
        data3List = new ArrayList<>();
        data1Adapter = new UserDataAdd3AddAdapter(R.layout.item_user_add3_add, data1List);
        data2Adapter = new UserDataAdd3RefAddAdapter(R.layout.item_user_add3_add, data2List);
        data3Adapter = new UserDataAdd3LabelAddAdapter(R.layout.item_user_add_factory_label, data3List);
        data1Adapter.bindToRecyclerView(rvData1);
        data2Adapter.bindToRecyclerView(rvData2);
        data3Adapter.bindToRecyclerView(rvData3);
        getFactoryData(data.getSteelmakingWorksCode());
    }

    private void getFactoryData(String code) {
        Map<String, Object> param = WorkUtils.simpleParam();
        param.put("steelmakingWorksCode", code);
        RtfUtils.getMesRtf().factoryDetail("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;
                }
                factoryDetailBean = JSON.parseObject(data.getData().toString(), FactoryDetailBean.class);
                FactoryDetailBean.SteelWorksBean steelWorks = factoryDetailBean.getSteelWorks();
                if (steelWorks != null) {
                    etSum.setText(steelWorks.getAnnualOutput());
                    etName.setText(steelWorks.getSteelmakingWorksName());
                    etType.setText(steelWorks.getSteelGrade());
                }
                if (factoryDetailBean.getSteelFurnList() != null) {
                    data1List.clear();
                    data1List.addAll(factoryDetailBean.getSteelFurnList());
                    data1Adapter.notifyDataSetChanged();
                }
                if (factoryDetailBean.getSteelRefFurnList() != null) {
                    data2List.clear();
                    data2List.addAll(factoryDetailBean.getSteelRefFurnList());
                    data2Adapter.notifyDataSetChanged();
                }
                if (factoryDetailBean.getSteelLadleList() != null) {
                    data3List.clear();
                    data3List.addAll(factoryDetailBean.getSteelLadleList());
                    data3Adapter.notifyDataSetChanged();
                }

            }
        });
    }

    @Override
    protected void initEvent() {
        data1Adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                data1List.remove(position);
                data1Adapter.notifyDataSetChanged();
            }
        });
        data2Adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                data2List.remove(position);
                data2Adapter.notifyDataSetChanged();
            }
        });
        data3Adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.tv_delete:
                        data3List.remove(position);
                        data3Adapter.notifyDataSetChanged();
                        break;
                    case R.id.rl_time:
                        PickTimeUtils.showPickThree(MesChooseFactoryModifyActivity.this, new OnTimeSelectListener() {
                            @Override
                            public void onTimeSelect(Date date, View v) {
                                data3List.get(position).setCastingDateTime(TimeUtils.date2Millis(date) / 1000);
                                data3Adapter.notifyDataSetChanged();
                            }
                        }).show();
                        break;
                }

            }
        });
    }

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


    @OnClick({R.id.tv_add1, R.id.tv_add2, R.id.tv_add3})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_add1:
                FactoryDetailBean.SteelFurnListBean data1 = new FactoryDetailBean.SteelFurnListBean();
                data1List.add(data1);
                data1Adapter.notifyDataSetChanged();
                break;
            case R.id.tv_add2:
                FactoryDetailBean.SteelRefFurnListBean data2 = new FactoryDetailBean.SteelRefFurnListBean();
                data2List.add(data2);
                data2Adapter.notifyDataSetChanged();
                break;
            case R.id.tv_add3:
                FactoryDetailBean.SteelLadleListBean data3 = new FactoryDetailBean.SteelLadleListBean();
                data3List.add(data3);
                data3Adapter.notifyDataSetChanged();
                break;

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_finish, menu);
        return super.onCreateOptionsMenu(menu);
    }

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

    private void submit() {
        if (!checkParam()) {
            return;
        }
        FactoryDetailBean.SteelWorksBean steelWorks = factoryDetailBean.getSteelWorks();
        if (steelWorks != null) {
            steelWorks.setAnnualOutput(etSum.getText().toString());
            steelWorks.setSteelmakingWorksName(etName.getText().toString());
            steelWorks.setSteelGrade(etType.getText().toString());
        }
        if (factoryDetailBean.getSteelFurnList() != null) {
            factoryDetailBean.getSteelFurnList().clear();
            factoryDetailBean.getSteelFurnList().addAll(data1List);
        }
        if (factoryDetailBean.getSteelRefFurnList() != null) {
            factoryDetailBean.getSteelRefFurnList().clear();
            factoryDetailBean.getSteelRefFurnList().addAll(data2List);
        }
        if (factoryDetailBean.getSteelLadleList() != null) {
            factoryDetailBean.getSteelLadleList().clear();
            factoryDetailBean.getSteelLadleList().addAll(data3List);
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JSON.toJSONString(factoryDetailBean));
        showLoading();
        RtfUtils.getMesRtf().factoryAdd("1", "2", requestBody).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("编辑成功");
                EventBus.getDefault().post(new ModifyFactoryEvent());
                finish();
            }
        });
    }


    private boolean checkParam() {
        boolean dataHasNull = false;
        for (FactoryDetailBean.SteelFurnListBean steelFurnListBean : data1List) {
            if (TextUtils.isEmpty(steelFurnListBean.getCapacity())
                    || TextUtils.isEmpty(steelFurnListBean.getType())) {
                dataHasNull = true;
            }
        }
        if (dataHasNull) {
            toast("请填写炼钢厂数据");
            return false;
        }
        for (FactoryDetailBean.SteelRefFurnListBean steelRefFurnListBean : data2List) {
            if ( TextUtils.isEmpty(steelRefFurnListBean.getModelNumber())
                    || TextUtils.isEmpty(steelRefFurnListBean.getCalciumTreatmentSituation())) {
                dataHasNull = true;
            }
        }
        if (dataHasNull) {
            toast("请填写精炼厂数据");
            return false;
        }
        for (FactoryDetailBean.SteelLadleListBean steelLadleListBean : data3List) {
            if (TextUtils.isEmpty(steelLadleListBean.getCapacity()) || steelLadleListBean.getCastingDateTime() == null
                    || TextUtils.isEmpty(steelLadleListBean.getTemperatureRange())) {
                dataHasNull = true;
            }
        }
        if (dataHasNull) {
            toast("请填写钢包数据");
            return false;
        }
        return true;
    }

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

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

    @Subscribe
    public void finish(AddUserDataEvent event) {
        finish();
    }
}
