package com.philisense.rdgo.ui.user;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

import com.borax12.materialdaterangepicker.date.DatePickerDialog;
import com.example.xrecyclerview.XRecyclerView;
import com.philisense.rdgo.R;
import com.philisense.rdgo.adapter.OrderAdapter;
import com.philisense.rdgo.base.BaseActivity;
import com.philisense.rdgo.bean.LineBean;
import com.philisense.rdgo.bean.OError;
import com.philisense.rdgo.bean.response.PutOutRecordBean;
import com.philisense.rdgo.databinding.ActivityOrderBinding;
import com.philisense.rdgo.http.RequestImpl;
import com.philisense.rdgo.viewModel.OrderViewModel;
import com.scandecode.ScanDecode;
import com.scandecode.inf.ScanInterface;

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

public class OrderActivity extends BaseActivity<ActivityOrderBinding> implements PopupMenu.OnMenuItemClickListener, DatePickerDialog.OnDateSetListener {

    private OrderViewModel viewModel;
    private OrderAdapter adapter;
    private ScanDecode scanDecode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order);

        Toolbar toolbar = bindingView.toolbar;
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                finish();
            }
        });

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

        scanDecode.getBarCode(new ScanInterface.OnScanListener() {
            @Override
            public void getBarcode(String s) {

                if (Type == 1) {
                    viewModel.senId = s;
                    getPutOutInfo(false, true, 1);
                }

            }
        });


        bindingView.orderRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new OrderAdapter(this);
        bindingView.orderRecyclerView.setAdapter(adapter);

        viewModel = new OrderViewModel(this);

        Typeface iconfont = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
        bindingView.toolbarText.setTypeface(iconfont);
        bindingView.toolbarText.setText("出库记录 " + getResources().getString(R.string.down));

        bindingView.toolbarText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PopupMenu popup = new PopupMenu(OrderActivity.this, bindingView.toolbarTextTopLine);
                popup.setGravity(Gravity.TOP);
                MenuInflater inflater = popup.getMenuInflater();
                inflater.inflate(R.menu.order_type_menu, popup.getMenu());
                //绑定菜单项的点击事件
                popup.setOnMenuItemClickListener(OrderActivity.this);
                popup.show();
            }
        });

        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                Calendar now = Calendar.getInstance();
                DatePickerDialog dpd = DatePickerDialog.newInstance(
                        OrderActivity.this,
                        now.get(Calendar.YEAR),
                        now.get(Calendar.MONTH),
                        now.get(Calendar.DAY_OF_MONTH)
                );
                dpd.setStartTitle("开始时间");
                dpd.setEndTitle("结束时间");
                dpd.show(getFragmentManager(), "Datepickerdialog");
                return true;
            }
        });

        getPutOutInfo(false, true, 0);
        getLin();

        bindingView.orderRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                getPutOutInfo(false, true, 1);
            }

            @Override
            public void onLoadMore() {

//                getPutOutInfo(true,false,1);
                bindingView.orderRecyclerView.refreshComplete();
            }
        });

        bindingView.determine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String t = bindingView.edit.getText().toString();
                viewModel.senId = t;
                getPutOutInfo(false, true, 1);


            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.search_menu, menu);
        return true;
    }

    private int Type = 1;

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_put_in:
                bindingView.toolbarText.setText("入库记录 " + getResources().getString(R.string.down));
                bindingView.relLin.setVisibility(View.GONE);
                bindingView.linId.setVisibility(View.GONE);
                viewModel.type = 2;
                Type = 2;
                break;
            case R.id.action_put_out:
                bindingView.toolbarText.setText("出库记录 " + getResources().getString(R.string.down));
                bindingView.relLin.setVisibility(View.GONE);
                bindingView.linId.setVisibility(View.VISIBLE);
                viewModel.type = 1;
                Type = 1;
                break;
            case R.id.action_line_in:
                bindingView.toolbarText.setText("产线入库记录 " + getResources().getString(R.string.down));
                bindingView.relLin.setVisibility(View.VISIBLE);
                bindingView.lins.setText("请选择产线");
                bindingView.linId.setVisibility(View.GONE);
                viewModel.type = 0;
                Type = 0;
                break;
            case R.id.action_get_out:
                bindingView.toolbarText.setText("剔除记录 " + getResources().getString(R.string.down));
                bindingView.relLin.setVisibility(View.GONE);
                bindingView.linId.setVisibility(View.GONE);
                viewModel.type = 6;
                Type = 6;
                break;
            case R.id.action_replace:
                bindingView.toolbarText.setText("替换记录 " + getResources().getString(R.string.down));
                bindingView.relLin.setVisibility(View.GONE);
                bindingView.linId.setVisibility(View.GONE);
                viewModel.type = 7;
                Type = 7;
                break;
            case R.id.action_destroy:
                bindingView.toolbarText.setText("销毁记录 " + getResources().getString(R.string.down));
                bindingView.relLin.setVisibility(View.GONE);
                bindingView.linId.setVisibility(View.GONE);
                viewModel.type = 8;
                Type = 8;
                break;
            default:
                break;
        }
        showLoading();
        getPutOutInfo(false, true, 0);
        return false;
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }


    /**
     * 获取出库记录
     */
    public void getPutOutInfo(boolean isNextPage, boolean isRefresh, int flag) {

        bindingView.edit.setText("");

        viewModel.getPutInOrder(isNextPage, isRefresh, flag, new RequestImpl<List<PutOutRecordBean.DataBean>>() {
            @Override
            public void loadSuccess(List<PutOutRecordBean.DataBean> bean) {
                adapter.setData(bean);
                bindingView.orderRecyclerView.refreshComplete();
                getNum(bean);
                getNowTime();
                showContentView();
                bindingView.orderRecyclerView.isnomore = bean.size() % 20 != 0;

            }

            @Override
            public void loadFailed(OError error) {
                showContentView();
                adapter.setData(new ArrayList<>());
                bindingView.orderRecyclerView.refreshComplete();
                Snackbar.make(bindingView.orderRootLayout, error.getErrorMsg(), Snackbar.LENGTH_LONG).show();
                getNowTime();
                bindingView.num.setText("总共0箱");
            }
        });

    }

    private void getNum(List<PutOutRecordBean.DataBean> bean) {
        int a = 0;
        for (int i = 0; i < bean.size(); i++) {
            a = a + bean.get(i).getNum();
        }
        bindingView.num.setText("总共" + a + "箱");
    }

    private void getNowTime() {

        bindingView.time.setText(viewModel.startTime + " 至 " + viewModel.endTime);


    }

    private List<LineBean.ListBean> myline;

    /**
     * 获取产线列表
     */
    public void getLin() {
        myline = new ArrayList<>();
        viewModel.getLins(new RequestImpl<LineBean>() {
            @Override
            public void loadSuccess(LineBean bean) {

                myline = bean.getList();

            }

            @Override
            public void loadFailed(OError error) {

            }
        });


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

                digo(myline);
            }
        });


    }

    private void digo(List<LineBean.ListBean> bean) {
        if (bean == null) {
            bean = new ArrayList<>();
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(OrderActivity.this);
        builder.setTitle("选择需要查询的产线");

        /**
         * 设置内容区域为简单列表项
         */
        String[] Items = new String[bean.size() + 1];

        Items[0] = "全部";
        for (int i = 0; i < bean.size(); i++) {
            Items[i + 1] = bean.get(i).getName();
        }

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

                if (i == 0) {
                    viewModel.lin = "";
                } else {
                    viewModel.lin = Items[i];
                }

                bindingView.lins.setText(Items[i] + "");
                showLoading();
                getPutOutInfo(false, false, 1);

            }
        });

        builder.setCancelable(true);
        AlertDialog dialog = builder.create();
        dialog.show();
    }


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

    @Override
    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth, int yearEnd, int monthOfYearEnd, int dayOfMonthEnd) {
        int month = monthOfYear + 1;
        String mfy = "";
        if (month < 10) {
            mfy = "0" + month;
        } else {
            mfy = month + "";
        }
        int monthEnd = monthOfYearEnd + 1;
        String mfe = "";
        if (monthEnd <10) {
            mfe = "0" + monthEnd;
        } else {
            mfe = monthEnd + "";
        }
        String day = "";
        if (dayOfMonth < 10) {
            day = "0" + dayOfMonth;
        } else {
            day = dayOfMonth + "";
        }

        String dayEnd = "";
        if (dayOfMonthEnd < 10) {
            dayEnd = "0" + dayOfMonthEnd;
        } else {
            dayEnd = dayOfMonthEnd + "";
        }

        viewModel.startTime = year + "-" + mfy + "-" + day;
        viewModel.endTime = yearEnd + "-" + mfe + "-" + dayEnd;
        showLoading();
        getPutOutInfo(false, false, 1);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            scanDecode.onDestroy();

        } catch (Exception e) {
        }
    }
}
