package com.gh.base;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gh.common.constant.Config;
import com.gh.common.util.DataUtils;
import com.gh.common.util.DialogUtils;
import com.gh.common.util.DisplayUtils;
import com.gh.common.util.FileUtils;
import com.gh.common.util.NetworkUtils;
import com.gh.common.util.PackageUtils;
import com.gh.common.util.PlatformUtils;
import com.gh.common.util.ShareUtils;
import com.gh.common.view.DownloadDialog;
import com.gh.download.DataWatcher;
import com.gh.download.DownloadEntity;
import com.gh.download.DownloadManager;
import com.gh.gamecenter.DownloadManagerActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.entity.ApkEntity;
import com.gh.gamecenter.entity.GameEntity;
import com.gh.gamecenter.eventbus.EBDownloadStatus;
import com.gh.gamecenter.eventbus.EBPackage;
import com.gh.gamecenter.manager.DataCollectionManager;
import com.gh.gamecenter.manager.PackageManager;
import com.tencent.tauth.Tencent;

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

/**
 * Created by Administrator on 2016/9/19.
 */
public abstract class DetailActivity extends BaseActivity implements View.OnClickListener {

    protected TextView actionbar_tv_title;
    protected RecyclerView detail_rv_show;
    protected LinearLayout detail_ll_bottom;
    protected TextView detail_tv_download;
    protected ProgressBar detail_pb_progressbar;
    protected TextView detail_tv_per;
    protected LinearLayout reuse_ll_loading;
    protected LinearLayout reuse_no_connection;
    protected ImageView iv_share;

    protected GameEntity gameEntity;
    protected DownloadEntity mDownloadEntity;

    protected String entrance;
    protected String name;
    protected String title;
    protected String downloadAddWord;

    protected Handler handler = new Handler();

    private DataWatcher dataWatcher = new DataWatcher() {
        @Override
        public void onDataChanged(DownloadEntity downloadEntity) {
            if (gameEntity != null && gameEntity.getApk().size() == 1) {
                String url = gameEntity.getApk().get(0).getUrl();
                if (url.equals(downloadEntity.getUrl())) {
                    if (!"pause".equals(DownloadManager.getInstance(DetailActivity.this).
                            getStatus(downloadEntity.getUrl()))) {
                        mDownloadEntity = downloadEntity;
                        invalidate();
                    }
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        entrance = getIntent().getStringExtra("entrance");

        View contentView = View.inflate(this, R.layout.activity_detail, null);

        // 添加分享图标
        iv_share = new ImageView(this);
        iv_share.setImageResource(R.drawable.share_icon);
        iv_share.setOnClickListener(this);
        iv_share.setVisibility(View.GONE);
        iv_share.setPadding(DisplayUtils.dip2px(this, 13),DisplayUtils.dip2px(this, 11)
                ,DisplayUtils.dip2px(this, 11),DisplayUtils.dip2px(this, 13));
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                DisplayUtils.dip2px(this, 48), DisplayUtils.dip2px(this, 48));
        params.addRule( RelativeLayout.CENTER_VERTICAL);
        params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT );
        RelativeLayout reuse_actionbar = (RelativeLayout) contentView.findViewById(
                R.id.reuse_actionbar);
        reuse_actionbar.addView(iv_share, params);

        init(contentView);

        actionbar_tv_title = (TextView) findViewById(R.id.actionbar_tv_title);
        detail_rv_show = (RecyclerView) findViewById(R.id.detail_rv_show);
        detail_ll_bottom = (LinearLayout) findViewById(R.id.detail_ll_bottom);
        detail_tv_download = (TextView) findViewById(R.id.detail_tv_download);
        detail_pb_progressbar = (ProgressBar) findViewById(R.id.detail_pb_progressbar);
        detail_tv_per = (TextView) findViewById(R.id.detail_tv_per);
        reuse_ll_loading = (LinearLayout) findViewById(R.id.reuse_ll_loading);
        reuse_no_connection = (LinearLayout) findViewById(R.id.reuse_no_connection);

        detail_ll_bottom.setOnClickListener(this);
        detail_tv_download.setOnClickListener(this);
        detail_pb_progressbar.setOnClickListener(this);
        detail_tv_per.setOnClickListener(this);
        reuse_no_connection.setOnClickListener(this);

    }

    //接收QQ或者QQ空间分享回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == com.tencent.connect.common.Constants.REQUEST_QQ_SHARE
                || requestCode == com.tencent.connect.common.Constants.REQUEST_QZONE_SHARE) {
            Tencent.onActivityResultData(requestCode, resultCode, data, ShareUtils.getInstance(this).QqShareListener);
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (gameEntity != null
                && gameEntity.getApk() != null
                && gameEntity.getApk().size() == 1) {
            initDownload(true);
        }
        DownloadManager.getInstance(this).addObserver(dataWatcher);
    }

    @Override
    protected void onPause() {
        super.onPause();
        DownloadManager.getInstance(this).removeObserver(dataWatcher);
    }

