package com.sheep.gamegroup.view.activity;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.VideoView;

import com.bumptech.glide.Glide;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.model.entity.Advertising;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.RouserArticlesEntity;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.GlideImageLoader;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.LogUtil;
import com.sheep.gamegroup.util.RxjavaCountDownTimer;
import com.sheep.gamegroup.util.SysAppUtil;
import com.sheep.gamegroup.util.TestUtil;
import com.sheep.jiuyan.samllsheep.BuildConfig;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;

import org.afinal.simplecache.ApiKey;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static com.sheep.gamegroup.util.CommonUtil.JUMP_FIND_ACT;
import static com.sheep.gamegroup.util.CommonUtil.JUMP_FIND_GMAE;
import static com.sheep.gamegroup.util.CommonUtil.JUMP_FIND_INFORMATION;
import static com.sheep.gamegroup.util.CommonUtil.JUMP_FIND_RECOMMEND;
import static com.sheep.gamegroup.util.CommonUtil.JUMP_GMAE;
import static com.sheep.gamegroup.util.CommonUtil.JUMP_WATCH_FOCUS;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.AD_SPLASH;

/**
 * Created by ljy on 2018/3/9.
 */

public class SplashAct extends BaseActivity implements EasyPermissions.PermissionCallbacks {

    @BindView(R.id.splash_bg)
    ImageView splash_bg;
    @BindView(R.id.splash_skip)
    TextView splash_skip;
//    @BindView(R.id.splash_know_ad_tv)
    TextView splash_know_ad_tv;


    @BindView(R.id.splash_video_view)
    VideoView splash_video_view;
    @BindView(R.id.btn_join)
    TextView btnJoin;
    private Activity activity;

    VideoView videoView;
    private boolean isClick;

