package com.xxfc.rv;

import android.app.AlertDialog;
import android.app.Notification;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.frame.base.url.Constance;
import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.adapter.TabAdapter;
import com.ruiwenliu.wrapper.base.BaseActivity;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseWrapperFragment;
import com.ruiwenliu.wrapper.bean.ActBean;
import com.ruiwenliu.wrapper.receiver.NetWorkReceiver;
import com.ruiwenliu.wrapper.statusbar.StatusBarUtil;
import com.ruiwenliu.wrapper.util.listener.SwitchFragment;
import com.ruiwenliu.wrapper.weight.CustomScrollViewPager;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.camp.CampFragment;
import com.rv.component.utils.Cookie;
import com.rv.home.rv.module.ApiConfig;
import com.ruiwenliu.wrapper.base.presenter.CommonPresenter;
import com.rv.home.rv.module.ui.main.home.HomeFragment;
import com.rv.home.rv.module.ui.main.home.bean.EffectiveTimeBean;
import com.rv.rvmine.MineFragment;
import com.rv.share.WebViewActivity;
import com.rv.share.view.PromotionDialog;
import com.rv.tourism.R2;
import com.rv.tourism.TourismFragment;
import com.rv.version.bean.VersionCheckBean;
import com.rv.version.util.DownloadAppUtils;
import com.rv.version.util.UpdateAppUtils;
import com.squareup.haha.perflib.Main;
import com.xxfc.discovery.DiscoveryFragment;
import com.yuyife.okgo.OkGoUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.BasicPushNotificationBuilder;
import cn.jpush.android.api.CustomPushNotificationBuilder;
import cn.jpush.android.api.JPushInterface;


public class MainActivity extends BaseActivity<CommonPresenter> {

    //    @BindView(R2.id.pager_view_fragment)
    CustomScrollViewPager viewPager;
    @BindView(R2.id.iv_home)
    ImageView ivHome;
    @BindView(R2.id.tv_home)
    TextView tvHome;
    @BindView(R2.id.iv_travel)
    ImageView ivTravel;
    @BindView(R2.id.tv_travel)
    TextView tvTravel;
    @BindView(R2.id.iv_camp)
    ImageView ivCamp;
    @BindView(R2.id.tv_camp)
    TextView tvCamp;
    @BindView(R2.id.iv_found)
    ImageView ivFound;
    @BindView(R2.id.tv_found)
    TextView tvFound;
    @BindView(R2.id.iv_mine)
    ImageView ivMine;
    @BindView(R2.id.tv_mine)
    TextView tvMine;
    private TabAdapter mAdapter;
    private final int TYPE_HOME_PAGE = 0;//首页
    private final int TYPE_TRAVEL = 1;//旅行
    private final int TYPE_CAMP = 2;//营地
    private final int TYPE_FOUND = 3;//旅行
    private final int TYPE_MINE = 4;//我的
    private long exitTime = 0;


    private UpdateAppUtils updateAppUtils;
    private PromotionDialog promotionDialog;

    private NetWorkReceiver netReceiver = null;

    public static Intent getIntent(Context context) {
        return new Intent(context, MainActivity.class);
    }

    @Override
    protected int setLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setRootViewFitsSystemWindows(mActivity, false);
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        updateAppUtils = UpdateAppUtils.from(MainActivity.this);
        viewPager = findViewById(R.id.pager_view_fragment);
        showTitle(false);
        mAdapter = new TabAdapter(getSupportFragmentManager(), getListFragment());
        viewPager.setAdapter(mAdapter);
        viewPager.setOffscreenPageLimit(5);
        setCurrent(TYPE_HOME_PAGE);
        registerNetWorkListener();
        initNotification();
        SwitchFragment.setFragmentSelected(postion -> setCurrent(postion));

