package com.philisense.rdgo.ui;

import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.pgyersdk.javabean.AppBean;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;
import com.philisense.rdgo.R;
import com.philisense.rdgo.bean.OError;
import com.philisense.rdgo.bean.response.BoxBean;
import com.philisense.rdgo.bean.response.CommonBean;
import com.philisense.rdgo.databinding.ActivityMainBinding;
import com.philisense.rdgo.databinding.NavHeaderMainBinding;
import com.philisense.rdgo.db.DBFactory;
import com.philisense.rdgo.db.RealmDataBinding;
import com.philisense.rdgo.db.UserDb;
import com.philisense.rdgo.http.RequestImpl;
import com.philisense.rdgo.ui.Query.QueryActivity;
import com.philisense.rdgo.ui.Reset.ResetActivity;
import com.philisense.rdgo.ui.out.OutReplaceActivity;
import com.philisense.rdgo.ui.inRemove.InRemoveActivity;
import com.philisense.rdgo.ui.lineIn.LineInActivity;
import com.philisense.rdgo.ui.putIn.PutInActivity;
import com.philisense.rdgo.ui.putOut.PutOutActivity;
import com.philisense.rdgo.ui.remove.RemoveActivity;
import com.philisense.rdgo.ui.replace.ReplaceOldActivity;
import com.philisense.rdgo.ui.user.LoginActivity;
import com.philisense.rdgo.ui.user.OrderActivity;
import com.philisense.rdgo.ui.user.PasswordActivity;
import com.philisense.rdgo.ui.user.QuareActivity;
import com.philisense.rdgo.ui.validation.ValidationActivity;
import com.philisense.rdgo.ui.waitPutIn.HQTActivity;
import com.philisense.rdgo.util.PerfectClickListener;
import com.philisense.rdgo.viewModel.MainViewModel;
import com.scandecode.ScanDecode;
import com.scandecode.inf.ScanInterface;

