package com.philisense.rdgo.ui.out;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.philisense.rdgo.R;
import com.philisense.rdgo.adapter.OutReplaceAddAdapter;
import com.philisense.rdgo.adapter.OutReplaceDelteAdapter;
import com.philisense.rdgo.base.BaseActivity;
import com.philisense.rdgo.bean.OError;
import com.philisense.rdgo.bean.response.BoxInfoBean;
import com.philisense.rdgo.bean.response.OrderDetailBean;
import com.philisense.rdgo.databinding.ActivityOutReplaceOrderBinding;
import com.philisense.rdgo.http.RequestImpl;
import com.philisense.rdgo.util.CodeParsingUtil;
import com.philisense.rdgo.viewModel.OutReplaceOrderViewModel;
import com.scandecode.ScanDecode;
import com.scandecode.inf.ScanInterface;

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

public class OutReplaceOrderActivity extends BaseActivity<ActivityOutReplaceOrderBinding> implements Toolbar.OnMenuItemClickListener {

    // 本页面扫描选项
    enum ScanOption {
        SCAN_OPTION_DELETE,
        SCAN_OPTION_ADD
    }

    public OutReplaceOrderViewModel viewModel;
    private ScanDecode scanDecode;
    private String orderId;

    private ScanOption scanOption;


    private ProgressDialog progressDialog;
    private OutReplaceDelteAdapter outReplaceDelteAdapter;
    private OutReplaceAddAdapter outReplaceAddAdapter;


    public Map<String, String> boxMap; // key 油的 Id，val 无所谓，主要用于判断是否有重复
    public Map<String, String> oilMap; // key 为油种类，val 为 nodeMap 的keys


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_out_replace_order);
        if (getIntent() != null) {
            orderId = getIntent().getStringExtra("orderId");

        }


        bindingView.outReplaceDelteRecycle.setLayoutManager(new LinearLayoutManager(this));
        outReplaceDelteAdapter = new OutReplaceDelteAdapter(this);
        bindingView.outReplaceDelteRecycle.setAdapter(outReplaceDelteAdapter);


        bindingView.outReplaceAddRecycle.setLayoutManager(new LinearLayoutManager(this));
        outReplaceAddAdapter = new OutReplaceAddAdapter(this);
        bindingView.outReplaceAddRecycle.setAdapter(outReplaceAddAdapter);


        // 初始化各类弹窗
        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("提示");
        progressDialog.setMessage("读取中");

        // 初始化箱字典
        boxMap = new HashMap<>();

        // 初始化 toolbar
        Toolbar toolbar = bindingView.include.toolbar;
        toolbar.setTitle("已出库扫码");
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                showExitAlert();
            }
        });
        toolbar.setOnMenuItemClickListener(this);

        // 初始化扫描类型
        scanOption = ScanOption.SCAN_OPTION_DELETE;

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


        viewModel = new OutReplaceOrderViewModel(this);

        initOrderDetail();

        scanDecode.getBarCode(new ScanInterface.OnScanListener() {
            @Override
            public void getBarcode(String s) {
                scanDecode.stopScan();
                s = s.substring(s.lastIndexOf("/") + 1);
                // 可操作状态（订单未配送）
                if (scanOption == ScanOption.SCAN_OPTION_ADD) {
                    // 添加方法
                    getAdd(CodeParsingUtil.boxParasing(s));
                } else {
                    // 删除方法
                    getDelte(CodeParsingUtil.boxParasing(s));

                }

            }
        });


    }


    @Override
    public boolean onMenuItemClick(MenuItem item) {
        scanOption = ScanOption.SCAN_OPTION_DELETE;

        return true;
    }

    int starts;

    public void initOrderDetail() {


        viewModel.getOrderDetail(orderId, new RequestImpl<OrderDetailBean>() {
            @Override
            public void loadSuccess(OrderDetailBean bean) {
                bindingView.setOder(bean);


                getZL(bean);


                starts = bean.getData().getStatus();
                if (starts == 0) {
                    bindingView.orderCompleteButton.setVisibility(View.GONE);
                    new AlertDialog.Builder(OutReplaceOrderActivity.this).setTitle("该订单未配送")
                            .setPositiveButton("确定", null)
                            .show();

                }

                showContentView();


            }

            @Override
            public void loadFailed(OError error) {
                showError(error);
            }
        });

        bindingView.orderCompleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                check();
            }
        });

        myDelte = new ArrayList<>();
        myAdd = new ArrayList<>();
        oilMap = new HashMap<>();


        outReplaceAddAdapter.setOnClickListener(new OutReplaceAddAdapter.OnItemClickListener() {
            @Override
            public void onClick() {
                bindingView.addLin.setBackgroundColor(Color.parseColor("#ffffff"));
                bindingView.delteLin.setBackgroundColor(Color.parseColor("#dddddd"));
                scanOption = ScanOption.SCAN_OPTION_ADD;
            }

            @Override
            public void btnOnClick(int postion, String boxId) {
                myAdd.remove(postion);
                outReplaceAddAdapter.setData(myAdd);
                boxMap.remove(boxId);
            }
        });


        outReplaceDelteAdapter.setOnClickListener(new OutReplaceDelteAdapter.OnItemClickListener() {
            @Override
            public void onClick() {
                bindingView.delteLin.setBackgroundColor(Color.parseColor("#ffffff"));
                bindingView.addLin.setBackgroundColor(Color.parseColor("#dddddd"));
                scanOption = ScanOption.SCAN_OPTION_DELETE;
            }

            @Override
            public void btnOnClick(int postion, String boxId) {

                myDelte.remove(postion);
                outReplaceDelteAdapter.setData(myDelte);
                boxMap.remove(boxId);
            }
        });


        bindingView.outReplaceAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                scanOption = ScanOption.SCAN_OPTION_ADD;
                tan(1);
                bindingView.addLin.setBackgroundColor(Color.parseColor("#ffffff"));
                bindingView.delteLin.setBackgroundColor(Color.parseColor("#dddddd"));

            }
        });


        bindingView.outReplaceDelte.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                scanOption = ScanOption.SCAN_OPTION_DELETE;

                tan(2);
                bindingView.delteLin.setBackgroundColor(Color.parseColor("#ffffff"));
                bindingView.addLin.setBackgroundColor(Color.parseColor("#dddddd"));
                scanOption = ScanOption.SCAN_OPTION_DELETE;

            }
        });

        bindingView.addLin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bindingView.addLin.setBackgroundColor(Color.parseColor("#ffffff"));
                bindingView.delteLin.setBackgroundColor(Color.parseColor("#dddddd"));
                scanOption = ScanOption.SCAN_OPTION_ADD;

            }
        });

        bindingView.delteLin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bindingView.delteLin.setBackgroundColor(Color.parseColor("#ffffff"));
                bindingView.addLin.setBackgroundColor(Color.parseColor("#dddddd"));
                scanOption = ScanOption.SCAN_OPTION_DELETE;

            }
        });

        bindingView.outReplaceBtadd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bindingView.addLin.setBackgroundColor(Color.parseColor("#ffffff"));
                bindingView.delteLin.setBackgroundColor(Color.parseColor("#dddddd"));
                scanOption = ScanOption.SCAN_OPTION_ADD;

            }
        });


        bindingView.outReplaceBtdle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bindingView.delteLin.setBackgroundColor(Color.parseColor("#ffffff"));
                bindingView.addLin.setBackgroundColor(Color.parseColor("#dddddd"));
                scanOption = ScanOption.SCAN_OPTION_DELETE;

            }
        });