        if (!isGpsOpen()) {
            new AlertDialog.Builder(this).setTitle("提示")
                    .setMessage("定位服务尚未打开，定位导航功能可能无法正常使用，是否进入设置界面打开GPS")
                    .setNegativeButton("下次再说", (dialogInterface, i) -> {
                        dialogInterface.dismiss();
                    })
                    .setPositiveButton("好的", (dialogInterface, i) -> {
                        Intent intent1 = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(intent1);
                    })
                    .setCancelable(false).show();
        }
    }

    private void initNotification() {
        BasicPushNotificationBuilder builder = new BasicPushNotificationBuilder(mActivity);
        builder.statusBarDrawable = R.drawable.logo_title;
        builder.notificationFlags =Notification.FLAG_AUTO_CANCEL
                | Notification.FLAG_SHOW_LIGHTS;  //设置为自动消失和呼吸灯闪烁
        builder.notificationDefaults = Notification.DEFAULT_SOUND
                | Notification.DEFAULT_VIBRATE
                | Notification.DEFAULT_LIGHTS;  // 设置为铃声、震动、呼吸灯闪烁都要
        JPushInterface.setPushNotificationBuilder(1, builder);
        JPushInterface.setDefaultPushNotificationBuilder(builder);

//        CustomPushNotificationBuilder builder2 = new CustomPushNotificationBuilder(mActivity, R.layout.customer_notitfication_layout, R.id.icon, R.id.title, R.id.text,R.id.time);
//        builder2.statusBarDrawable = R.drawable.logo_title;
//        builder2.layoutIconDrawable = R.mipmap.logo;
//        builder2.developerArg0 = "developerArg2";
//        JPushInterface.setPushNotificationBuilder(2, builder2);
    }


    private boolean isGpsOpen() {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    private void registerNetWorkListener() {
        netReceiver = NetWorkReceiver.getInstance();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netReceiver, filter);
    }

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        wakeUp(intent);
        getEffectiveTime();
        getActivityPopup();
        checkVersion();

        checkToken();
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                VersionCheckBean versionCheckBean = (VersionCheckBean) result;
                if (versionCheckBean != null && versionCheckBean.isRel() == false) {

                    if (versionCheckBean != null && !TextUtils.isEmpty(versionCheckBean.getData().getDownloadUrl())) {
                        updateAppUtils.serverVersionCode(versionCheckBean.getData().getWeigh())
                                .serverVersionName(versionCheckBean.getData().getVersionName())
                                .apkPath(versionCheckBean.getData().getDownloadUrl())
                                .updateInfo(versionCheckBean.getData().getContent())
                                .apkSize(versionCheckBean.getData().getPackagesize())
                                .isForce(versionCheckBean.getData().getIsCompel() == 0 ? false : true)
                                .update();
                    }
                }
                break;
            case 1:
                EffectiveTimeBean bean = (EffectiveTimeBean) result;
                if (bean != null && bean.isRel() && bean.getData() != null) {
                    Cookie.save(getApplicationContext(), "actRent", bean.getData().getActRent());
                    Cookie.save(getApplicationContext(), "actTour", bean.getData().getActTour());
                    Cookie.save(getApplicationContext(), "insurePrice", bean.getData().getInsurePrice());
                    Cookie.save(getApplicationContext(), "actMember", bean.getData().getActMember());
                }
                break;
            case 2:
                final ActBean actBean = (ActBean) result;
                if (actBean != null && actBean.isRel() && actBean.getData() != null && actBean.getData().size() > 0) {
                    final ActBean.Act act = actBean.getData().get(0);
                    mPresenter.saveOnclick("0", String.valueOf(act.getId()));
                    promotionDialog = new PromotionDialog.Builder(this, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            promotionDialog.dismiss();
                            mPresenter.saveOnclick("1", String.valueOf(act.getId()));
                            postActivityPopup(act.getId());
                            startActivity(WebViewActivity.getIntent(getApplicationContext(), act.getUrl(), act.getName()));
                        }
                    }).setData(act).create();
                    promotionDialog.show();
                }
                break;
            case 3:

                break;
            default:
                break;
        }
    }


    /**
     * 检查token是否过期
     */
    private void checkToken() {
        Map<String, Object> heapmap = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        if (!TextUtils.isEmpty(OkGoUtil.getToken())) {
            map.put("Authorization", OkGoUtil.getToken());
            map.put("token", OkGoUtil.getToken());
            mPresenter.getData(RvFrameConfig.HOST, 3, ApiConfig.HTTP_URL_GET_TOKEN, BaseBean.class, map, heapmap, false);
        }
    }


    private void getActivityPopup() {
        Map<String, Object> map = new HashMap<>();
        if (!TextUtils.isEmpty(OkGoUtil.getToken())) {
            map.put("Authorization", OkGoUtil.getToken());
            mPresenter.getDataHead(RvFrameConfig.HOST, 2, ApiConfig.HTTP_URL_GET_ACT, ActBean.class, map, true);
        }
    }

    private void postActivityPopup(int id) {
        if (!TextUtils.isEmpty(OkGoUtil.getToken())) {
            Map<String, Object> map = new HashMap<>();
            map.put("Authorization", OkGoUtil.getToken());
            mPresenter.postData(1000, String.format(ApiConfig.HTTP_URL_POST_ACT, id), BaseBean.class, map, false);
        }
    }


    @OnClick({R2.id.rl_home, R2.id.rl_travel, R2.id.rl_camp, R2.id.rl_found, R2.id.rl_mine})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.rl_home) {
            setCurrent(TYPE_HOME_PAGE);
        } else if (id == R.id.rl_travel) {
            setCurrent(TYPE_TRAVEL);
        } else if (id == R.id.rl_camp) {
            setCurrent(TYPE_CAMP);
        } else if (id == R.id.rl_found) {
            setCurrent(TYPE_FOUND);
        } else if (id == R.id.rl_mine) {
            setCurrent(TYPE_MINE);
        }
    }

    private List<BaseWrapperFragment> getListFragment() {
        List<BaseWrapperFragment> list = new ArrayList<>();
        list.add(HomeFragment.getInstance(TYPE_HOME_PAGE));
        list.add(TourismFragment.getInstance(TYPE_TRAVEL));
        list.add(CampFragment.getInstance(TYPE_CAMP));
        list.add(DiscoveryFragment.getInstance(TYPE_FOUND));
        list.add(MineFragment.getInstance(TYPE_MINE));
        return list;
    }

    /**
     * 设置切换
     *
     * @param index
     */
    public void setCurrent(int index) {
        setViewStyle(ivHome, tvHome, index == TYPE_HOME_PAGE);
        setViewStyle(ivTravel, tvTravel, index == TYPE_TRAVEL);
        setViewStyle(ivCamp, tvCamp, index == TYPE_CAMP);
        setViewStyle(ivFound, tvFound, index == TYPE_FOUND);
        setViewStyle(ivMine, tvMine, index == TYPE_MINE);
        viewPager.setCurrentItem(index, false);
    }

    /**
     * 设置view的样式
     */
    private void setViewStyle(ImageView imageView, TextView textView, boolean isTrue) {
        imageView.setSelected(isTrue);
        textView.setTextColor(ContextCompat.getColor(this, isTrue ? R.color.gray_FFB74B : R.color.textMain));
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mAdapter != null) {
            mAdapter.getCurrentFragment().onActivityResult(requestCode, resultCode, data);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1001:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    updateAppUtils.download();
                } else {
                    Toast.makeText(getApplicationContext(), "授权失败,无法下载最新App", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
                exitApp();
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null && "home".equals(intent.getStringExtra("to"))) {
            setCurrent(TYPE_HOME_PAGE);
        } else if (intent != null && "travel".equals(intent.getStringExtra("to"))) {
            setCurrent(TYPE_TRAVEL);
        } else if (intent != null && "discovery".equals(intent.getStringExtra("to"))) {
            setCurrent(TYPE_FOUND);
        } else if (intent != null && "mine_coupons".equals(intent.getStringExtra("to"))) {
            setCurrent(TYPE_MINE);
            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_COUPONALL)
                    .navigation();
        } else if (intent != null && "mine_wallet".equals(intent.getStringExtra("to"))) {
            setCurrent(TYPE_MINE);
            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_WALLET)
                    .navigation();
        } else {
            wakeUp(intent);
        }
    }

    /****
     * 检测版本
     */
    private void checkVersion() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        String versionName = updateAppUtils.getAppVersionName(this);
        if (!TextUtils.isEmpty(versionName)) {
            mPresenter.getData(0, String.format(ApiConfig.HTTP_URL_VERSION_CHECK, versionName), VersionCheckBean.class, headMap, false);

        }
    }

    private void getEffectiveTime() {
        mPresenter.getData(1, ApiConfig.HTTP_URL_EFFECTIVE_TIME, EffectiveTimeBean.class, false);
    }

    /**
     * 退出APP
     */
    private void exitApp() {
        if (System.currentTimeMillis() - exitTime > 2000) {
            showToast("再按一次，退出程序");
            exitTime = System.currentTimeMillis();
        } else {
            finish();
        }
    }

    /**
     * 判断是否登录
     *
     * @return
     */
    private boolean isLogin() {
        if (TextUtils.isEmpty(OkGoUtil.getToken())) {
            return false;
        }
        return true;
    }

    /******
     * 唤醒Apk，跳转到webView页面
     * @param intent
     */
    private void wakeUp(Intent intent) {

        if ("webView".equals(intent.getStringExtra("to"))) {
            if (!TextUtils.isEmpty(OkGoUtil.getToken())) {
                Map<String, Object> header = new HashMap<>();
                header.put("Authorization", OkGoUtil.getToken());

                Map<String, Object> body = new HashMap<>();
                body.put("code", Cookie.getStringValue(getApplicationContext(), "code"));

                mPresenter.postData(RvFrameConfig.HOST, 10000, ApiConfig.HTTP_URL_RELATION_BIND, null, body, header, false);
            }
            ComponentName componentName = new ComponentName(this, "com.rv.share.WebViewActivity");
            Intent in = new Intent();
            in.setComponent(componentName);
            in.putExtra("url", intent.getStringExtra("url"));
            in.putExtra("title", intent.getStringExtra("title"));
            startActivity(in);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        DownloadAppUtils.unRegisterReceiver(getApplicationContext());
        if (netReceiver != null) {
            unregisterReceiver(netReceiver);
            netReceiver = null;
        }
    }
}
