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

/**
 * 用户数据采集，添加炼钢厂
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class MesChooseFactoryAddActivity 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;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        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);
    }


    @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(MesChooseFactoryAddActivity.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, R.id.rl_factory})
    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;
            case R.id.rl_factory:
                if (!checkParam()) {
                    return;
                }
                data.setSteelmakingWorksCode(null);
                Map<String, Object> param = getParam();
                startActivity(MesChooseMachineAddActivity.class,"from","1"
                ,"data",JSON.toJSONString(data),"factory",JSON.toJSONString(param));
                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;
        }
        Map<String, Object> param = getParam();
        showLoading();
        RtfUtils.getMesRtf().factoryAdd("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("添加成功");
                EventBus.getDefault().post(new AddFactoryEvent());
                finish();
            }
        });
    }

    private Map<String, Object> getParam() {
        Map<String, Object> param = WorkUtils.simpleParam();
        String name = etName.getText().toString();
        String sum = etSum.getText().toString();
        String type = etType.getText().toString();
        JSONObject steelWorks = new JSONObject();
        steelWorks.put("steelmakingWorksName", name);
        steelWorks.put("annualOutput", sum);
        steelWorks.put("steelGrade", type);
        steelWorks.put("customerUserCode", data.getCustomerUserCode());
        param.put("steelWorks", steelWorks);
        param.put("steelRefFurnList", data2List);
        param.put("steelLadleList", data3List);
        param.put("steelFurnList", data1List);
        return param;
    }

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