package com.kfzs.duanduan;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.kfzs.appstore.utils.restful.KFZSNetwork;
import com.kfzs.duanduan.bean.KFIntentKeys;
import com.kfzs.duanduan.bll.UrlBll;
import com.kfzs.duanduan.datashare.provider.download.DownLoadInfo;
import com.kfzs.duanduan.db.DataSave;
import com.kfzs.duanduan.event.BigEvent;
import com.kfzs.duanduan.event.EventTypes;
import com.kfzs.duanduan.proto.ApiResponseOuterClass;
import com.kfzs.duanduan.proto.GameOuterClass;
import com.kfzs.duanduan.proto.RecommendedGameOuterClass;
import com.kfzs.duanduan.react.TabsHelper;
import com.kfzs.duanduan.services.DownloadTaskService;
import com.kfzs.duanduan.utils.dlg.HelperUtils;
import com.kfzs.duanduan.utils.dlg.SkipUtils;
import com.kfzs.duanduan.utils.net.APIRequest;
import com.kfzs.duanduan.utils.net.APIRequestInstance;
import com.kfzs.duanduan.utils.net.ResponseNetworkTask;
import com.kfzs.duanduan.view.AppHomepageAdvertisementDialog;
import com.kfzs.duanduan.view.DialogStorageLow;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.util.UMConfigUtils;
import com.sheep.jiuyan.samllsheep.R;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

import static com.kfzs.duanduan.services.DownloadTaskService.STATUS_ING;


public class ActMain extends BaseActivity {
    private static final String TAG = "ActMain";

    @BindView(R.id.other_container)
    LinearLayout other_container;

    public final static String INTEN_GAME_ID = "INTEN_GAME_ID";

    private DownloadTaskService mDownloadTaskService;

    private ImageView mImgDot;//下载按钮的小红点
    private AppHomepageAdvertisementDialog gameDialog;//预约窗口


    private final static int INTENT_GET_PERMISSION = 1;

    public TabsHelper tabsHelper;

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

    @Override
    public void initView() {
        KFZSApp.actMain = this;
        tabsHelper = new TabsHelper();
        getSA();//6.0以上获取必要权限
        HelperUtils.init();//初始化屏幕的高，density等
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        mImgDot = findViewById(R.id.img_download_manager_dot);
        tabsHelper.init();
        mDownloadTaskService = new DownloadTaskService(this);
    }

