package com.taikor.investment;

import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.taikor.investment.modules.CustomerFragment;
import com.taikor.investment.modules.FindFragment;
import com.taikor.investment.modules.GroupFragment;
import com.taikor.investment.modules.ProductFragment;
import com.taikor.investment.modules.UserFragment;
import com.taikor.investment.utils.CommonUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.fl_content)
    FrameLayout flContent;
    @BindView(R.id.rb_find)
    RadioButton rbFind;
    @BindView(R.id.rb_product)
    RadioButton rbProduct;
    @BindView(R.id.rb_group)
    public RadioButton rbGroup;
    @BindView(R.id.rb_customer)
    RadioButton rbCustomer;
    @BindView(R.id.rb_user)
    RadioButton rbUser;
    @BindView(R.id.rg_tab)
    RadioGroup rgTab;

    public FindFragment findFragment;
    public ProductFragment productFragment;
    public GroupFragment groupFragment;
    public CustomerFragment customerFragment;
    public UserFragment userFragment;
    private NetWorkChangeReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        //打开APP进行授权
        CommonUtils.verifyStoragePermissions(this);

        Intent intent = getIntent();
        //false,表示显示默认的fragment——FindFragment
        boolean flag = intent.getBooleanExtra("default_fragment", false);
        //传递过来的标记，需要切换显示的fragment
        String fragment_position = intent.getStringExtra("fragment_position");
        if (!flag) {
            //显示默认
            rgTab.check(R.id.rb_find);
            changeFragment(0);
        } else {//显示其他页
            switch (fragment_position) {
                case "2":
                    changeFragment(2);
                    rbGroup.setChecked(true);
                    break;
                case "3":
                    changeFragment(3);
                    rbCustomer.setChecked(true);
                    break;
            }

        }
        //注册广播，判断网络连接
        if (receiver == null) {
            receiver = new NetWorkChangeReceiver();
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(receiver, filter);
    }

    //显示之前隐藏所有fragment
    public void hideFragments(FragmentTransaction transaction) {
        if (findFragment != null)
            transaction.hide(findFragment);
        if (productFragment != null)
            transaction.hide(productFragment);
        if (groupFragment != null)
            transaction.hide(groupFragment);
        if (customerFragment != null)
            transaction.hide(customerFragment);
        if (userFragment != null)
            transaction.hide(userFragment);
    }

    //切换fragment
    public void changeFragment(int position) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        hideFragments(ft);//隐藏所有fragment

        switch (position) {
            case 0:
                if (findFragment == null) {
                    findFragment = new FindFragment();
                    ft.add(R.id.fl_content, findFragment);
                } else {
                    ft.show(findFragment);
                }
                break;
            case 1:
                if (productFragment == null) {
                    productFragment = new ProductFragment();
                    ft.add(R.id.fl_content, productFragment);
                } else {
                    ft.show(productFragment);
                }
                break;
            case 2:
                if (groupFragment == null) {
                    groupFragment = new GroupFragment();
                    ft.add(R.id.fl_content, groupFragment);
                } else {
                    ft.show(groupFragment);
                }
                break;
            case 3:
                if (customerFragment == null) {
                    customerFragment = new CustomerFragment();
                    ft.add(R.id.fl_content, customerFragment);
                } else {
                    ft.show(customerFragment);
                }
                break;
            case 4:
                if (userFragment == null) {
                    userFragment = new UserFragment();
                    ft.add(R.id.fl_content, userFragment);
                } else {
                    ft.show(userFragment);
                }
                break;
        }
        ft.commit();
    }

    @OnClick({R.id.rb_find, R.id.rb_product, R.id.rb_group, R.id.rb_customer, R.id.rb_user})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rb_find:
                changeFragment(0);
                break;
            case R.id.rb_product:
                changeFragment(1);
                break;
            case R.id.rb_group:
                changeFragment(2);
                break;
            case R.id.rb_customer:
                changeFragment(3);
                break;
            case R.id.rb_user:
                changeFragment(4);
                break;
        }
    }

    //保存状态
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        for (int i = 0; i < rgTab.getChildCount(); i++) {
            RadioButton radioButton = (RadioButton) rgTab.getChildAt(i);
            FragmentManager fm = getSupportFragmentManager();
            Fragment fragment = fm.findFragmentByTag((String) radioButton.getTag());
            FragmentTransaction ft = fm.beginTransaction();
            if (fragment != null) {
                if (!radioButton.isChecked()) {
                    ft.hide(fragment);
                }
            }
            ft.commit();
        }
    }

    // 双击退出功能实现
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                onBackPressed();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}
