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

import android.os.Bundle;
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.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
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.RefreshMachineEvent;
import com.wd.workoffice.bean.mesBean.MachineDetailBean;
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.UserDataMachineAdapter;
import com.wd.workoffice.util.WorkUtils;

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

import java.util.ArrayList;
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 io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 用户数据采集，
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class MesChooseMachineModifyActivity extends WorkToolBarActivity {
    @BindView(R.id.tv_machine_name)
    EditText tvMachineName;
    @BindView(R.id.tv_machine_type)
    EditText tvMachineType;
    @BindView(R.id.tv_section)
    EditText tvSection;
    @BindView(R.id.tv_steel_type)
    EditText tvSteelType;
    @BindView(R.id.tv_speed)
    EditText tvSpeed;
    @BindView(R.id.rl_middle)
    RelativeLayout rlMiddle;
    @BindView(R.id.tv_middle1)
    EditText tvMiddle1;
    @BindView(R.id.tv_middle2)
    EditText tvMiddle2;
    @BindView(R.id.tv_middle3)
    EditText tvMiddle3;
    @BindView(R.id.tv_middle4)
    EditText tvMiddle4;
    @BindView(R.id.tv_middle5)
    EditText tvMiddle5;
    @BindView(R.id.tv_middle6)
    EditText tvMiddle6;
    @BindView(R.id.tv_middle7)
    EditText tvMiddle7;
    @BindView(R.id.tv_middle8)
    EditText tvMiddle8;
    @BindView(R.id.ll_middle)
    LinearLayout llMiddle;
    @BindView(R.id.rl_cover)
    RelativeLayout rlCover;
    @BindView(R.id.tv_cover1)
    EditText tvCover1;
    @BindView(R.id.tv_cover2)
    EditText tvCover2;
    @BindView(R.id.tv_cover3)
    EditText tvCover3;
    @BindView(R.id.tv_cover4)
    TextView tvCover4;
    @BindView(R.id.rl_cover4)
    RelativeLayout rlCover4;
    @BindView(R.id.ll_cover)
    LinearLayout llCover;
    @BindView(R.id.rl_protection)
    RelativeLayout rlProtection;
    @BindView(R.id.tv_protection1)
    EditText tvProtection1;
    @BindView(R.id.tv_protection2)
    EditText tvProtection2;
    @BindView(R.id.tv_protection3)
    EditText tvProtection3;
    @BindView(R.id.tv_protection4)
    TextView tvProtection4;
    @BindView(R.id.rl_protection4)
    RelativeLayout rlProtection4;
    @BindView(R.id.ll_protection)
    LinearLayout llProtection;
    @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.rv_data5)
    RecyclerView rvData5;
    @BindView(R.id.tv_add5)
    TextView tvAdd5;
    @BindView(R.id.rv_data4)
    RecyclerView rvData4;
    @BindView(R.id.tv_add4)
    TextView tvAdd4;
    @BindView(R.id.rv_data6)
    RecyclerView rvData6;
    @BindView(R.id.tv_add6)
    TextView tvAdd6;
    @BindView(R.id.rl_add)
    RelativeLayout rlAdd;
    @BindView(R.id.rv_data7)
    RecyclerView rvData7;
    @BindView(R.id.tv_add7)
    TextView tvAdd7;
    private UserDataMachineAdapter data1Adapter;
    private UserDataMachineAdapter data2Adapter;
    private UserDataMachineAdapter data3Adapter;
    private UserDataMachineAdapter data4Adapter;
    private MachineDetailBean machineDetailBean;
    private List<String> data1List;
    private List<String> data2List;
    private List<String> data3List;
    private List<String> data4List;
    private UserDataMachineAdapter data5Adapter;
    private UserDataMachineAdapter data6Adapter;
    private UserDataMachineAdapter data7Adapter;
    private List<String> data5List;
    private List<String> data6List;
    private List<String> data7List;
    private boolean canFinish;
    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));
        rvData4.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rvData5.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rvData6.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rvData7.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<>();
        data4List = new ArrayList<>();
        data5List = new ArrayList<>();
        data6List = new ArrayList<>();
        data7List = new ArrayList<>();
        data1Adapter = new UserDataMachineAdapter(R.layout.item_machine, data1List);
        data2Adapter = new UserDataMachineAdapter(R.layout.item_machine, data2List);
        data3Adapter = new UserDataMachineAdapter(R.layout.item_machine, data3List);
        data4Adapter = new UserDataMachineAdapter(R.layout.item_machine, data4List);
        data5Adapter = new UserDataMachineAdapter(R.layout.item_machine, data5List);
        data6Adapter = new UserDataMachineAdapter(R.layout.item_machine, data6List);
        data7Adapter = new UserDataMachineAdapter(R.layout.item_machine, data7List);
        data1Adapter.bindToRecyclerView(rvData1);
        data2Adapter.bindToRecyclerView(rvData2);
        data3Adapter.bindToRecyclerView(rvData3);
        data4Adapter.bindToRecyclerView(rvData4);
        data5Adapter.bindToRecyclerView(rvData5);
        data6Adapter.bindToRecyclerView(rvData6);
        data7Adapter.bindToRecyclerView(rvData7);
        getMachineData(data.getContinuousCasterCode());
    }


    private void getMachineData(String code) {
        Map<String, Object> param = WorkUtils.simpleParam();
        param.put("continuousCasterCode", code);
        RtfUtils.getMesRtf().machineDetail("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;
                }
                machineDetailBean = JSON.parseObject(data.getData().toString(), MachineDetailBean.class);
                MachineDetailBean.CastInfoBean castInfo = machineDetailBean.getCastInfo();
                if (castInfo != null) {
                    tvMachineType.setText(castInfo.getContinuousCasterType());
                    tvMachineName.setText(castInfo.getContinuousCasterName());
                    tvSection.setText(castInfo.getFractureSurface());
                    tvSteelType.setText(castInfo.getSteelGrade());
                    tvSpeed.setText(castInfo.getCastingSpeed());
                }
                MachineDetailBean.CastLadleBean castLadle = machineDetailBean.getCastLadle();
                if (castLadle != null) {
                    tvMiddle1.setText(castLadle.getCapacity());
                    tvMiddle2.setText(castLadle.getLifeSpan());
//                    tvMiddle3.setText(castLadle.getLadleCode());
                    tvMiddle4.setText(castLadle.getLiquidLevel());
                    tvMiddle5.setText(castLadle.getLiquidSteelTemperature());
                    tvMiddle6.setText(castLadle.getBakingMethod());
                    tvMiddle7.setText(castLadle.getBakingTemperature());
                    tvMiddle8.setText(String.valueOf(castLadle.getBakingDateTime()));
                }
//                MachineDetailBean.CovAgentBean covAgent = machineDetailBean.getCovAgent();
//                if (covAgent != null) {
//                    tvCover1.setText(covAgent.getLadleCoveringAgentName());
//                    tvCover2.setText(covAgent.getAcidAlkaliDegree());
//                    tvCover3.setText(covAgent.getChemicalComposition());
//                    tvCover4.setText(covAgent.getSupplierName());
//                }
//                MachineDetailBean.MouldFluBean mouldFlu = machineDetailBean.getMouldFlu();
//                if (mouldFlu != null) {
//                    tvProtection1.setText(mouldFlu.getMouldFluxesName());
//                    tvProtection2.setText(mouldFlu.getAcidAlkaliDegree());
//                    tvProtection3.setText(mouldFlu.getChemicalComposition());
//                    tvProtection4.setText(mouldFlu.getSupplierName());
//                }
                changeList();
            }
        });
    }

    private void changeList() {
        data1List.clear();
        data2List.clear();
        data3List.clear();
        data4List.clear();
        data5List.clear();
        data6List.clear();
        data7List.clear();
        if (machineDetailBean.getProductList() != null) {
            for (MachineDetailBean.ProductListBean productListBean : machineDetailBean.getProductList()) {
                data1List.add(productListBean.getProductsName());
            }
        }
        data1Adapter.notifyDataSetChanged();
        if (machineDetailBean.getSupplyList() != null) {
            for (MachineDetailBean.SupplyListBean productListBean : machineDetailBean.getSupplyList()) {
                data2List.add(productListBean.getProductsName());
            }
        }
        data2Adapter.notifyDataSetChanged();
        if (machineDetailBean.getOtherSupList() != null) {
            for (MachineDetailBean.OtherSupListBean productListBean : machineDetailBean.getOtherSupList()) {
                data3List.add(productListBean.getSupplierName());
            }
        }
        data3Adapter.notifyDataSetChanged();
        if (machineDetailBean.getOtherLadleList() != null) {
            for (MachineDetailBean.OtherLadleListBean productListBean : machineDetailBean.getOtherLadleList()) {
                data4List.add(productListBean.getRefractoryName());
            }
        }
        data4Adapter.notifyDataSetChanged();
        if (machineDetailBean.getStockList() != null) {
            for (MachineDetailBean.StockListBean productListBean : machineDetailBean.getStockList()) {
                data5List.add(productListBean.getProductsName());
            }
        }
        data5Adapter.notifyDataSetChanged();
        if (machineDetailBean.getSettleList() != null) {
            for (MachineDetailBean.SettleListBean productListBean : machineDetailBean.getSettleList()) {
                data6List.add(productListBean.getSettlementMethod());
            }
        }
        data6Adapter.notifyDataSetChanged();
        if (machineDetailBean.getSpeeds() != null) {
            for (MachineDetailBean.SpeedsBean productListBean : machineDetailBean.getSpeeds()) {
                if (null == productListBean.getCovAgent()) {
                    productListBean.setCovAgent(new MachineDetailBean.SpeedsBean.CovAgentBean());
                }
                if (null == productListBean.getMouldFlu()) {
                    productListBean.setMouldFlu(new MachineDetailBean.SpeedsBean.MouldFluBean());
                }
                data7List.add(productListBean.getSteelGrade());
            }
        }
        data7Adapter.notifyDataSetChanged();
    }

    @Override
    protected void initEvent() {
        data1Adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(MesThreeModifyActivity.class, "data", JSON.toJSONString(machineDetailBean.getProductList().get(position))
                        , "user", data.getCustomerUserCode());
            }
        });
        data2Adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(MesSupplierModifyActivity.class, "data", JSON.toJSONString(machineDetailBean.getSupplyList().get(position))
                        , "user", data.getCustomerUserCode());
            }
        });
        data3Adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(MesOtherSupplierModifyActivity.class, "data", JSON.toJSONString(machineDetailBean.getOtherSupList().get(position))
                        , "user", data.getCustomerUserCode());
            }
        });
        data4Adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(MesPackageModifyActivity.class, "data", JSON.toJSONString(machineDetailBean.getOtherLadleList().get(position))
                        , "user", data.getCustomerUserCode());

            }
        });
        data5Adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(MesStockModifyActivity.class,
                        "id", data.getCustomerUserCode(),
                        "data", JSON.toJSONString(machineDetailBean.getStockList().get(position)));
            }
        });
        data6Adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(MesMiddleModifyActivity.class, "data", JSON.toJSONString(machineDetailBean.getSettleList().get(position))
                        , "user", data.getCustomerUserCode());
            }
        });
        data7Adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(MesSpeedModifyActivity.class, "data", JSON.toJSONString(machineDetailBean.getSpeeds().get(position))
                        , "user", data.getCustomerUserCode());
            }
        });
    }

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


    @OnClick({R.id.rl_cover4, R.id.rl_protection4, R.id.tv_add2,
            R.id.tv_add7, R.id.tv_add5, R.id.tv_add6, R.id.tv_add1, R.id.tv_add3,
            R.id.tv_add4})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_cover4:
                startActivityForResult(MesChooseClientActivity.class,
                        10001, "from", "1");
                break;
            case R.id.rl_protection4:
                startActivityForResult(MesChooseClientActivity.class,
                        10002, "from", "1");
                break;
            case R.id.tv_add1:
                if (machineDetailBean == null) {
                    toast("数据加载中，请稍后");
                    return;
                }
                startActivity(MesThreeAddActivity.class, "continuousCasterCode", data.getContinuousCasterCode()
                        , "user", data.getCustomerUserCode());
                break;
            case R.id.tv_add7:
                if (machineDetailBean == null) {
                    toast("数据加载中，请稍后");
                    return;
                }
                startActivity(MesSpeedAddActivity.class, "continuousCasterCode", data.getContinuousCasterCode()
                        , "user", data.getCustomerUserCode());
                break;
            case R.id.tv_add2:
                if (machineDetailBean == null) {
                    toast("数据加载中，请稍后");
                    return;
                }
                startActivity(MesSupplierAddActivity.class, "continuousCasterCode", data.getContinuousCasterCode()
                        , "user", data.getCustomerUserCode());
                break;
            case R.id.tv_add3:
                if (machineDetailBean == null) {
                    toast("数据加载中，请稍后");
                    return;
                }
                startActivity(MesOtherSupplierAddActivity.class, "continuousCasterCode", data.getContinuousCasterCode()
                        , "user", data.getCustomerUserCode());
                break;
            case R.id.tv_add4:
                if (machineDetailBean == null) {
                    toast("数据加载中，请稍后");
                    return;
                }
                startActivity(MesPackageAddActivity.class, "continuousCasterCode", data.getContinuousCasterCode()
                        , "user", data.getCustomerUserCode());
                break;
            case R.id.tv_add5:
                if (machineDetailBean == null) {
                    toast("数据加载中，请稍后");
                    return;
                }
                startActivity(MesStockAddActivity.class,
                        "continuousCasterCode", data.getContinuousCasterCode()
                        , "id", data.getCustomerUserCode());
                break;
            case R.id.tv_add6:
                if (machineDetailBean == null) {
                    toast("数据加载中，请稍后");
                    return;
                }
                startActivity(MesMiddleAddActivity.class, "continuousCasterCode",
                        data.getContinuousCasterCode()
                        , "user", data.getCustomerUserCode());
                break;
            case R.id.rl_middle:
                if (llMiddle.getVisibility() == View.VISIBLE) {
                    llMiddle.setVisibility(View.GONE);
                } else {
                    llMiddle.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.rl_cover:
                if (llCover.getVisibility() == View.VISIBLE) {
                    llCover.setVisibility(View.GONE);
                } else {
                    llCover.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.rl_protection:
                if (llProtection.getVisibility() == View.VISIBLE) {
                    llProtection.setVisibility(View.GONE);
                } else {
                    llProtection.setVisibility(View.VISIBLE);
                }
                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:
                changeSimple();
                submitMachine();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void changeSimple() {
        MachineDetailBean.CastInfoBean castInfo = machineDetailBean.getCastInfo();
        if (castInfo == null) {
            castInfo = new MachineDetailBean.CastInfoBean();
            machineDetailBean.setCastInfo(castInfo);
        }
        castInfo.setContinuousCasterName(tvMachineName.getText().toString());
        castInfo.setContinuousCasterType(tvMachineType.getText().toString());
        castInfo.setFractureSurface(tvSection.getText().toString());
        castInfo.setSteelGrade(tvSteelType.getText().toString());
        castInfo.setCastingSpeed(tvSpeed.getText().toString());

        MachineDetailBean.CastLadleBean castLadle = machineDetailBean.getCastLadle();
        if (castLadle == null) {
            castLadle = new MachineDetailBean.CastLadleBean();
            machineDetailBean.setCastLadle(castLadle);
        }
        castLadle.setCapacity(tvMiddle1.getText().toString());
        castLadle.setLifeSpan(tvMiddle2.getText().toString());
//        castLadle.setLadleCode(tvMiddle3.getText().toString());
        castLadle.setLiquidLevel(tvMiddle4.getText().toString());
        castLadle.setLiquidSteelTemperature(tvMiddle5.getText().toString());
        castLadle.setBakingMethod(tvMiddle6.getText().toString());
        castLadle.setBakingTemperature(tvMiddle7.getText().toString());
        if (!TextUtils.isEmpty(tvMiddle8.getText().toString())) {
            castLadle.setBakingDateTime(tvMiddle8.getText().toString());
        }

//        MachineDetailBean.CovAgentBean covAgent = machineDetailBean.getCovAgent();
//        if (covAgent == null) {
//            covAgent = new MachineDetailBean.CovAgentBean();
//            machineDetailBean.setCovAgent(covAgent);
//        }
//        covAgent.setLadleCoveringAgentName(tvCover1.getText().toString());
//        covAgent.setAcidAlkaliDegree(tvCover2.getText().toString());
//        covAgent.setChemicalComposition(tvCover3.getText().toString());
//        covAgent.setSupplierName(tvCover4.getText().toString());
//
//        MachineDetailBean.MouldFluBean mouldFlu = machineDetailBean.getMouldFlu();
//        if (mouldFlu == null) {
//            mouldFlu = new MachineDetailBean.MouldFluBean();
//            machineDetailBean.setMouldFlu(mouldFlu);
//        }
//        mouldFlu.setMouldFluxesName(tvProtection1.getText().toString());
//        mouldFlu.setAcidAlkaliDegree(tvProtection2.getText().toString());
//        mouldFlu.setChemicalComposition(tvProtection3.getText().toString());
//        mouldFlu.setSupplierName(tvProtection4.getText().toString());
    }

    private void submitMachine() {
        showLoading();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JSON.toJSONString(machineDetailBean));
        RtfUtils.getMesRtf().machineAdd("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("编辑成功");
                finish();
                EventBus.getDefault().post(new RefreshMachineEvent());
            }
        });
    }


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

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

    @Subscribe
    public void refresh(RefreshMachineEvent event) {
        getMachineData(data.getContinuousCasterCode());
    }

}