//

    }

    private void tan(final int a) {
        final EditText editText = new EditText(OutReplaceOrderActivity.this);

        AlertDialog.Builder builder = new AlertDialog.Builder(OutReplaceOrderActivity.this);
        builder.setView(editText);
        builder.setTitle("提示");
        builder.setMessage("请输入箱码");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String s = editText.getText().toString();
                if (!"".equals(s)) {
                    if (a == 1) {
                        getAdd(s);
                    } else {
                        getDelte(s);
                    }


                }
            }
        });
        builder.setNegativeButton("取消", null);
        AlertDialog alertDialog = builder.create();
        alertDialog.show();

    }


    private List<String> zhonglei = new ArrayList();

    private void getZL(OrderDetailBean bean) {
        int a = bean.getData().getProduct().size();
//
        for (int i = 0; i < a; i++) {
            zhonglei.add(bean.getData().getProduct().get(i).getProductCode());

            oilMap.put(bean.getData().getProduct().get(i).getProductCode(), "2");
        }


    }


    /**
     * 处理 barcode
     *
     * @param s barcode
     */
    private List<BoxInfoBean.DataBean> myDelte;

    public void getDelte(String s) {
        // 如果已经存在该 key，提示用户已经有这个箱子录入了
        if (boxMap.containsKey(s)) {
            Snackbar.make(bindingView.orderRootLayout, "该箱已经录入（" + s + "）", Snackbar.LENGTH_LONG).show();
            return;
        }


        if (!progressDialog.isShowing()) {
            progressDialog.show();
            viewModel.getBoxInfo(s, new RequestImpl<BoxInfoBean>() {
                @Override
                public void loadSuccess(BoxInfoBean bean) {
                    progressDialog.dismiss();

                    Checkd(bean, s);
                }

                @Override
                public void loadFailed(OError error) {
                    progressDialog.dismiss();
                    Snackbar.make(bindingView.orderRootLayout, error.getErrorMsg(), Snackbar.LENGTH_LONG).show();
                }
            });
        }
    }


    private void Checkd(BoxInfoBean bean, String boxId) {

        if (bean.getData().getStatus() != 0) {


            if (oilMap.containsKey(bean.getData().getTypeCode()) && !boxMap.containsKey(boxId)) {
                boxMap.put(boxId, "1");
                bean.getData().setBoxId(boxId);
                myDelte.add(bean.getData());

                outReplaceDelteAdapter.setData(myDelte);
//        bindingView.outReplaceDelteRecycle.refreshComplete();

            } else {
                Snackbar.make(bindingView.orderRootLayout, "订单中不存在该品种或已经录入", Snackbar.LENGTH_LONG).show();
            }

        } else {
            Snackbar.make(bindingView.orderRootLayout, "该箱不是出库状态", Snackbar.LENGTH_LONG).show();
        }

    }


    /**
     * 处理 barcode
     *
     * @param s barcode
     */
    private List<BoxInfoBean.DataBean> myAdd;

    public void getAdd(String s) {
        // 如果已经存在该 key，提示用户已经有这个箱子录入了
        if (boxMap.containsKey(s)) {
            Snackbar.make(bindingView.orderRootLayout, "该箱已经录入（" + s + "）", Snackbar.LENGTH_LONG).show();
            return;
        }

        if (!progressDialog.isShowing()) {
            progressDialog.show();
            viewModel.getBoxInfo(s, new RequestImpl<BoxInfoBean>() {
                @Override
                public void loadSuccess(BoxInfoBean bean) {
                    progressDialog.dismiss();

                    Checka(bean, s);
                }

                @Override
                public void loadFailed(OError error) {
                    progressDialog.dismiss();
                    Snackbar.make(bindingView.orderRootLayout, error.getErrorMsg(), Snackbar.LENGTH_LONG).show();
                }
            });
        }
    }


    private void Checka(BoxInfoBean bean, String boxId) {


        if (bean.getData().getStatus() == 0) {

            if (oilMap.containsKey(bean.getData().getTypeCode()) && !boxMap.containsKey(boxId)) {


                boxMap.put(boxId, "1");
                bean.getData().setBoxId(boxId);
                myAdd.add(bean.getData());

                outReplaceAddAdapter.setData(myAdd);
//            bindingView.outReplaceAddRecycle.refreshComplete();

            } else {
                Snackbar.make(bindingView.orderRootLayout, "订单中不存在该品种或已经录入", Snackbar.LENGTH_LONG).show();
            }

        } else {
            Snackbar.make(bindingView.orderRootLayout, "该箱已出库", Snackbar.LENGTH_LONG).show();
        }

    }

    /**
     * 确认信息
     */
    public void check() {
        new AlertDialog.Builder(this).setTitle("确认要更改吗？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                        onComplete();

                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    /**
     * 完成订单
     */


    public void onComplete() {
//        final ProgressDialog dialog = ProgressDialog.show(OutReplaceOrderActivity.this, "提示", "正在录入系统..");


        int a = myAdd.size();
        int b = myDelte.size();
        if (a == b) {

            int c = zhonglei.size();
            for (int i = 0; i < c; i++) {
                String s = zhonglei.get(i);
                int d = 0;
                int e = 0;
                for (int f = 0; f < a; f++) {
                    if (s.equals(myAdd.get(f).getTypeCode())) {
                        d++;
                    }
                }

                for (int g = 0; g < b; g++) {
                    if (s.equals(myDelte.get(g).getTypeCode())) {
                        e++;
                    }
                }

                if (d != e) {
                    Snackbar.make(bindingView.orderRootLayout, "品种数量不对等", Snackbar.LENGTH_LONG).show();
//                    break;
                    return;
                }

            }


            viewModel.submitOrder(myAdd, myDelte, orderId, new RequestImpl<String>() {
                @Override
                public void loadSuccess(String bean) {

//                    dialog.dismiss();
                    Toast.makeText(OutReplaceOrderActivity.this, bean, Toast.LENGTH_LONG).show();
                    finish();


                }

                @Override
                public void loadFailed(OError error) {
//                    dialog.dismiss();
                    Toast.makeText(OutReplaceOrderActivity.this, error.getErrorMsg(), Toast.LENGTH_LONG).show();
                }
            });


        } else {
            Snackbar.make(bindingView.orderRootLayout, "增删数量不对等", Snackbar.LENGTH_LONG).show();
        }

    }


    public static void start(Activity context, String orderId) {
        Intent intent = new Intent(context, OutReplaceOrderActivity.class);
        intent.putExtra("orderId", orderId);
        ActivityCompat.startActivity(context, intent, null);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            scanDecode.onDestroy();
        } catch (Exception e) {
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            showExitAlert();
        }
        return false;
    }

    /**
     * 退出提醒
     */
    private void showExitAlert() {
        new AlertDialog.Builder(this).setTitle("确认要返回吗？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }
}
