package com.philisense.rdgo.ui.putIn;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
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.Toolbar;
import android.text.InputType;
import android.text.method.DigitsKeyListener;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.philisense.rdgo.R;
import com.philisense.rdgo.base.BaseActivity;
import com.philisense.rdgo.bean.OError;
import com.philisense.rdgo.bean.response.OrderDetailBean;
import com.philisense.rdgo.databinding.ActivityPutInOrderBinding;
import com.philisense.rdgo.http.RequestImpl;
import com.philisense.rdgo.ui.putOut.PutOutOrderActivity;
import com.philisense.rdgo.util.Constant;
import com.philisense.rdgo.util.TreeNodeInsertListener;
import com.philisense.rdgo.view.OrderInViewHolder;
import com.philisense.rdgo.view.OrderViewHolder;
import com.philisense.rdgo.viewModel.PutInOrderViewModel;
import com.unnamed.b.atv.model.TreeNode;
import com.unnamed.b.atv.view.AndroidTreeView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.functions.Consumer;

public class PutInOrderActivity extends BaseActivity<ActivityPutInOrderBinding> {

    public PutInOrderViewModel viewModel;
    public AndroidTreeView tView;
    private String orderId;

    private TreeNodeInsertListener insertListener;
    public Map<String, TreeNode> nodeMap; // key 为油种类+订单号，val 为 node
    public Map<String, List<String>> oilMap; // key 为油种类，val 为 nodeMap 的keys
    public Map<String, TreeNode> boxMap; // key 油的 Id，val 无所谓，主要用于判断是否有重复

    private ProgressDialog progressDialog;
    private AlertDialog alertDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_put_in_order);
        if (getIntent() != null) {
            orderId = getIntent().getStringExtra("orderId");
        }
        // 初始化箱字典
        boxMap = new HashMap<>();

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

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

        // 初始化 viewModel
        viewModel = new PutInOrderViewModel(this);
        // 监听提交按钮
        viewModel.completeAvailable.subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                bindingView.orderCompleteButton.setEnabled(aBoolean);
            }
        });

        // 初始化提交按钮为空
        bindingView.orderCompleteButton.setEnabled(false);

        initOrderDetail();
    }

    /**
     * 初始化订单详情
     */
    public void initOrderDetail() {
        viewModel.getOrderDetail(orderId, new RequestImpl<OrderDetailBean>() {
            @Override
            public void loadSuccess(OrderDetailBean bean) {
                if (bean.getData().getStatus() == 1) {
                    bindingView.setOder(bean);
                    initNodeView(bean.getData().getProduct());
                    showContentView();
                }else {
                    showError(new OError(Constant.SystemErrorCode,"配送单未出货"));
                }
            }

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

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

    /**
     * 初始化树
     */
    public void initNodeView(List<OrderDetailBean.DataBean.ProductBean> productBeanList) {
        nodeMap = new HashMap<>();
        oilMap = new HashMap<>();

        TreeNode root = TreeNode.root();

        for (OrderDetailBean.DataBean.ProductBean bean : productBeanList) {
            OrderInViewHolder viewHolder = new OrderInViewHolder(this);
            TreeNode child1 = new TreeNode(new OrderInViewHolder.OrderInfo(bean.getTypeName(),
                    bean.getOrderChildId(),
                    bean.getOrderId(),
                    bean.get_id(),
                    bean.getSendId(),
                    bean.getName(),
                    bean.getProductCode(),
                    bean.getSendBox(),
                    bean.getSendBox())).setViewHolder(viewHolder);
            nodeMap.put(bean.getProductCode()+bean.getOrderChildId(),child1);
            // 储存键值
            if (oilMap.containsKey(bean.getProductCode())) {
                oilMap.get(bean.getProductCode()).add(bean.getProductCode()+bean.getOrderChildId());
            }else {
                List<String> list = new ArrayList<>();
                list.add(bean.getProductCode()+bean.getOrderChildId());
                oilMap.put(bean.getProductCode(),list);
            }

            viewHolder.setListenner(new OrderInViewHolder.AddListenner() {
                @Override
                public void add(OrderInViewHolder.OrderInfo orderInfo) {
                    addVirtualBox(viewHolder, orderInfo);
                }
            });

            root.addChildren(child1);
        }

        tView = new AndroidTreeView(this, root);
        tView.setDefaultAnimation(false);
        bindingView.orderRootView.addView(tView.getView());

        viewModel.setRoot(root);
    }

    /**
     * 添加虚拟箱子
     */
    public void addVirtualBox(OrderInViewHolder viewHolder, OrderInViewHolder.OrderInfo orderInfo) {
        final EditText et = new EditText(this);
        et.setInputType(InputType.TYPE_NUMBER_FLAG_SIGNED);
        et.setKeyListener(DigitsKeyListener.getInstance("0123456789"));

        new AlertDialog.Builder(this).setTitle("请输入确认的数量")
                .setView(et)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        onClickBoxInput(et,orderInfo,viewHolder);
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    /**
     * 确认添加箱码
     * @param et 输入框
     * @param orderInfo 订单号
     */
    public void onClickBoxInput(EditText et, OrderInViewHolder.OrderInfo orderInfo, OrderInViewHolder viewHolder) {
        if (isNumeric(et.getText().toString()) && !et.getText().toString().equals("")) {
            int number = Integer.parseInt(et.getText().toString());
            if (number == 0) {
                Toast.makeText(PutInOrderActivity.this, "输入的内容不能为0", Toast.LENGTH_LONG).show();
            } else if (number > orderInfo.getMaxBoxNum()) {
                Toast.makeText(PutInOrderActivity.this, "输入的内容不能超过订单数量", Toast.LENGTH_LONG).show();
            } else {
                viewHolder.addBox(number);
                // 监听添加箱子
                if (insertListener != null) {
                    insertListener.onInsert();
                }
            }
        }else {
            Toast.makeText(this,"输入了非法数值",Toast.LENGTH_LONG).show();
        }
    }

    public boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if( !isNum.matches() ){
            return false;
        }
        return true;
    }


    /**
     * 确认信息
     */
    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(PutInOrderActivity.this,"提示","正在录入系统..");
        dialog.show();
        viewModel.putInAction(orderId, new RequestImpl<String>() {
            @Override
            public void loadSuccess(String bean) {
                dialog.dismiss();
                Toast.makeText(PutInOrderActivity.this,"入库成功",Toast.LENGTH_LONG).show();
                finish();
            }

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

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

    public void setInsertListener(TreeNodeInsertListener insertListener) {
        this.insertListener = insertListener;
    }

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