package com.philisense.rdgo.ui.lineIn;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.xrecyclerview.XRecyclerView;
import com.philisense.rdgo.R;
import com.philisense.rdgo.adapter.digaoAddAdapter;
import com.philisense.rdgo.bean.OError;
import com.philisense.rdgo.bean.response.PileInfoBean;
import com.philisense.rdgo.bean.response.WarehouseBean;
import com.philisense.rdgo.databinding.ActivityLineInBinding;
import com.philisense.rdgo.http.RequestImpl;
import com.philisense.rdgo.ui.putOut.PutOutOrderActivity;
import com.philisense.rdgo.viewModel.LineInViewModel;
import com.scandecode.ScanDecode;
import com.scandecode.inf.ScanInterface;

import java.util.ArrayList;
import java.util.List;

public class LineInActivity extends AppCompatActivity {

    public ActivityLineInBinding mBinding;
    private ScanDecode scanDecode;
    private LineInViewModel viewModel;

    private digaoAddAdapter digaoAddAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_line_in);
        Toolbar toolbar = mBinding.include.toolbar;
        toolbar.setTitle("产线入库");
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                finish();
            }
        });

        viewModel = new LineInViewModel(this);

        // 初始化扫描
        try {
            scanDecode = new ScanDecode(this);
            scanDecode.initService("true");
        } catch (Exception e) {
            Snackbar.make(mBinding.lineInRoot, "本机没有扫码功能", Snackbar.LENGTH_LONG).show();
        }

        scanDecode.getBarCode(new ScanInterface.OnScanListener() {
            @Override
            public void getBarcode(String s) {
                scanDecode.stopScan();
                s = s.substring(s.lastIndexOf("/") + 1);
                getWarehouse(s);

            }
        });


        mBinding.determine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String s = mBinding.edit.getText().toString().trim();
                s = s.substring(s.lastIndexOf("/") + 1);
                getWarehouse(s);
            }
        });


        ShowDialog("", null, null);


    }


    private AlertDialog alertDialog;

    TextView myName;
    TextView myNum;
    TextView myStart;
    TextView myEnd;
    Button see;

    public void ShowDialog(String boxId, List<WarehouseBean.ListBean> mybean, PileInfoBean bean) {


        LineInActivity context = LineInActivity.this;
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.digao, null);

        XRecyclerView myListView = (XRecyclerView) layout.findViewById(R.id.cangku);

        myListView.setLayoutManager(new LinearLayoutManager(this));
        digaoAddAdapter = new digaoAddAdapter(this);
        myListView.setAdapter(digaoAddAdapter);


        myName = layout.findViewById(R.id.name);
        myNum = layout.findViewById(R.id.duoshu);
        myStart = layout.findViewById(R.id.duokaishi);
        myEnd = layout.findViewById(R.id.duokaijieshu);
        see = layout.findViewById(R.id.see_all_box);

        if (bean != null) {
            digaoAddAdapter.setData(mybean);

        }


        TextView quXiao = layout.findViewById(R.id.quxiao);

        quXiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setView(layout);
        alertDialog = builder.create();

    }

    AlertDialog LIEBIAOdialog;

    private void data(String boxId, List<WarehouseBean.ListBean> mybean, PileInfoBean bean) {
        mBinding.edit.setText("");
        if (LIEBIAOdialog != null && LIEBIAOdialog.isShowing()) {
            LIEBIAOdialog.dismiss();
        }
        if (bean != null) {
            digaoAddAdapter.setData(mybean);
            String nama = bean.getData().getName();
            if ("".equals(nama)) {
                myName.setText("产品名称：" + bean.getData().getTypeName());
            } else {
                myName.setText("产品名称：" + nama);
            }


            List<String> s = bean.getData().getBoxIn();
            if (s == null) {
                s = new ArrayList<>();
            }
            int n = s.size();
            myNum.setText("垛总箱数：" + n);

            if (n == 0) {
                myStart.setText("起始箱码：无");
                myEnd.setText("结束箱码：无");
            } else if (n == 1) {
                myStart.setText("起始箱码：" + s.get(0));
                myEnd.setText("结束箱码：无");
            } else {
                myStart.setText("起始箱码：" + s.get(0));
                myEnd.setText("结束箱码：" + s.get(n - 1));
            }
            digaoAddAdapter.setOnClickListener(new digaoAddAdapter.OnItemClickListener() {
                @Override
                public void btnOnClick(String warehouse, String warehouseCode) {
                    check(boxId, warehouse, warehouseCode);
                }
            });

            see.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    AlertDialog.Builder builder = new AlertDialog.Builder(LineInActivity.this);
                    builder.setTitle("箱码列表");

                    /**
                     * 设置内容区域为简单列表项
                     */
                    String[] Items = new String[n];

                    for (int i = 0; i < n; i++) {
                        Items[i] = bean.getData().getBoxIn().get(i);

                    }
                    builder.setItems(Items, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                        }
                    });

                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    LIEBIAOdialog.dismiss();
                                }
                            }
                    );
                    builder.setCancelable(true);
                    LIEBIAOdialog = builder.create();
                    LIEBIAOdialog.show();


                }
            });
        } else {
            myName.setText("无");
            myStart.setText("起始箱码：无");
            myEnd.setText("结束箱码：无");
            myNum.setText("垛总箱数：0");
        }
        if (!alertDialog.isShowing()) {
            alertDialog.show();
        }


    }


    public void getWarehouse(String boxId) {


        viewModel.getWarehouse(new RequestImpl<List<WarehouseBean.ListBean>>() {
            @Override
            public void loadSuccess(List<WarehouseBean.ListBean> bean) {

                getData(boxId, bean);

            }

            @Override
            public void loadFailed(OError error) {
                Snackbar.make(mBinding.lineInRoot, error.getErrorMsg(), Snackbar.LENGTH_LONG).show();
                mBinding.edit.setText("");
            }
        });

    }


    private void getData(String boxId, List<WarehouseBean.ListBean> mybean) {
        viewModel.getPileInfo(boxId, new RequestImpl<PileInfoBean>() {
            @Override
            public void loadSuccess(PileInfoBean bean) {


                //   ShowDialog(boxId, mybean, bean);
                if (isLiving(LineInActivity.this)) {
                    data(boxId, mybean, bean);
                }


            }

            @Override
            public void loadFailed(OError error) {

                Snackbar.make(mBinding.lineInRoot, error.getErrorMsg(), Snackbar.LENGTH_LONG).show();

            }
        });

    }

    /**
     * 确认信息
     */
    public void check(String boxId, String warehouse, String warehouseCode) {

        new AlertDialog.Builder(this).setTitle("确认要入库吗？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (alertDialog != null) {
                            alertDialog.dismiss();

                        }
                        putInOrder(boxId, warehouse, warehouseCode);
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }


    public void putInOrder(String boxId, String warehouse, String warehouseCode) {
        final ProgressDialog dialog = ProgressDialog.show(LineInActivity.this, "提示", "正在录入..");

        viewModel.lineInAction(boxId, warehouse, warehouseCode, new RequestImpl<String>() {
            @Override
            public void loadSuccess(String bean) {
                dialog.dismiss();
                Toast.makeText(LineInActivity.this, "入库成功", Toast.LENGTH_LONG).show();
                finish();
            }

            @Override
            public void loadFailed(OError error) {
                dialog.dismiss();
                Snackbar.make(mBinding.lineInRoot, error.getErrorMsg(), Snackbar.LENGTH_LONG).show();
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            scanDecode.onDestroy();
            if (alertDialog != null) {
                alertDialog.dismiss();

            }

        } catch (Exception e) {
        }
    }

    /**
     * @param context activity
     */
    public static void start(Activity context) {
        Intent intent = new Intent(context, LineInActivity.class);
        ActivityCompat.startActivity(context, intent, null);
    }


    private static boolean isLiving(Activity activity) {

        if (activity == null) {
            Log.d("wisely", "activity == null");
            return false;
        }

        if (activity.isFinishing()) {
            Log.d("wisely", "activity is finishing");
            return false;
        }

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {//android 4.2
//
//            if (activity.isDestroyed()) {
//                Log.d("wisely", "activity is destroy");
//                return false;
//            }
//        }

        return true;
    }
}