    private static final int PERMISSON_REQUESTCODE = 1;
    /**
     * 需要进行检测的权限数组
     */
    protected String[] needPermissions = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_PHONE_STATE
    };
    private RxjavaCountDownTimer timer;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        try {
            super.onCreate(savedInstanceState);
            hideSystemStatusBar();
            hideSystemNavBar();
            if (!isTaskRoot()) {
                LogUtil.println("SheepApp SplashAct isTaskRoot");
                finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        LogUtil.println("SplashAct onStart");
        requestCodePermissions();
    }

    private boolean isRequestCodePermissions = true;//是否正在获取权限或者没有获取到权限
    @AfterPermissionGranted(PERMISSON_REQUESTCODE)
    private void requestCodePermissions() {
        if (!EasyPermissions.hasPermissions(this, needPermissions)) {
            EasyPermissions.requestPermissions(this, "应用需要这些权限", PERMISSON_REQUESTCODE, needPermissions);
        } else {
            isRequestCodePermissions = false;
            sendHandlerMessages(1000);
        }
    }

    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    if(!isRequestCodePermissions && !isLoadingData && timerIsFinish())
                        gotoNext();
                    else
                        sendHandlerMessages(100);
                    break;
                case 1:
                    if(SysAppUtil.isNewSmallSheep() || TestUtil.isDev()){//新版本只显示引导页面，不展示弹窗和开屏广告
                        isLoadingData = false;
                        sendHandlerMessages(200);
                    } else {
                        Advertising cacheAdvertising = DataUtil.getInstance().getCacheResult(ApiKey.advertisements(1), Advertising.class);
                        if (cacheAdvertising != null) {
                            isLoadingData = false;
                            advertising = cacheAdvertising;
                            try {
                                loadAdvertising();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            SheepApp.getInstance().getNetComponent().getApiService().getAdvertising(1)
                                    .subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(new SheepSubscriber<BaseMessage>(activity) {
                                        @Override
                                        public void onNext(BaseMessage baseMessage) {
                                            DataUtil.getInstance().resetCacheTime(ApiKey.advertisements(1), 3600*5);//开屏广告最多缓存5个小时
                                            isLoadingData = false;
                                            advertising = baseMessage.getData(Advertising.class);
                                            try {
                                                loadAdvertising();
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }

                                        @Override
                                        public void onError(BaseMessage baseMessage) {
                                            isLoadingData = false;
                                            sendHandlerMessages(10);
                                        }
                                    });
                        }
                    }
                    break;
            }

        }
    };

    private boolean timerIsFinish() {
        return timer == null || splash_skip.getVisibility() == View.INVISIBLE;
    }

    private void gotoNext() {
        if (!isClick) {
            isClick = true;
            Jump2View.getInstance().gotoGuide(activity);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.splash_activity;
    }

    @BindView(R.id.login_bg_img)
    ImageView login_bg_img;
    @Override
    public void initView() {
        activity = this;
        GlideImageLoader.setImage(login_bg_img, "http://cdngame.kuaifazs.com/login_bg_img.png");
//        if(BuildConfig.DEBUG){
//            Jump2View.getInstance().checkCommendApp(activity, null);
//        } else {
//            mHandler.sendEmptyMessageDelayed(1, 500);
//        }
    }

    @Override
    public void initListener() {

    }
    private boolean isLoadingData = true;//是否正在获取开屏广告数据
    private Advertising advertising;
    @Override
    public void initData() {
        SheepApp.getInstance().getNetComponent().getApiService().checkUserFirst()
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                            @Override
                            public void onNext(BaseMessage baseMessage) {
                                boolean isNewSmallSheep = baseMessage.getData(Boolean.class);
                                DataUtil.getInstance().setIsNewSmallSheep(isNewSmallSheep);
                                mHandler.sendEmptyMessageDelayed(1, 300);
                            }

                            @Override
                            public void onError(BaseMessage baseMessage) {
                                //访问出错时，认为不是新设备
                                DataUtil.getInstance().setIsNewSmallSheep(false);
                                mHandler.sendEmptyMessageDelayed(1, 300);
                            }
                        });
    }

    private void loadAdvertising() {
        if(advertising.isImage()) {
            Glide.with(activity).load(advertising.getDisplay_src()).into(splash_bg);
//            btnJoin.setVisibility(View.GONE);
            splash_video_view.setVisibility(View.GONE);
        } else {
            Uri uri = Uri.parse(advertising.getDisplay_src());
            splash_video_view.setVisibility(View.VISIBLE);
            videoView = splash_video_view;
            videoView.setOnInfoListener(new MediaPlayer.OnInfoListener() {
                @Override
                public boolean onInfo(MediaPlayer mediaPlayer, int what, int extra) {
                    if(!mediaPlayer.isLooping())
                        mediaPlayer.setLooping(true);
                    LogUtil.println("onInfo what = " + what + " extra = " + extra);
                    if(MediaPlayer.MEDIA_INFO_BUFFERING_START == what){
                        splash_bg.setVisibility(View.GONE);
//                        btnJoin.setVisibility(View.GONE);
                    }
                    return false;
                }
            });
            videoView.setVideoURI(uri);
            videoView.start();
            videoView.requestFocus();
        }

        if(splash_know_ad_tv != null)
            splash_know_ad_tv.setVisibility(View.VISIBLE);
        mHandler.removeMessages(0);
        if(advertising.getShow_time() > 0) {
            splash_skip.setVisibility(View.VISIBLE);
            timer = RxjavaCountDownTimer.getInstance(/*BuildConfig.DEBUG ? 10 : */advertising.getShow_time())
                    .setOnTickListener(new RxjavaCountDownTimer.OnTickListener() {
                        @Override
                        public void onFinish() {
                            splash_skip.setVisibility(View.INVISIBLE);//设置为INVISIBLE代表定时器结束
//                            btnJoin.setVisibility(View.VISIBLE);
                            if (isResume)
                                sendHandlerMessages(10);
                        }

                        @Override
                        public void onTicker(long time) {
                            splash_skip.setText(activity.getString(R.string.tip_skip, time));
                        }
                    }).start();
        } else {
//            btnJoin.setVisibility(View.VISIBLE);
            sendHandlerMessages(1000);
        }
    }
    private boolean isResume = false;
    @Override
    protected void onResume() {
        super.onResume();
        isResume = true;
        if(videoView != null)
            videoView.resume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        isResume = false;
        if(videoView != null)
            videoView.pause();
    }

    @Override
    public void onPermissionsGranted(int i, @NonNull List<String> list) {
        recreate();
    }

    @Override
    public void onPermissionsDenied(int i, @NonNull List<String> list) {
        showMissingPermissionDialog();
    }

    private void showMissingPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("当前应用缺少必要权限。请点击\"设置\"-\"权限\"-打开所需权限。");

        // 拒绝, 退出应用
        builder.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });

        builder.setPositiveButton("设置",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppSettings();
                    }
                });

        builder.setCancelable(false);

        builder.show();
    }

    /**
     * 启动应用的设置
     */
    private void startAppSettings() {
        Intent intent = new Intent(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }


    @OnClick({R.id.btn_join, R.id.splash_skip, R.id.splash_know_ad_tv, R.id.splash_bg, R.id.splash_video_view,R.id.splash_click_view})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_join:
            case R.id.splash_skip:
                gotoNext();
                break;
            case R.id.splash_bg:
            case R.id.splash_video_view:
            case R.id.splash_know_ad_tv:
            case R.id.splash_click_view:
                if(advertising != null) {
                    goAdLink(activity, advertising);
                    AD_SPLASH.onEvent("ad_id", advertising.getId());
                }else {
                    gotoNext();
                }
                break;
        }
    }

    public static void goAdLink(Activity activity, Advertising advertising) {
        if(advertising != null){
            switch(advertising.getLinkType()){//转跳类型1：H5外部 2：H5内部 3：试玩赚钱 4:单个任务 5：信用卡 6:微信二维码 7：连续任务 8：打卡赚钱
                case 1:
                    Jump2View.getInstance().goWeb(activity, advertising.getLink());
                    break;
                case 2:
                    Jump2View.getInstance().goWeb(activity, advertising.getLink(), advertising.getName());
                    break;
                case 3:
                    Jump2View.getInstance().goTryplayView(activity, null);
                    break;
                case 4:
                    Jump2View.getInstance().goTaskDetailView(activity, advertising.getLink_id());
                    break;
                case 5:
                    Jump2View.getInstance().goCreditCardTaskList(activity, null);
                    break;
                case 6:
                    Jump2View.getInstance().goWeb(activity, advertising.getLink(), "微信二维码辅助好友注册任务");
                    break;
                case 7:
                    Jump2View.getInstance().goSequentialTaskView(activity);
                    break;
                case 8:
                    Jump2View.getInstance().goSignCardAct(activity, null);
                    break;
                case 15://小米游戏列表
                    Jump2View.getInstance().goXiaomiGameList(activity, null);
                    break;
                case JUMP_GMAE://游戏详情
                    Jump2View.getInstance().goPlayGameDetail(activity, advertising.getLink_id());
                    break;
                case JUMP_FIND_RECOMMEND://发现--推荐
                case JUMP_FIND_ACT://发现--活动
                case JUMP_FIND_INFORMATION://webView资讯
                case JUMP_FIND_GMAE://发现中的游戏详情
                    Jump2View.getInstance().goFindItem(activity, advertising.getLink_id());
                    break;
                case JUMP_WATCH_FOCUS://看点
                    Jump2View.getInstance().goWatchFocus(activity, advertising.getLink_id());
                    break;
            }
        }
    }

    @Override
    public void onActivityReenter(int resultCode, Intent data) {
        super.onActivityReenter(resultCode, data);
        isRequestCodePermissions = false;
        sendHandlerMessages(10);
    }
    private void sendHandlerMessages(int time){
        try {
            mHandler.removeMessages(0);
            mHandler.sendEmptyMessageDelayed(0, /*BuildConfig.DEBUG ? 100 :*/ time);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(timer != null)
            timer.clear();
        try {
            mHandler.removeMessages(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
