package com.qhclh.ytzh.home;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.qhclh.ytzh.R;
import com.qhclh.ytzh.base.BaseActivity;
import com.qhclh.ytzh.bean.DownLoadBean;
import com.qhclh.ytzh.bean.MobileBean;
import com.qhclh.ytzh.index.HomepageEvent;
import com.qhclh.ytzh.index.IndexFragment;
import com.qhclh.ytzh.index.JPInfoActivity;
import com.qhclh.ytzh.index.WorkEvent;
import com.qhclh.ytzh.index.fumudai.FumudaiFragment;
import com.qhclh.ytzh.index.shangpin.InHouseActivity;
import com.qhclh.ytzh.index.shangpin.ShangpinFragment;
import com.qhclh.ytzh.me.MeFragment;
import com.qhclh.ytzh.tasks.ViewOnClickTask;
import com.qhclh.ytzh.utils.ApkUtils;
import com.qhclh.ytzh.utils.Urltool;
import com.qhclh.ytzh.work.WorkFragment;


import org.forks.jsonrpc.JsonRpcResult;
import org.forks.jsonrpc.RpcFacade;
import org.forks.jsonrpc.RpcObject;
import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends BaseActivity {
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.tv_toolbar_title)
    TextView mTvToolbarTitle;

    @BindView(R.id.iv_index)
    ImageView iv_index;
    @BindView(R.id.tv_index)
    TextView tv_index;
    @BindView(R.id.iv_work)
    ImageView iv_work;
    @BindView(R.id.tv_work)
    TextView tv_work;
    @BindView(R.id.iv_me)
    ImageView iv_me;
    @BindView(R.id.tv_me)
    TextView tv_me;


    private long mLastClickTime;
    private static final long DEFAULT_EXIT_TIME = 2000;
    ///< 首页
    private static final int TAB_POSITION_INDEX = 0;
    ///< 工作
    private static final int TAB_POSITION_WORK = 1;
    ///< 我的
    private static final int TAB_POSITION_ME = 2;
    private int mCurrentTabPosition = -1;
    private int mTargetTabPosition = TAB_POSITION_INDEX;

    private IndexFragment indexFragment;
    private WorkFragment workFragment;
    private MeFragment meFragment;

    private ShangpinFragment shangpinFragment;
    private FumudaiFragment fumudaiFragment;
    ///< 0 商品鸡   1父母代
    private int indexFlag = -1;


    private String versionName, downloadUrl;
    private DownLoadBean downLoadBean;


    public static List<String> homepageList;
    public static List<String> workList;


    @Override
    protected int setLayoutId() {
        return R.layout.act_main;
    }

    @Override
    protected void initView() {
        initToolbar(mToolbar, "", null);

        dongtaiQuanxian();
    }

    @Override
    protected void initData() {
//        FalgBean falgBean = new FalgBean();
//        falgBean.setFlag(0);
//        falgBean.save();
    }

    @Override
    protected void initOper() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        MobileAppSchemaRpc_Load();
    }

    private void MobileAppSchemaRpc_Load() {
        ViewOnClickTask mobileTask = new ViewOnClickTask(this, "加载中...") {
            RpcObject rpcObj;

            @Override
            protected void successUI() {
                if (rpcObj.getString("Content") != null) {
                    Gson gson = new Gson();
                    MobileBean mobileBean = gson.fromJson(rpcObj.getString("Content"), MobileBean.class);

                    homepageList = mobileBean.getHomepage().getFunctions();
                    workList = mobileBean.getWork().getFunctions();
                    ///< 点击切换fragment
                    indexFlag = Integer.parseInt(mobileBean.getHomepage().getType());

                    onTabClick(mTargetTabPosition);
                    EventBus.getDefault().postSticky(new HomepageEvent(homepageList));
                    EventBus.getDefault().postSticky(new WorkEvent(workList));
                }

            }

            @Override
            public Object call() throws Exception {
                JsonRpcResult result = RpcFacade.rpcCall(RpcUrl.MobileAppSchemaRpc_Load);
                rpcObj = result.getRpcObject(RpcUrl.MobileAppSchemaRpc_Load_fanhui);
                return null;
            }
        };
        mobileTask.execute();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        DataSupport.deleteAll(FalgBean.class);
    }

    @OnClick({R.id.ll_index, R.id.ll_work, R.id.ll_me})
    public void onClick(View view) {
        switch (view.getId()) {
            ///< 首页
            case R.id.ll_index: {
                onTabClick(TAB_POSITION_INDEX);
                mTargetTabPosition = TAB_POSITION_INDEX;
                break;
            }
            ///< 工作
            case R.id.ll_work: {
                onTabClick(TAB_POSITION_WORK);
                mTargetTabPosition = TAB_POSITION_WORK;
                break;
            }

            ///< 我的
            case R.id.ll_me: {
                onTabClick(TAB_POSITION_ME);
                mTargetTabPosition = TAB_POSITION_ME;
                break;
            }
        }
    }

    private void onTabClick(int tabPosition) {
        if (mCurrentTabPosition == tabPosition) {
            return;
        }
        mCurrentTabPosition = tabPosition;
        changeTabState(tabPosition);
        changeFragment(tabPosition);
    }

    private void changeTabState(int tabPosition) {
        clearAllTabState();
        switch (tabPosition) {
            case TAB_POSITION_INDEX: {
                iv_index.setImageResource(R.drawable.shouye_3x);
                tv_index.setTextColor(getResources().getColor(R.color.green029737));
                mTvToolbarTitle.setText(R.string.index);
                break;
            }

            case TAB_POSITION_WORK: {
                iv_work.setImageResource(R.drawable.gongzuo_3x);
                tv_work.setTextColor(getResources().getColor(R.color.green029737));
                mTvToolbarTitle.setText(R.string.work);
                break;
            }
            case TAB_POSITION_ME: {
                iv_me.setImageResource(R.drawable.wode_3x);
                tv_me.setTextColor(getResources().getColor(R.color.green029737));
                mTvToolbarTitle.setText(R.string.me);
                break;
            }
        }
    }


    private void clearAllTabState() {
        ///< 首页
        iv_index.setImageResource(R.drawable.shouye1_3x);
        tv_index.setTextColor(getResources().getColor(R.color.grey888888));
        ///< 工作
        iv_work.setImageResource(R.drawable.gongzuo1_3x);
        tv_work.setTextColor(getResources().getColor(R.color.grey888888));

        ///< 我的
        iv_me.setImageResource(R.drawable.wode1_3x);
        tv_me.setTextColor(getResources().getColor(R.color.grey888888));

    }


    private void changeFragment(int tabPosition) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        hideFragment(transaction);
        switch (tabPosition) {
            case TAB_POSITION_INDEX: {
                optionMenuOn = true;
                checkOptionMenu();
                if (indexFlag == 0) {
                    if (shangpinFragment == null) {
                        shangpinFragment = new ShangpinFragment();
                        transaction.add(R.id.main_container, shangpinFragment);
                    } else {
                        transaction.show(shangpinFragment);
                    }
                } else {
                    if (fumudaiFragment == null) {
                        fumudaiFragment = new FumudaiFragment();
                        transaction.add(R.id.main_container, fumudaiFragment);
                    } else {
                        transaction.show(fumudaiFragment);
                    }
                }
//                if (indexFragment == null) {
//                    indexFragment = new IndexFragment();
//                    transaction.add(R.id.main_container, indexFragment);

//                } else {
//                    transaction.show(indexFragment);
//                }
                break;
            }

            case TAB_POSITION_WORK: {
                optionMenuOn = false;
                checkOptionMenu();
                if (workFragment == null) {
                    workFragment = new WorkFragment();
                    transaction.add(R.id.main_container, workFragment);
                } else {
                    transaction.show(workFragment);
                }
                break;
            }

            case TAB_POSITION_ME: {
                optionMenuOn = false;
                checkOptionMenu();
                if (meFragment == null) {
                    meFragment = new MeFragment();
                    transaction.add(R.id.main_container, meFragment);
                } else {
                    transaction.show(meFragment);
                }
                break;
            }
        }
        transaction.commitAllowingStateLoss();
    }

    private void hideFragment(FragmentTransaction transaction) {
//        if (indexFragment != null) {
//            transaction.hide(indexFragment);
//        }

        if (shangpinFragment != null) {
            transaction.hide(shangpinFragment);
        }

        if (fumudaiFragment != null) {
            transaction.hide(fumudaiFragment);
        }


        if (workFragment != null) {
            transaction.hide(workFragment);
        }
        if (meFragment != null) {
            transaction.hide(meFragment);
        }
    }

    private boolean optionMenuOn = false;  //标示是否要显示optionmenu
    private Menu aMenu;         //获取optionmenu

    private void checkOptionMenu() {
        if (null != aMenu) {
            if (optionMenuOn) {

                if (homepageList !=null) {
                    if (homepageList.contains("001")) {
                        aMenu.findItem(R.id.shangpin_xiaoxi).setVisible(true);
                    } else {
                        aMenu.findItem(R.id.shangpin_xiaoxi).setVisible(false);
                    }
                    if (homepageList.contains("002")) {
                        aMenu.findItem(R.id.shangpin_rushedan).setVisible(true);
                    } else {
                        aMenu.findItem(R.id.shangpin_rushedan).setVisible(false);
                    }
                }

            } else {
                aMenu.findItem(R.id.shangpin_xiaoxi).setVisible(false);
                aMenu.findItem(R.id.shangpin_rushedan).setVisible(false);
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.shangpinmenu, menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        aMenu = menu;
        checkOptionMenu();
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.shangpin_xiaoxi:
//                if (indexFlag == 0){
//                    System.out.println("aaa+++++++商品鸡消息");
//                }else {
//                    System.out.println("aaa+++++++父母代消息");
//                }
                startActivity(new Intent(MainActivity.this, JPInfoActivity.class));
                break;
            case R.id.shangpin_rushedan:
//                System.out.println("aaa+++++++商品鸡入舍单");
                startActivity(new Intent(MainActivity.this, InHouseActivity.class));
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        exitApp();
    }

    ///< back键退出
    private void exitApp() {
        long currentTime = System.currentTimeMillis();
        if (currentTime - mLastClickTime < DEFAULT_EXIT_TIME) {
            finishAll();
        } else {
            mLastClickTime = currentTime;
            showToast(getString(R.string.back_exit_app));
        }
    }


    private static final int REQUEST_PERMISSION_CAMERA_CODE = 1021;

    @AfterPermissionGranted(REQUEST_PERMISSION_CAMERA_CODE)
    private void dongtaiQuanxian() {
        String[] perms = {Manifest.permission.READ_PHONE_STATE};
        if (!EasyPermissions.hasPermissions(this, perms)) {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, getString(R.string.permission_phonestate),
                    REQUEST_PERMISSION_CAMERA_CODE, perms);
        } else {
            // Already have permission, do the thing
            // ...
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        checkUpData();
    }

    private void checkUpData() {
        ///< 版本更新检查
        final String url = "http://bwp.oss-cn-beijing.aliyuncs.com/publish/ZhongHuiApp/publish.json";
        new Thread(new Runnable() {
            @Override
            public void run() {
                String jsonString = Urltool.getJsonByInternet(url);
                if (jsonString != null && !jsonString.equals("")) {
                    Gson gson = new Gson();
                    downLoadBean = gson.fromJson(jsonString, DownLoadBean.class);
                    versionName = downLoadBean.getVersion();
                    downloadUrl = downLoadBean.getDownload();
                    String localversionname = ApkUtils.getVersionName(MainActivity.this);

                    if (localversionname.equals(versionName)) {
//                    showToast("");
                    } else {
                        Intent intent = new Intent();
                        intent.setAction("android.intent.action.VIEW");
                        Uri content_url = Uri.parse(downloadUrl);
                        intent.setData(content_url);
                        startActivity(intent);
                    }
                }
            }
        }).start();
    }
}
