package com.philisense.rdgo.ui.waitPutIn;

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.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.view.View;
import android.widget.Toast;

import com.example.xrecyclerview.XRecyclerView;
import com.philisense.rdgo.R;
import com.philisense.rdgo.adapter.HqtOilAdapter;
import com.philisense.rdgo.bean.LineBean;
import com.philisense.rdgo.bean.OError;
import com.philisense.rdgo.bean.request.addRequestBean;

import com.philisense.rdgo.bean.response.PeopleBean;
import com.philisense.rdgo.bean.response.ProductBean;
import com.philisense.rdgo.bean.response.WhBean;
import com.philisense.rdgo.databinding.ActivityHqttBinding;
import com.philisense.rdgo.db.DBFactory;
import com.philisense.rdgo.db.UserDb;
import com.philisense.rdgo.http.RequestImpl;
import com.philisense.rdgo.http.cache.ACache;
import com.philisense.rdgo.util.Constant;
import com.philisense.rdgo.viewModel.HQTViewModel;
import com.scandecode.ScanDecode;
import com.scandecode.inf.ScanInterface;

import java.io.Serializable;
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;


public class HQTActivity extends AppCompatActivity {

    private ActivityHqttBinding mBinding;
    private HQTViewModel viewModel;
    private ScanDecode scanDecode;
    private HqtOilAdapter adapter;
    private ACache aCache;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_hqtt);

        // toolbar
        Toolbar toolbar = mBinding.include.toolbar;
        toolbar.setTitle("手工归垛");
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        viewModel = new HQTViewModel(this);

        aCache = ACache.get(HQTActivity.this);


        mBinding.recyPin.setLayoutManager(new LinearLayoutManager(this));
        adapter = new HqtOilAdapter(this);
        mBinding.recyPin.setAdapter(adapter);
        mBinding.recyPin.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                mBinding.recyPin.refreshComplete();
            }

            @Override
            public void onLoadMore() {
                mBinding.recyPin.refreshComplete();
            }
        });
        adapter.setOnClickListener(new HqtOilAdapter.OnItemClickListener() {
            @Override
            public void btnOnClick(String s, int postion) {
                myList.remove(postion);
                map.remove(s);
                adapter.setData(myList);
                mBinding.recyPin.refreshComplete();
                mBinding.number.setText("已扫" + myList.size() + "个");
            }
        });

        click();
        getData();

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

        scanDecode.getBarCode(new ScanInterface.OnScanListener() {
            @Override
            public void getBarcode(String s) {
                if (!"".equals(s)) {
                    s = s.substring(s.lastIndexOf("/") + 1);
                    saoma(s);
                }
            }
        });
    }

    private List<String> myList;
    private Map<String, String> map;
    private int number = 0;

    private void saoma(String s) {
        if (issuo == 0) {
            Snackbar.make(mBinding.layout, "请先加锁后再扫瓶码", Snackbar.LENGTH_LONG).show();
            return;
        }
        if (adapter.getItemCount() >= number) {
            Snackbar.make(mBinding.layout, "列表已满，请提交", Snackbar.LENGTH_LONG).show();
            return;
        }


        if (map.containsKey(s)) {
            Snackbar.make(mBinding.layout, "该产品已存在列表中", Snackbar.LENGTH_LONG).show();
            return;
        } else {
            myList.add(s);
            adapter.setData(myList);
            mBinding.recyPin.refreshComplete();
            map.put(s, s);
            mBinding.number.setText("已扫" + myList.size() + "个");
        }
    }

    private void click() {
        myList = new ArrayList<>();
        map = new HashMap();
        mBinding.line.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TanChanxian();
            }
        });

        mBinding.Warehouse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TanCangKu();
            }
        });
        mBinding.team.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                peopleActivity.start(HQTActivity.this, "1", 1);
            }
        });
        mBinding.nextName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                peopleActivity.start(HQTActivity.this, "1", 3);
            }
        });
        mBinding.worker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                peopleActivity.start(HQTActivity.this, "2", 2);
            }
        });
        mBinding.brand.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ProductActivity.start(HQTActivity.this, 100);
            }
        });

        mBinding.gene.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ProductActivity.start(HQTActivity.this, 100);
            }
        });
        mBinding.level.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ProductActivity.start(HQTActivity.this, 100);
            }
        });
        mBinding.capacity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ProductActivity.start(HQTActivity.this, 100);
            }
        });
        mBinding.name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ProductActivity.start(HQTActivity.this, 100);
            }
        });
        mBinding.suo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (issuo == 0) {
                    jiasuo();
                } else {
                    jiesuo();
                }

            }
        });
        mBinding.sub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showAdd();
            }
        });
        mBinding.determine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String s = mBinding.edit.getText().toString();
                if (!"".equals(s)) {
                    s = s.substring(s.lastIndexOf("/") + 1);
                    saoma(s);
                    mBinding.edit.setText("");
                }
            }
        });

    }

    addRequestBean requestBean;

    private void set() {
        requestBean = (addRequestBean) aCache.getAsObject("HQTActivity");
        ProductBean.ListBean b = (ProductBean.ListBean) aCache.getAsObject("HQT");
        if (b != null) {
            mybean = b;
            mBinding.brand.setText(b.getBrand());
            mBinding.level.setText(b.getLevel());
            mBinding.capacity.setText(b.getCapacity());
            mBinding.name.setText(b.getName());
            int gene = b.getGene();
            if (gene == 0) {
                mBinding.gene.setText("是");
            } else if (gene == 1) {
                mBinding.gene.setText("否");
            } else {
                mBinding.gene.setText("其他");
            }

        }


        if (requestBean != null) {
            mBinding.line.setText(requestBean.getLine());
            mBinding.Warehouse.setText(requestBean.getWarehouse());
            warehouse = requestBean.getWarehouse();
            warehouseCode = requestBean.getWarehouseCode();
            if (requestBean.getBoxes().size() > 0) {
                mBinding.team.setText(requestBean.getBoxes().get(0).getOperator());
                peopleName = requestBean.getBoxes().get(0).getOperator();
                peopleCode = requestBean.getBoxes().get(0).getOpPersonAccount();
            }
            mBinding.nextName.setText(requestBean.getConfirmer());
            mBinding.worker.setText(requestBean.getGroupCode());
            mBinding.num.setText(requestBean.getBoxNum() + "");
            number = requestBean.getBoxNum();
        }

    }

    private void add() {
        if (mybean == null) {
            Snackbar.make(mBinding.layout, "产品无信息，请重新选择", Snackbar.LENGTH_LONG).show();
            return;
        }
        if (myList.size() != number) {
            Snackbar.make(mBinding.layout, "产品数量不正确，请检查", Snackbar.LENGTH_LONG).show();
            return;
        }
        ACache aCache = ACache.get(HQTActivity.this);
        String accessToken = aCache.getAsString(Constant.ACCESSTOKEN);
        UserDb userDb = DBFactory.getUserInfo(HQTActivity.this);
        addRequestBean bean = new addRequestBean();
        bean.setAccessToken(accessToken);
        bean.setAccount(userDb.getAccount() == null ? "" : userDb.getAccount());
        bean.setBoxNum(number);
        bean.setName(mybean.getName());
        bean.setTypeName(mybean.getTypeName());
        bean.setBrand(mybean.getBrand());
        bean.setGene(mybean.getGene());
        bean.setLevel(mybean.getLevel());
        bean.setCapacity(mybean.getCapacity());
        bean.setLine(mBinding.line.getText().toString().trim());
        bean.setTypeCode(mybean.getTypeCode());
        bean.setFactory(mybean.getCreatedBy().getFactory());
        bean.setKeepDate(mybean.getKeepDate());
        bean.setUrl(mybean.getUrl());
        bean.setGroupCode(mBinding.worker.getText().toString().trim());
        bean.setSources(mybean.getSources());
        bean.setTechnology(mybean.getTechnology());
        bean.setIngredients(mybean.getIngredients());
        bean.setSourcesCountry(mybean.getSourcesCountry());
        bean.setProductStandard(mybean.getProductStandard());
        bean.setFoodLicense(mybean.getFoodLicense());
        bean.setAddress(mybean.getAddress());
        bean.setConfirmer(mBinding.nextName.getText().toString().trim());
        bean.setWarehouse(warehouse);
        bean.setWarehouseCode(warehouseCode);
        List<addRequestBean.BoxesBean> boxList = new ArrayList<>();
        for (int i = 0; i < myList.size(); i++) {
            addRequestBean.BoxesBean boxesBean = new addRequestBean.BoxesBean();
            boxesBean.setBottleNum(1);
            String id = myList.get(i);
            boxesBean.setBoxId(id);
            boxesBean.setOperator(peopleName);
            boxesBean.setOpPersonAccount(peopleCode);
            addRequestBean.BoxesBean.BottlesBean b = new addRequestBean.BoxesBean.BottlesBean();
            b.setBottleId(id);
            List<addRequestBean.BoxesBean.BottlesBean> list = new ArrayList<>();
            list.add(b);
            boxesBean.setBottles(list);
            boxList.add(boxesBean);
        }
        bean.setBoxes(boxList);
        final ProgressDialog dialog = ProgressDialog.show(HQTActivity.this, "提示", "正在录入系统..");
        viewModel.addpile(bean, new RequestImpl<String>() {
            @Override
            public void loadSuccess(String s) {
                dialog.dismiss();
                Snackbar.make(mBinding.layout, s, Snackbar.LENGTH_LONG).show();
                if (myList.size() > 0) {
                    id = myList.get(0);
                }
                showAddNext();
                myList.clear();
                adapter.setData(myList);
                mBinding.recyPin.refreshComplete();
                mBinding.number.setText("已扫0个");
                aCache.put("HQTActivity", (Serializable) bean);
                aCache.put("HQT", (Serializable) mybean);
            }

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

            }
        });
    }

    private String id = "";

    private void addNext() {
        final ProgressDialog dialog = ProgressDialog.show(HQTActivity.this, "提示", "正在录入系统..");
        viewModel.lineInAction(id, warehouse, warehouseCode, new RequestImpl<String>() {
            @Override
            public void loadSuccess(String bean) {
                id = "";
                dialog.dismiss();
                Snackbar.make(mBinding.layout, "入库成功", Snackbar.LENGTH_LONG).show();
            }

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

            }
        });
    }

    /**
     * 提交提醒
     */
    private void showAdd() {
        new AlertDialog.Builder(this).setTitle("是否待入库？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        add();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    /**
     * 入库提醒
     */
    private void showAddNext() {
        new AlertDialog.Builder(this).setTitle("是否直接入库？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        addNext();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }


    private int issuo = 0;

    private void jiasuo() {
        issuo = 1;
        String aa = mBinding.num.getText().toString().trim();
        if ("".equals(mBinding.line.getText().toString().trim())) {
            Snackbar.make(mBinding.layout, "请选择产线", Snackbar.LENGTH_LONG).show();
            return;
        } else if ("".equals(mBinding.Warehouse.getText().toString().trim())) {
            Snackbar.make(mBinding.layout, "请选择仓库", Snackbar.LENGTH_LONG).show();
            return;
        } else if ("".equals(mBinding.team.getText().toString().trim())) {
            Snackbar.make(mBinding.layout, "请选择班组长", Snackbar.LENGTH_LONG).show();
            return;
        } else if ("".equals(mBinding.worker.getText().toString().trim())) {
            Snackbar.make(mBinding.layout, "请选择成员", Snackbar.LENGTH_LONG).show();
            return;
        } else if ("".equals(mBinding.brand.getText().toString().trim())) {
            Snackbar.make(mBinding.layout, "请选择产品", Snackbar.LENGTH_LONG).show();
            return;
        } else if (!isNumeric(aa)) {
            Snackbar.make(mBinding.layout, "请输入正确的数字", Snackbar.LENGTH_LONG).show();
            return;
        } else if ("".equals(mBinding.nextName.getText().toString().trim())) {
            Snackbar.make(mBinding.layout, "请选择二次确认人员", Snackbar.LENGTH_LONG).show();
        }
        if (isNumeric(aa)) {
            number = Integer.parseInt(aa);
        }
        mBinding.information.setVisibility(View.GONE);
        mBinding.tishi.setVisibility(View.VISIBLE);
        mBinding.suo.setText("点击解锁后修改信息");
        mBinding.allNumber.setText("总数：" + number + "个");
//        mBinding.line.setEnabled(false);
//        mBinding.Warehouse.setEnabled(false);
//        mBinding.team.setEnabled(false);
//        mBinding.worker.setEnabled(false);
//        mBinding.brand.setEnabled(false);
//        mBinding.gene.setEnabled(false);
//        mBinding.level.setEnabled(false);
//        mBinding.capacity.setEnabled(false);
//        mBinding.name.setEnabled(false);
    }

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

    private void jiesuo() {
        issuo = 0;
        mBinding.information.setVisibility(View.VISIBLE);
        mBinding.tishi.setVisibility(View.GONE);
        mBinding.suo.setText("点击加锁后再扫瓶码");
//        mBinding.line.setEnabled(true);
//        mBinding.Warehouse.setEnabled(true);
//        mBinding.team.setEnabled(true);
//        mBinding.worker.setEnabled(true);
//        mBinding.brand.setEnabled(true);
//        mBinding.gene.setEnabled(true);
//        mBinding.level.setEnabled(true);
//        mBinding.capacity.setEnabled(true);
//        mBinding.name.setEnabled(true);
    }

    private void TanChanxian() {
        AlertDialog.Builder builder = new AlertDialog.Builder(HQTActivity.this);
        builder.setTitle("选择产线");
        /**
         * 设置内容区域为简单列表项
         */
        String[] Items = new String[cxList.size()];
        String[] ItemsId = new String[cxList.size()];
        for (int i = 0; i < cxList.size(); i++) {
            Items[i] = cxList.get(i).getName();
            ItemsId[i] = cxList.get(i).getNumber();
        }
        builder.setItems(Items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                mBinding.line.setText(Items[i]);
            }
        });
        builder.setCancelable(true);
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    private String warehouse = "";
    private String warehouseCode = "";

    private void TanCangKu() {
        AlertDialog.Builder builder = new AlertDialog.Builder(HQTActivity.this);
        builder.setTitle("选择仓库");
        /**
         * 设置内容区域为简单列表项
         */
        String[] Items = new String[whList.size()];
        String[] ItemsId = new String[whList.size()];
        for (int i = 0; i < whList.size(); i++) {
            Items[i] = whList.get(i).getName();
            ItemsId[i] = whList.get(i).getCode();
        }
        builder.setItems(Items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                mBinding.Warehouse.setText(Items[i]);
                warehouse = Items[i];
                warehouseCode = ItemsId[i];
            }
        });
        builder.setCancelable(true);
        AlertDialog dialog = builder.create();
        dialog.show();
    }


    private List<WhBean.ListBean> whList;
    private List<LineBean.ListBean> cxList;


    private void getData() {
        viewModel.getWh(new RequestImpl<List<WhBean.ListBean>>() {
            @Override
            public void loadSuccess(List<WhBean.ListBean> bean) {
                whList = bean;

                if (whList.size() > 0 && requestBean == null) {
                    mBinding.Warehouse.setText(whList.get(0).getName());
                    warehouse = whList.get(0).getName();
                    warehouseCode = whList.get(0).getCode();
                }

            }

            @Override
            public void loadFailed(OError error) {
                whList = new ArrayList<>();
            }
        });
        viewModel.getLins(new RequestImpl<List<LineBean.ListBean>>() {
            @Override
            public void loadSuccess(List<LineBean.ListBean> bean) {
                cxList = bean;
                if (cxList.size() > 0 && requestBean == null) {
                    mBinding.line.setText(cxList.get(0).getName());
                }
            }

            @Override
            public void loadFailed(OError error) {
                cxList = new ArrayList<>();
            }
        });
        set();
    }

    private ProductBean.ListBean mybean;
    private String peopleName = "";
    private String peopleCode = "";

    @Override
    /**
     * 当跳转的activity(被激活的activity)使用完毕,销毁的时候调用该方法
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            List<PeopleBean.ListBean> name = (List<PeopleBean.ListBean>) data.getSerializableExtra("data");
            switch (requestCode) {
                case 1:
                    String n = "";
                    for (int i = 0; i < name.size(); i++) {
                        n = n + name.get(i).getPersonName() + ",";
                    }
                    if (n.length() > 1) {
                        n = n.substring(0, n.length() - 1);
                    }
                    if (name.size() > 0) {
                        peopleName = name.get(0).getPersonName();
                        peopleCode = name.get(0).getPersonCode();
                    }
                    mBinding.team.setText(n);
                    break;
                case 2:
                    String m = "";
                    for (int i = 0; i < name.size(); i++) {
                        m = m + name.get(i).getPersonName() + ",";
                    }
                    if (m.length() > 1) {
                        m = m.substring(0, m.length() - 1);
                    }
                    mBinding.worker.setText(m);
                    break;
                case 3:
                    String t = "";
                    for (int i = 0; i < name.size(); i++) {
                        t = t + name.get(i).getPersonName() + ",";
                    }
                    if (t.length() > 1) {
                        t = t.substring(0, t.length() - 1);
                    }
                    mBinding.nextName.setText(t);
                    break;

                case 100:
                    ProductBean.ListBean bean = (ProductBean.ListBean) data.getSerializableExtra("product");
                    if (bean != null) {
                        mybean = bean;
                        mBinding.brand.setText(bean.getBrand());
                        mBinding.level.setText(bean.getLevel());
                        mBinding.capacity.setText(bean.getCapacity());
                        mBinding.name.setText(bean.getName());
                        int gene = bean.getGene();
                        if (gene == 0) {
                            mBinding.gene.setText("是");
                        } else if (gene == 1) {
                            mBinding.gene.setText("否");
                        } else {
                            mBinding.gene.setText("其他");
                        }

                    }

                    break;
                default:
                    break;

            }
        } else {
            System.out.println("pppppppp无数据");
        }
    }

    public static void start(Activity context) {
        Intent intent = new Intent(context, HQTActivity.class);
        ActivityCompat.startActivity(context, intent, null);
    }

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

}
