package com.philisense.rdgo.ui.replace;

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.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.philisense.rdgo.R;
import com.philisense.rdgo.adapter.ReplaceAdapter;
import com.philisense.rdgo.bean.OError;
import com.philisense.rdgo.databinding.ActivityReplaceReviewBinding;
import com.philisense.rdgo.http.RequestImpl;
import com.philisense.rdgo.viewModel.ReplaceViewModel;
import com.scandecode.ScanDecode;
import com.scandecode.inf.ScanInterface;

public class ReplaceReviewActivity extends AppCompatActivity {

    private ActivityReplaceReviewBinding mBinding;
    private ScanDecode scanDecode;
    private ReplaceAdapter adapter;
    private ReplaceViewModel viewModel;

    private String oldBoxId;
    private String newBoxId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this,R.layout.activity_replace_review);
        Toolbar toolbar = mBinding.include.toolbar;
        toolbar.setTitle("替换详情");
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener(){
            public void onClick(View view){
                showExitAlert();
            }
        });

        oldBoxId = getIntent().getStringExtra("oldBoxId");
        newBoxId = getIntent().getStringExtra("newBoxId");

        mBinding.orderSend.setText(oldBoxId);
        mBinding.orderReceiv.setText(newBoxId);

        viewModel = new ReplaceViewModel(this);

        adapter = new ReplaceAdapter();
        mBinding.replaceRecycler.setLayoutManager(new LinearLayoutManager(this));
        mBinding.replaceRecycler.setAdapter(adapter);
        mBinding.replaceRecycler.addItemDecoration(new DividerItemDecoration(this, LinearLayout.VERTICAL));

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

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

        scanDecode.getBarCode(new ScanInterface.OnScanListener() {
            @Override
            public void getBarcode(String s) {
                // 隐藏空白文件
                mBinding.replaceEmptyView.setVisibility(View.GONE);
                mBinding.replaceText.setVisibility(View.GONE);

                scanDecode.stopScan();
                String[] x = s.split("/");
                for (String boxId: adapter.getDataArray()) {
                    if (boxId.equals(x[x.length-1])) {
                        Snackbar.make(mBinding.replaceReviewRoot,"该瓶已被扫入",Snackbar.LENGTH_LONG).show();
                        return;
                    }
                }
                adapter.addOne(x[x.length-1]);
            }
        });

    }

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

    /**
     * 确认信息
     */
    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(ReplaceReviewActivity.this,"提示","正在录入..");

        viewModel.replaceAction(oldBoxId, newBoxId, adapter.getDataArray(), new RequestImpl<String>() {
            @Override
            public void loadSuccess(String bean) {
                dialog.dismiss();
                finish();
                Toast.makeText(ReplaceReviewActivity.this,"替换成功",Toast.LENGTH_LONG).show();
            }

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


    /**
     * @param context      activity
     */
    public static void start(Activity context, String oldBoxId, String newBoxId) {
        Intent intent = new Intent(context, ReplaceReviewActivity.class);
        intent.putExtra("oldBoxId",oldBoxId);
        intent.putExtra("newBoxId",newBoxId);
        ActivityCompat.startActivity(context, intent,null);
    }

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