import static com.philisense.rdgo.ui.MainActivity.ActionType.kPutIn;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {

    public enum ActionType {
        kPutOut,
        kReplace,
        kPutIn,
        kValidation,
        kTraffic,
        kLineIn,
        kRemove,
        kInRemove,
        kwait,
        kOrder,
        kPassword,
        kAbout,
        kLogout,
        kOutGoing,
        kLook,
        kbox,
        kRes,
        kcx
    }

    private ActivityMainBinding mBinding;
    private UserDb userDb;
    private MainViewModel viewModel;
    private ScanDecode scanDecode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        // toolbar 设置
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        // 初始化数据库
        initDataBase();

        //抽屉
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        // viewmodel 初始化
        viewModel = new MainViewModel(this);
        // 每次进入时更新用户信息，顺带验证用户 token
        viewModel.updateUserInfo();

        // 初始化各类 view
        initView();

        // 初始化抽屉
        initDrawerLayout();

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

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

    /**
     * 应用更新
     */
    private void update() {
        PgyUpdateManager.register(this, new UpdateManagerListener() {
            @Override
            public void onNoUpdateAvailable() {
            }

            @Override
            public void onUpdateAvailable(String s) {
                // 将新版本信息封装到AppBean中
                final AppBean appBean = getAppBeanFromString(s);
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("更新")
                        .setMessage(appBean.getReleaseNote())
                        .setNegativeButton(
                                "确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(
                                            DialogInterface dialog,
                                            int which) {
                                        startDownloadTask(
                                                MainActivity.this,
                                                appBean.getDownloadURL());
                                    }
                                }).show();
            }
        });
    }

    /**
     * 初始化 view
     */
    private void initView() {

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        mBinding.include.minclude.mainView1.mainItemText.setText("扫码出库");
        mBinding.include.minclude.mainView2.mainItemText.setText("扫码入库");
        mBinding.include.minclude.mainView3.mainItemText.setText("产线入库");
        mBinding.include.minclude.mainView4.mainItemText.setText("产线剔除");
        mBinding.include.minclude.mainView5.mainItemText.setText("仓库剔除");
        mBinding.include.minclude.mainView6.mainItemText.setText("坏箱替换");
        mBinding.include.minclude.mainView7.mainItemText.setText("已出库替换");
        mBinding.include.minclude.mainView8.mainItemText.setText("手工归垛");
        mBinding.include.minclude.mainView9.mainItemText.setText("重置");
        mBinding.include.minclude.mainView10.mainItemText.setText("产品询查");

        mBinding.include.minclude.mainView1.mainItemImage.setImageResource(R.drawable.come);       // 扫码出库
        mBinding.include.minclude.mainView2.mainItemImage.setImageResource(R.drawable.into);     // 扫码入库
        mBinding.include.minclude.mainView3.mainItemImage.setImageResource(R.drawable.into);        // 产线入库
        mBinding.include.minclude.mainView4.mainItemImage.setImageResource(R.drawable.delete);        // 扫码剔除
        mBinding.include.minclude.mainView5.mainItemImage.setImageResource(R.drawable.delete);        // 扫码剔除
        mBinding.include.minclude.mainView6.mainItemImage.setImageResource(R.drawable.replace);        // 扫码替换
        mBinding.include.minclude.mainView7.mainItemImage.setImageResource(R.drawable.outgoing);       //已出库替换
        mBinding.include.minclude.mainView8.mainItemImage.setImageResource(R.drawable.into);       //已出库替换
        mBinding.include.minclude.mainView9.mainItemImage.setImageResource(R.drawable.replace);       //重置
        mBinding.include.minclude.mainView10.mainItemImage.setImageResource(R.drawable.replace);       //查询


        View putOutView = mBinding.include.minclude.mainView1.getRoot();     // 扫码出库
        View putInView = mBinding.include.minclude.mainView2.getRoot();    // 扫码入库
        View lineInView = mBinding.include.minclude.mainView3.getRoot();      // 产线入库
        View removeView = mBinding.include.minclude.mainView4.getRoot(); // 扫码剔除
        View inRemoveView = mBinding.include.minclude.mainView5.getRoot(); // 扫码剔除
        View replaceView = mBinding.include.minclude.mainView6.getRoot();    // 扫码替换
        View OutGoingView = mBinding.include.minclude.mainView7.getRoot();    // 出库替换
        View WaitView = mBinding.include.minclude.mainView8.getRoot();    // 手工归垛
        View ResetView = mBinding.include.minclude.mainView9.getRoot();    // 重置
        View CXView = mBinding.include.minclude.mainView10.getRoot();    // 重置


        View logoutView = mBinding.footerItem2;

        putOutView.setTag(ActionType.kPutOut);
        putInView.setTag(kPutIn);
        lineInView.setTag(ActionType.kLineIn);
        removeView.setTag(ActionType.kRemove);
        inRemoveView.setTag(ActionType.kInRemove);
        replaceView.setTag(ActionType.kReplace);
        logoutView.setTag(ActionType.kLogout);
        OutGoingView.setTag(ActionType.kOutGoing);
        WaitView.setTag(ActionType.kwait);
        ResetView.setTag(ActionType.kRes);
        CXView.setTag(ActionType.kcx);

        putOutView.setOnClickListener(this);
        putInView.setOnClickListener(this);
        lineInView.setOnClickListener(this);
        removeView.setOnClickListener(this);
        inRemoveView.setOnClickListener(this);
        replaceView.setOnClickListener(this);
        OutGoingView.setOnClickListener(this);
        WaitView.setOnClickListener(this);
        ResetView.setOnClickListener(this);
        CXView.setOnClickListener(this);
        logoutView.setOnClickListener(perfectClickListener);
    }

    /**
     * 初始化本地数据
     */
    private void initDataBase() {
        userDb = DBFactory.getUserInfo(this);
        // 对数据库中个人信息进行监听，以防后期对 user 进行变更
        if (userDb != null) {
            userDb.addChangeListener(RealmDataBinding.FACTORY.create());
        } else {
            // 如果没有用户信息，则需要重新登录
            LoginActivity.start(MainActivity.this);
            finish();
        }
    }

    /**
     * 初始化抽屉
     */
    private void initDrawerLayout() {
        View headerView = mBinding.navView.getHeaderView(0);
        NavHeaderMainBinding headerbind = DataBindingUtil.bind(headerView);
        // 设置数据源
        headerbind.setUser(userDb);

        // 设置tag
        headerbind.navAbout.setTag(ActionType.kAbout);
        headerbind.navOrder.setTag(ActionType.kOrder);
        headerbind.navPasswrod.setTag(ActionType.kPassword);
        headerbind.navQuery.setTag(ActionType.kLook);
        headerbind.navBox.setTag(ActionType.kbox);
        // 设置监听
        headerbind.navAbout.setOnClickListener(perfectClickListener);
        headerbind.navOrder.setOnClickListener(perfectClickListener);
        headerbind.navPasswrod.setOnClickListener(perfectClickListener);
        headerbind.navQuery.setOnClickListener(perfectClickListener);
        headerbind.navBox.setOnClickListener(perfectClickListener);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = mBinding.drawerLayout;
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onClick(View view) {
        ActionType tag = (ActionType) view.getTag();
        switch (tag) {
            case kPutOut:
                PutOutActivity.start(this);
                break;
            case kReplace:
                ReplaceOldActivity.start(this);
                break;
            case kPutIn:
                PutInActivity.start(this);
                break;
            case kValidation:
                ValidationActivity.start(this);
                break;
            case kLineIn:
                LineInActivity.start(this);
                break;
            case kRemove:
                RemoveActivity.start(this);
                break;
            case kInRemove:
                InRemoveActivity.start(this);
                break;
            case kOutGoing:
                OutReplaceActivity.start(this);
                break;
            case kwait:
                HQTActivity.start(this);
                break;
            case kRes:
                ResetActivity.start(this);
                break;
            case kcx:
                QueryActivity.start(this);
                break;
            default:
                break;
        }
    }

    private PerfectClickListener perfectClickListener = new PerfectClickListener() {
        @Override
        protected void onNoDoubleClick(View v) {
            mBinding.drawerLayout.closeDrawer(GravityCompat.START);
            mBinding.drawerLayout.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ActionType tag = (ActionType) v.getTag();
                    switch (tag) {
                        case kOrder:
                            OrderActivity.start(MainActivity.this);
                            break;
                        case kPassword:
                            PasswordActivity.start(MainActivity.this);
                            break;
                        case kAbout:
                            AboutActivity.start(MainActivity.this);
                            break;
                        case kLogout:
                            logout();
                            break;
                        case kLook:
                            QuareActivity.start(MainActivity.this);
                            break;
                        case kbox:
                            box();
                            break;
                    }
                }
            }, 260);
        }
    };
    TextView name;
    private int flag = 0;
    private AlertDialog alertDialog;
    private AlertDialog.Builder builder;

    private void box() {
        flag = 1;
        MainActivity context = MainActivity.this;
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.box, null);

        TextView close = layout.findViewById(R.id.close);
        Button bt = layout.findViewById(R.id.determine);
        name = layout.findViewById(R.id.name);

        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String s = name.getText().toString().trim();
                ClipboardManager copy = (ClipboardManager) MainActivity.this
                        .getSystemService(Context.CLIPBOARD_SERVICE);
                copy.setText(s);
                Toast.makeText(MainActivity.this, "复制成功", Toast.LENGTH_LONG).show();
                flag = 0;
                alertDialog.dismiss();
                name.setText("");
            }
        });


        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                flag = 0;
                alertDialog.dismiss();
                name.setText("");
            }
        });


        builder = new AlertDialog.Builder(context);
        builder.setView(layout);
        alertDialog = builder.create();
        alertDialog.show();

        alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                flag = 0;
                name.setText("");
            }
        });
    }

    private void getBox(String id) {
        viewModel.getBoxId(id, new RequestImpl<BoxBean>() {
            @Override
            public void loadSuccess(BoxBean bean) {
                if (bean != null) {
                    name.setText(bean.getData().getBoxId());
                }
            }

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

            }
        });
    }

    /**
     * 登出操作
     */
    private void logout() {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        dialogBuilder.setTitle("提示");
        dialogBuilder.setMessage("您确定要登出账号吗？");
        dialogBuilder.setNegativeButton("取消", null);
        dialogBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                viewModel.logout(new RequestImpl<String>() {
                    @Override
                    public void loadSuccess(String bean) {
                        LoginActivity.start(MainActivity.this);
                        finish();
                        Toast.makeText(MainActivity.this, "登出成功", Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void loadFailed(OError error) {
                        Snackbar.make(mBinding.navView, error.getErrorMsg(), Snackbar.LENGTH_LONG).show();
                    }

                });
            }
        });
        dialogBuilder.show();
    }

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PgyUpdateManager.unregister();

        if (userDb != null) {
            if (userDb.isValid()) {
                userDb.removeAllChangeListeners(); // remove change listeners just in case
            }
        }
    }
}