    protected void initDownload(boolean isCheck) {
        if (Config.isShow(this)) {
            detail_ll_bottom.setVisibility(View.VISIBLE);
            detail_rv_show.setPadding(0, 0, 0,
                    DisplayUtils.dip2px(getApplicationContext(), 44));
        } else {
            detail_ll_bottom.setVisibility(View.GONE);
            detail_rv_show.setPadding(0, 0, 0, 0);
        }
        if (gameEntity != null && "光环助手".equals(gameEntity.getName())) {
            detail_ll_bottom.setVisibility(View.GONE);
            detail_rv_show.setPadding(0, 0, 0, 0);
        } else if (gameEntity == null || gameEntity.getApk().isEmpty()) {
            detail_tv_download.setVisibility(View.VISIBLE);
            detail_pb_progressbar.setVisibility(View.GONE);
            detail_tv_per.setVisibility(View.GONE);
            detail_tv_download.setText("暂无下载");
            detail_tv_download.setBackgroundResource(R.drawable.game_item_btn_pause_style);
            detail_tv_download.setTextColor(0xFF999999);
            detail_tv_download.setClickable(false);
        } else {
            detail_tv_download.setVisibility(View.VISIBLE);
            detail_pb_progressbar.setVisibility(View.GONE);
            detail_tv_per.setVisibility(View.GONE);
            boolean isInstalled = false;
            if (gameEntity.getApk() != null && gameEntity.getApk().size() == 1
                    && PackageManager.isInstalled(gameEntity.getApk().get(0).getPackageName())) {
                isInstalled = true;
            }
            if (isInstalled) {
                if (PackageManager.isCanUpdate(gameEntity.getApk().get(0).getPackageName())) {
                    if (TextUtils.isEmpty(downloadAddWord)) {
                        detail_tv_download.setBackgroundResource(
                                R.drawable.game_item_btn_download_style);
                        detail_tv_download.setText(String.format("更新《%s》",
                                gameEntity.getName()));
                    } else {
                        detail_tv_download.setBackgroundResource(
                                R.drawable.game_item_btn_download_style);
                        detail_tv_download.setText(String.format("更新《%s》%s",
                                gameEntity.getName(), downloadAddWord));
                    }
                } else {
                    if (gameEntity.getTag() != null && gameEntity.getTag().size() != 0
                            && !PackageUtils.isSignature(this, gameEntity.getApk().get(0).getPackageName())
                            ) {
                        if (TextUtils.isEmpty(downloadAddWord)) {
                            detail_tv_download.setBackgroundResource(
                                    R.drawable.game_item_btn_plugin_style);
                            detail_tv_download.setText(String.format("插件化《%s》",
                                    gameEntity.getName()));
                        } else {
                            detail_tv_download.setBackgroundResource(
                                    R.drawable.game_item_btn_plugin_style);
                            detail_tv_download.setText(String.format("插件化《%s》%s",
                                    gameEntity.getName(), downloadAddWord));
                        }
                    } else {
                        if (TextUtils.isEmpty(downloadAddWord)) {
                            detail_tv_download.setBackgroundResource(
                                    R.drawable.game_item_btn_launch_style);
                            detail_tv_download.setText(String.format("启动《%s》",
                                    gameEntity.getName()));
                        } else {
                            detail_tv_download.setBackgroundResource(
                                    R.drawable.game_item_btn_launch_style);
                            detail_tv_download.setText(String.format("启动《%s》%s",
                                    gameEntity.getName(), downloadAddWord));
                        }
                    }
                }
            } else {
                if (TextUtils.isEmpty(downloadAddWord)) {
                    detail_tv_download.setBackgroundResource(
                            R.drawable.game_item_btn_download_style);
                    detail_tv_download.setText(String.format("下载《%s》",
                            gameEntity.getName()));
                } else {
                    detail_tv_download.setBackgroundResource(
                            R.drawable.game_item_btn_download_style);
                    detail_tv_download.setText(String.format("下载《%s》%s",
                            gameEntity.getName(), downloadAddWord));
                }
            }
        }
        if (isCheck && gameEntity != null
                && gameEntity.getApk() != null
                && gameEntity.getApk().size() == 1) {
            String url = gameEntity.getApk().get(0).getUrl();
            List<DownloadEntity> list = DownloadManager.getInstance(getApplicationContext()).getAll();
            for (DownloadEntity entry : list) {
                if (url.equals(entry.getUrl())) {
                    mDownloadEntity = entry;
                    detail_tv_download.setVisibility(View.GONE);
                    detail_pb_progressbar.setVisibility(View.VISIBLE);
                    detail_tv_per.setVisibility(View.VISIBLE);
                    invalidate();
                    break;
                }
            }
        }
    }

    private void invalidate() {
        detail_pb_progressbar.setProgress((int) (mDownloadEntity.getPercent() * 10));
        detail_tv_per.setTextColor(0xFFFFFFFF);
        switch (mDownloadEntity.getStatus()) {
            case downloading:
            case pause:
            case timeout:
            case neterror:
            case waiting:
                detail_tv_per.setText("下载中");
                break;
            case done:
                detail_tv_per.setText("安装");
                if (mDownloadEntity.isPluggable()
                        && PackageManager.isInstalled(mDownloadEntity.getPackageName())) {
                    detail_pb_progressbar.setProgressDrawable(getResources().getDrawable(R.drawable.progressbar_plugin_radius_style));
                } else {
                    detail_pb_progressbar.setProgressDrawable(getResources().getDrawable(R.drawable.progressbar_normal_radius_style));
                }
                break;
            case cancel:
            case hijack:
                initDownload(false);
                break;
            default:
                break;
        }
    }