    @Override
    public void initListener() {
        findViewById(R.id.edt_main_search_enter).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ActMain.this, ActSearch.class));
            }
        });
        findViewById(R.id.img_download_manager).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mImgDot.setVisibility(View.GONE);
                startActivity(new Intent(ActMain.this, ActDownloadMgr.class));
                UMConfigUtils.onEvent(UMConfigUtils.Event.GAME_DOWNLOAD_MANAGER);
            }
        });
    }

    @Override
    public void initData() {

    }



    /**
     * 申请读写权限6.0
     */
    private void getSA() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return;
        }
        List<String> sa = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
            sa.add(Manifest.permission.READ_PHONE_STATE);
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            sa.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }
        if (sa.size() < 1) {//如果都已经授权了，不能空列表去请求，否则报异常
            return;
        }
        ActivityCompat.requestPermissions(this, sa.toArray(new String[]{}), INTENT_GET_PERMISSION);
    }


    /**
     * 权限申请的回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == INTENT_GET_PERMISSION) {
            boolean isOk = true;
            for (int result : grantResults) {
                if (result == PackageManager.PERMISSION_DENIED) {
                    isOk = false;
                    break;//只要有一个拒绝，就退出并提示
                }
            }
            if (!isOk) {
                Toast.makeText(ActMain.this, "权限获取失败，部分功能可能无法正常工作。", Toast.LENGTH_SHORT).show();
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

//
//    /**
//     * 传递事件
//     */
//    @Override
//    protected void onResume() {
//        super.onResume();
//    }


    /**
     * 传递事件
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        KFZSNetwork.stopByTag(TAG);
        EventBus.getDefault().unregister(this);
    }


    /**
     * 主要的事件广播接收更新处理
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(BigEvent event) {
        switch (event.getEventTypes()) {
            case TIPS_DOWN_ICON:
                mImgDot.setVisibility(View.VISIBLE);
                break;
            case STORAGE_LOW:
                DialogStorageLow.showDialog(this);
                break;
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        if (intent.hasExtra(INTEN_GAME_ID)) {
            tabsHelper.goToPostion(intent.getIntExtra(INTEN_GAME_ID, 0));
        } else {
            recreate();
            if (gameDialog != null) {
                gameDialog.dismiss();
            }
        }
    }

    /**
     *
     */
    @Override
    public void onBackPressed() {
        tabsHelper.onBackPressed();
    }

    /**
     * 获取首页弹窗Dialog广告
     */
    public void getAdvertisementDialogData() {
        Log.d(TAG, "getAdvertisementDialogData: " + UrlBll.AdvertisementApi.RECOMMENDED_ADVERTISEMENT);
        APIRequest bannerRequest = APIRequestInstance.getReqUrl(TAG, UrlBll.AdvertisementApi.RECOMMENDED_ADVERTISEMENT, null, new ResponseNetworkTask() {

            public void onSuccess(ApiResponseOuterClass.ApiResponse apiResponse) {
                showAdvertisementDialog(apiResponse);
            }

            @Override
            public void onFail(int code, String msg) {
                Log.d("FLY", "code: " + code + "\nmsg: " + msg);
            }
        }, null);
        KFZSNetwork.addRequest(bannerRequest);
    }

    private void showAdvertisementDialog(ApiResponseOuterClass.ApiResponse apiResponse) {
        if (apiResponse == null || apiResponse.getRecommendedGamesList().isEmpty()) {
            Log.d(TAG, "The showAdvertisementDialog response is null ");
            return;
        }

        final RecommendedGameOuterClass.RecommendedGame recommendeGame = apiResponse.getRecommendedGamesList().get(0);
        final String splashImageUrL = recommendeGame.getImageUrl();
        Log.d(TAG, "splashImageUrL: " + splashImageUrL);
        final String splashImageUr1 = recommendeGame.getTitle();
        Log.d(TAG, "splashImageUrL: " + splashImageUr1);
        final GameOuterClass.Game game = recommendeGame.getGame();
        Log.d(TAG, "game: " + game.toString());
        if (null != game || splashImageUrL != null || (!"".equals(splashImageUrL))) {
            if (gameDialog != null) {
                gameDialog.dismiss();
            }
            gameDialog = new AppHomepageAdvertisementDialog(ActMain.this);
            gameDialog.setShutImg(BitmapFactory.decodeResource(getResources(), R.drawable.btn_dialog_close));
            gameDialog.setBackground(splashImageUrL);
            if (getBtntext(recommendeGame).equals(getString(R.string.book_now))) {
                gameDialog.setCanceledOnTouchOutside(true);
                gameDialog.setCanceledOnTouchOutside(true);
                gameDialog.setCancelable(true);
                gameDialog.setDownloadOnOnclickListener(getBtntext(recommendeGame), new AppHomepageAdvertisementDialog.onDownloadOnclickListener() {
                    @Override
                    public void onDownloadClick() {
                        SkipUtils.getInstance().goGameDetails(ActMain.this,
                                recommendeGame.getGame().getId());
                    }
                });
                gameDialog.setBackgroundOnclickListener(new AppHomepageAdvertisementDialog.onBackOnclickListener() {
                    @Override
                    public void onClick() {
                        SkipUtils.getInstance().goGameDetails(ActMain.this, recommendeGame.getGame().getId());
                    }
                });


            } else {
                gameDialog.setDownloadOnOnclickListener(getBtntext(recommendeGame),
                        new AppHomepageAdvertisementDialog.onDownloadOnclickListener() {
                            @Override
                            public void onDownloadClick() {
                                final String downloadUrl = game.getDownloadUrl();
                                if (!TextUtils.isEmpty(downloadUrl) && !downloadUrl.endsWith(".apk")) {
                                    String url = UrlBll.GameApi.DOWNLOAD_REDIRECT + "game_id=" + game.getId() + "&channel=" + DataSave.getInstance().getChannelName();
                                    OkHttpUtils.get().url(url).build().execute(new StringCallback() {
                                        @Override
                                        public void onError(Call call, Exception e, int id) {
                                        }

                                        @Override
                                        public void onResponse(String response, int id) {
                                            if (!TextUtils.isEmpty(response)) {
                                                try {
                                                    JSONObject object = new JSONObject(response);
                                                    String realUrl = object.optString("DownloadUrl");
                                                    if (TextUtils.isEmpty(realUrl))
                                                        Toast.makeText(ActMain.this, "获取" + DataSave.getInstance().getChannelName() + "渠道下载地址失败", Toast.LENGTH_SHORT).show();
                                                    else {
                                                        KFZSApp.getInstance().mRealDownloadUrl.put(realUrl, downloadUrl);
                                                        DownLoadInfo downloadInfo = addNewDownloadTask(game.getGameName(), realUrl, game.getPackageName(),
                                                                Integer.parseInt(game.getVersionCode()), game.getIconImage(), game.getSize(), game.getId(), STATUS_ING);
                                                        mDownloadTaskService.start(downloadInfo);
                                                        EventBus.getDefault().post(BigEvent.get()
                                                                .setEventTypes(EventTypes.TIPS_DOWN_ICON));
                                                    }
                                                } catch (JSONException e) {
                                                    e.printStackTrace();
                                                }
                                            }

                                        }
                                    });
                                } else {
//                                    if(SpUtils.getClick(ActMain.this)){
//                                        SpUtils.saveClick(ActMain.this, false);
//                                    }else{
//                                        DialogAccountAbnormal.showDialog((Activity) ActMain.this,null, "当前网络处于非WIFI状态，确定下载吗？", "取消", "确定" );
//                                        return;
//                                    }
                                    DownLoadInfo downloadInfo = addNewDownloadTask(game.getGameName(),
                                            downloadUrl,
                                            game.getPackageName(),
                                            Integer.parseInt(game.getVersionCode()),
                                            game.getIconImage(),
                                            game.getSize(),
                                            game.getId(),
                                            STATUS_ING);

                                    mDownloadTaskService.start(downloadInfo);
                                    EventBus.getDefault().post(BigEvent.get()
                                            .setEventTypes(EventTypes.TIPS_DOWN_ICON));
                                }
                            }
                        });

                gameDialog.setBackgroundOnclickListener(new AppHomepageAdvertisementDialog.onBackOnclickListener() {
                    @Override
                    public void onClick() {
                        Intent intent = new Intent(ActMain.this, ActGameDetails.class);
                        intent.putExtra(KFIntentKeys.EXTRA_GAME_ID, recommendeGame.getGameId() + "");
                        ActMain.this.startActivity(intent);
                    }
                });
            }


            gameDialog.show();
        } else {
            Log.d(TAG, "showAdvertisementDialog: game or splashImageUrL is null");
        }
    }

    private DownLoadInfo addNewDownloadTask(String gameName, String downloadUrl, String packageName,
                                    int versionCode, String iconUrl, String size, Integer gameId, int state) {

        final DownLoadInfo task = new DownLoadInfo();
        task.setMIconUrl(iconUrl);
        task.setMGameName(gameName);
        task.setMDownloadUrl(downloadUrl);
        task.setMPackageName(packageName);
        task.setMVersionCode(versionCode);
        task.setMTotalSize(Double.valueOf(size));
        task.setMGameID(gameId);
        task.setMStatus(state);
        new Thread(new Runnable() {
            @Override
            public void run() {
                mDownloadTaskService.addDownloadTask(task);
            }
        }).start();
        return task;
    }


    /**
     * 返回首页启动广告弹窗的按钮文本
     *
     * @param game
     * @return
     */
    private String getBtntext(RecommendedGameOuterClass.RecommendedGame game) {
        String backStr = "立即下载";
        if (TextUtils.isEmpty(game.getApkUrl())) {
            backStr = getString(R.string.book_now);
        }
        return backStr;
    }

}