    // 接收下载被删除消息
    public void onEvent(EBDownloadStatus status) {
        if ("delete".equals(status.getStatus())
                && gameEntity != null
                && gameEntity.getApk() != null
                && gameEntity.getApk().size() == 1) {
            String url = gameEntity.getApk().get(0).getUrl();
            if (url.equals(status.getUrl())) {
                initDownload(false);
            }
        }
    }

    // 接受安装、卸载消息
    public void onEventMainThread(EBPackage busFour) {
        if (gameEntity != null
                && gameEntity.getApk() != null
                && gameEntity.getApk().size() == 1) {
            String packageName = gameEntity.getApk().get(0).getPackageName();
            if (packageName.equals(busFour.getPackageName())) {
                initDownload(false);
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (v == detail_tv_download) {
            if (gameEntity != null && !gameEntity.getApk().isEmpty()) {
                if (gameEntity.getApk().size() == 1) {
                    if (NetworkUtils.isWifiConnected(this)) {
                        download();
                    } else {
                        DialogUtils.showDownloadDialog(this, new DialogUtils.ConfiremListener() {
                            @Override
                            public void onConfirem() {
                                download();
                            }
                        });
                    }
                } else {
                    DownloadDialog.getInstance(this)
                            .showPopupWindow(v, gameEntity, entrance, name + ":" + title);
                }
            } else {
                toast("稍等片刻~！游戏正在上传中...");
            }
        } else if (v == detail_pb_progressbar || v == detail_tv_per) {
            String str = detail_tv_per.getText().toString();
            if ("下载中".equals(str)) {
                startActivity(new Intent(this, DownloadManagerActivity.class));
            } else if ("安装".equals(str)) {
                PackageUtils.launchSetup(this, mDownloadEntity.getPath());
            }
        }
    }

    private void download() {
        String str = detail_tv_download.getText().toString();
        if (str.contains("启动")) {
            Map<String, Object> kv = new HashMap<>();
            kv.put("版本", gameEntity.getApk().get(0).getPlatform());
            kv.put("页面", name);
            DataUtils.onEvent(DetailActivity.this, "游戏启动", gameEntity.getName(), kv);

            PackageUtils.launchApplicationByPackageName(getApplicationContext(),
                    gameEntity.getApk().get(0).getPackageName());
        } else {
            String method;
            if (str.contains("更新")) {
                method = "更新";
            } else if (str.contains("插件化")) {
                method = "插件化";
            } else {
                method = "下载";
            }
            ApkEntity apkEntity = gameEntity.getApk().get(0);
            String msg = FileUtils.isCanDownload(apkEntity.getSize());
            if (TextUtils.isEmpty(msg)) {
                Map<String, Object> kv = new HashMap<>();
                kv.put("版本", apkEntity.getPlatform());
                kv.put("状态", "下载开始");
                DataUtils.onEvent(DetailActivity.this, "游戏下载", gameEntity.getName(), kv);

                Map<String, Object> kv2 = new HashMap<>();
                kv2.put("版本", apkEntity.getPlatform());
                kv2.put("状态", "下载开始");
                kv2.put("页面", name);
                kv2.put("位置", entrance);
                DataUtils.onEvent(DetailActivity.this, "游戏下载位置", gameEntity.getName(), kv2);

                Map<String, Object> kv3 = new HashMap<>();
                kv3.put(entrance, "下载数");
                kv3.put(entrance, "下载开始");
                DataUtils.onEvent(DetailActivity.this, "应用数据", gameEntity.getName(), kv3);

                Map<String, Object> map = new HashMap<>();
                map.put("game", gameEntity.getName());
                map.put("game_id", gameEntity.getId());
                map.put("method", method.equals("下载") ? "正常" : method);
                map.put("platform", PlatformUtils.getInstance(getApplicationContext())
                                .getPlatformName(gameEntity.getApk().get(0).getPlatform()));
                map.put("status", "开始");
                map.put("location", name + ":" + title);
                map.put("entrance", entrance);
                map.put("btn_status", method);
                map.put("network", NetworkUtils.getConnectedType(this));
                DataCollectionManager.onEvent(this, "download", map);

                DownloadManager.createDownload(this, apkEntity, gameEntity, method, entrance, name + ":" + title);

                detail_tv_download.setVisibility(View.GONE);
                detail_pb_progressbar.setVisibility(View.VISIBLE);
                detail_tv_per.setVisibility(View.VISIBLE);
                detail_pb_progressbar.setProgress(0);
                detail_tv_per.setText("0.0%");

                DownloadManager.getInstance(DetailActivity.this).putStatus(apkEntity.getUrl(), "downloading");
            } else {
                toast(msg);
            }
        }
    }

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

}
