package com.sheep.gamegroup.view.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.os.Build;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.download.DownloadTask;
import com.sheep.gamegroup.event.BigEvent;
import com.sheep.gamegroup.util.DownloadUtil;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.FindApp;
import com.sheep.gamegroup.model.entity.FindItem;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.GlideImageLoader;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.LogUtil;
import com.sheep.gamegroup.util.SysAppUtil;
import com.sheep.gamegroup.helper.TaskHelper;
import com.sheep.gamegroup.util.TimeUtil;
import com.sheep.gamegroup.util.ViewHolder;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.view.adapter.AdbCommonRecycler;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.PackageUtil;
import com.sheep.jiuyan.samllsheep.utils.TitleBarUtils;

import org.afinal.simplecache.ApiKey;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

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

import butterknife.BindView;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

import static android.content.Intent.ACTION_PACKAGE_ADDED;
import static android.content.Intent.ACTION_PACKAGE_REMOVED;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.FIND_SHARE;

/**
 * Created by realicing on 2018/5/10.
 * realicing@sina.com
 */
public class ActFindInformation extends BaseActivity implements Action1<Integer> {
    @Override
    protected int getLayoutId() {
        return R.layout.net_empty_fresh_list;
    }

    private int id;

    /**
     * 视频全屏参数
     */


    protected final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    private View customView;
    private FrameLayout fullscreenContainer;
    private WebChromeClient.CustomViewCallback customViewCallback;


    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    @BindView(R.id.empty_view)
    View empty_view;
    @BindView(R.id.check_net_ll)
    View check_net_ll;
    @BindView(R.id.view_list)
    RecyclerView view_list;
    WebView webView;

    @Override
    public void initView() {
        id = getIntent().getIntExtra("id", 0);

        TitleBarUtils.getInstance()
                .setTitle(this,"详情")
                .setTitleFinish(this)
                .setRightImgBotton(this, R.mipmap.share, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        FIND_SHARE.onEvent("find_id", id);
                        Jump2View.getInstance().tryShare(ActFindInformation.this, "find_share_url", "find_id", id);
                    }
                });

        EventBus.getDefault().register(this);
        Aria.download(this).register();

        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initData();
            }
        });

        view_list.setLayoutManager(new LinearLayoutManager(SheepApp.getInstance()));
        view_list.setAdapter(new AdbCommonRecycler<String>(SheepApp.getInstance(), list) {

            @Override
            public int getItemViewType(int position) {
                return position;
            }

            @Override
            public int getViewIdByType(int type) {//type来源于 getItemViewType 返回的值
                String item = list.get(type);
                switch (item) {
                    case "top":
                        return R.layout.find_information_top;
                    case "bottom":
                    default:
                        return R.layout.find_information_bottom;
                }
            }

            @Override
            public void convert(ViewHolder holder, final String item) {
                switch (item) {
                    case "top":
                        loadTop(holder.itemView);
                        break;
                    default:
                        loadBottom((ViewGroup) holder.itemView);
                        break;
                }
            }
        });
    }


    public void initWebView() {
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
//                WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);

        WebChromeClient wvcc = new WebChromeClient();
        WebSettings webSetting = webView.getSettings();
        webSetting.setJavaScriptEnabled(true);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(true);
        webSetting.setAppCacheEnabled(true);
        webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSetting.setCacheMode(android.webkit.WebSettings.LOAD_NO_CACHE);


        webSetting.setCacheMode(android.webkit.WebSettings.LOAD_DEFAULT);
        webSetting.setLoadWithOverviewMode(true);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        webView.setWebChromeClient(wvcc);
        WebViewClient wvc = new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //Android8.0以下的需要返回true 并且需要loadUrl；8.0之后效果相反
                if(Build.VERSION.SDK_INT<26) {
                    webView.loadUrl(url);
                    Jump2View.getInstance().goWeb(ActFindInformation.this, url);
                    return true;
                }
                return false;
            }
        };
        webView.setWebChromeClient(new WebChromeClient() {

            /**视频播放相关的方法*
             *
             */


            @Override
            public View getVideoLoadingProgressView() {
                FrameLayout frameLayout = new FrameLayout(ActFindInformation.this);
                frameLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                return frameLayout;
            }

            @Override
            public void onShowCustomView(View view, CustomViewCallback callback) {
                super.onShowCustomView(view, callback);
                showCustomView(view, callback);
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//设置横屏
            }

            @Override
            public void onHideCustomView() {
                hideCustomView();
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//设置竖屏
                super.onHideCustomView();
            }
        });
        webView.setWebViewClient(wvc);
    }

    /**
     * 视频播放全屏
     */

    private void showCustomView(View view, WebChromeClient.CustomViewCallback callback) {
        // if a view already exists then immediately terminate the new one
        if (customView != null) {
            callback.onCustomViewHidden();
            return;
        }

        ActFindInformation.this.getWindow().getDecorView();

        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        fullscreenContainer = new FullscreenHolder(ActFindInformation.this);
        fullscreenContainer.addView(view, COVER_SCREEN_PARAMS);
        decor.addView(fullscreenContainer, COVER_SCREEN_PARAMS);
        customView = view;
        setStatusBarVisibility(false);
        customViewCallback = callback;
    }

    /**
     * 隐藏视频全屏
     */


    private void hideCustomView() {
        if (customView == null) {
            return;
        }

        setStatusBarVisibility(true);
        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        decor.removeView(fullscreenContainer);
        fullscreenContainer = null;
        customView = null;
        customViewCallback.onCustomViewHidden();
        webView.setVisibility(View.VISIBLE);
    }

    /**
     * 全屏容器界面
     */


    class FullscreenHolder extends FrameLayout {

        public FullscreenHolder(Context ctx) {
            super(ctx);
            setBackgroundColor(ctx.getResources().getColor(android.R.color.black));
        }

        @Override
        public boolean onTouchEvent(MotionEvent evt) {
            switch (evt.getAction()) {
                case MotionEvent.ACTION_POINTER_UP:
                    break;
            }
            return true;
        }
    }

    private void setStatusBarVisibility(boolean visible) {
        int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        Log.i("bar------", visible + "");
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
/**回退键 事件处理 优先级:
 视频播放全屏 - 网页回退 - 关闭页面*/

                if (customView != null) {
                    hideCustomView();
                } else if (webView.canGoBack()) {
                    webView.goBack();
                } else {
                    finish();
                }
                return true;
            default:
                return super.onKeyUp(keyCode, event);
        }
    }


    private void loadTop(View itemView) {
        TextView find_information_name = (TextView) itemView.findViewById(R.id.find_information_name);
        TextView find_information_time = (TextView) itemView.findViewById(R.id.find_information_time);
        TextView find_information_look = (TextView) itemView.findViewById(R.id.find_information_look);
        ViewUtil.setText(find_information_name, findItem.getTitle());
        ViewUtil.setText(find_information_time, String.format(Locale.CHINA, "发布时间：%s", TimeUtil.TimeStamp2Date(findItem.getCreated_at(), "yyyy-MM-dd HH:mm")));
        ViewUtil.setText(find_information_look, findItem.getClicks());

        webView = itemView.findViewById(R.id.find_information_content_wb);
        initWebView();


        ViewUtil.loadDataWithBaseURL(webView, findItem.getContent());
        LogUtil.logI("结果为——-----" + findItem.getContent());
       /* webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Jump2View.getInstance().goWeb(ActFindInformation.this, url);
                return true;
            }
        });*/


    }


    private TaskHelper taskHelper = new TaskHelper(this);
    private ViewGroup bottomViewGroup;

    private void loadBottom(ViewGroup viewGroup) {
        bottomViewGroup = viewGroup;
        if (taskHelper.hasTask()) {
            taskHelper.loadTask(viewGroup.getChildAt(0));
        } else {
            viewGroup.getChildAt(0).setVisibility(View.GONE);
        }
        viewGroup.getChildAt(1).setVisibility(taskHelper.hasTask() && findApp != null ? View.VISIBLE : View.GONE);
        if (findApp != null) {
            loadGame(viewGroup.getChildAt(2));
        } else {
            viewGroup.getChildAt(2).setVisibility(View.GONE);
        }
    }

    private void loadGame(View itemView) {
        itemView.setVisibility(View.VISIBLE);
        ImageView find_information_game_icon = (ImageView) itemView.findViewById(R.id.find_information_game_icon);
        TextView find_information_game_name = (TextView) itemView.findViewById(R.id.find_information_game_name);
        TextView find_information_game_surplus = (TextView) itemView.findViewById(R.id.find_information_game_surplus);
        TextView find_information_game_time = (TextView) itemView.findViewById(R.id.find_information_game_time);
        TextView find_information_game_task_center = (TextView) itemView.findViewById(R.id.find_information_game_task_center);
        GlideImageLoader.setGameImage(find_information_game_icon, findApp.getIcon());
        ViewUtil.setText(find_information_game_name, findApp.getName());
        final boolean isNeedReservation = !findApp.isCanDownload();//这里认为只有两种状态：可下载与预约下载
        ViewUtil.setText(find_information_game_surplus);
        if (isNeedReservation)
            ViewUtil.setText(find_information_game_time, String.format(Locale.CHINA, "开放时间：%s", TimeUtil.TimeStamp2Date(findApp.getDownload_at(), "yyyy-MM-dd\u0020HH:mm")));
        else
            ViewUtil.setText(find_information_game_time, String.format(Locale.CHINA, "厂商：%s\u0020包体大小：%sM", findApp.getManufacturer(), findApp.getPackage_size()));
        find_information_game_task_center.setVisibility(View.VISIBLE);

        updateView(this, findApp, find_information_game_task_center);

        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Jump2View.getInstance().goFindGame(ActFindInformation.this, findItem);
            }
        });
    }

    @Override
    public void initListener() {

    }

    private List<String> list = ListUtil.emptyList();

    @Override
    public void initData() {
        empty_view.setVisibility(View.INVISIBLE);
        SysAppUtil.checkNet(new Action1<Integer>() {
            @Override
            public void call(Integer result) {
                if (result != 0) {//无网络
                    if (check_net_ll != null)
                        check_net_ll.setVisibility(View.VISIBLE);
                } else {
                    if (check_net_ll != null)
                        check_net_ll.setVisibility(View.GONE);
                }
            }
        });
        FindItem data = DataUtil.getInstance().getCacheResult(ApiKey.articlesItem(id), FindItem.class);
        if (data != null) {
            loadFindItem(data);
        }
        SheepApp.getInstance().getNetComponent().getApiService().getFindDetail(id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        boolean isNewData = DataUtil.getInstance().isNewData(ApiKey.articlesItem(id));
                        if (isNewData) {
                            FindItem data = baseMessage.getData(FindItem.class);
                            loadFindItem(data);
                        }
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        taskHelper.clear();
                        notifyDataSetChanged();
                    }
                });
    }

    private void loadFindItem(FindItem data) {
        if (data != null) {
            taskHelper.clear();
            findItem = data;
            list.clear();
            list.add("top");
            list.add("bottom");
            notifyDataSetChanged();
            if (findItem.getRelease_task_id() != 0) {//包含任务
                taskHelper.initAcceptedTask(ActFindInformation.this, findItem.getRelease_task_id());
            }
            if (findItem.getApplication_id() != 0) {//包含游戏
                initFindApp(findItem.getApplication_id());
            }
        } else {
            refresh.setRefreshing(false);
        }
    }

    private FindApp findApp;

    private void initFindApp(int application_id) {
        FindApp cacheResult = DataUtil.getInstance().getCacheResult(ApiKey.applications(id), FindApp.class);
        if (cacheResult != null) {
            findApp = cacheResult;
            notifyDataSetChanged();
        }
        SheepApp.getInstance().getNetComponent().getApiService().getAppDetail(application_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        boolean isNewData = DataUtil.getInstance().isNewData(ApiKey.applications(id));
                        if (isNewData) {
                            findApp = baseMessage.getData(FindApp.class);
                            notifyDataSetChanged();
                        } else {
                            refresh.setRefreshing(false);
                        }
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        G.showToast(baseMessage);
                        refresh.setRefreshing(false);
                    }
                });
    }

    private FindItem findItem;

    private void notifyDataSetChanged() {
        CommonUtil.getInstance().updateEmptyView(empty_view, list.isEmpty());
        refresh.setRefreshing(false);
        view_list.getAdapter().notifyDataSetChanged();
    }


    private Map<String, TextView> downLoadTextViewMap = new HashMap<>();

    //获取任务对应的TextView来更新进度
    private TextView getTextViewByTask(DownloadTask task) {
        return getTextViewByKey(task.getKey());
    }

    private TextView getTextViewByKey(String key) {
        if (downLoadTextViewMap.containsKey(key))
            return downLoadTextViewMap.get(key);
        return null;
    }

    //更新按钮状态与添加点击事件
    private void updateView(Activity activity, FindApp findApp, TextView textView) {
        if (findApp.isCanDownload()) {//可下载
            downLoadTextViewMap.put(findApp.getDownload_link(), textView);
            downLoadTextViewMap.put(findApp.getPackage_name(), textView);
            findApp.getFindAppHelper().updateDownloadTaskView(activity, findApp, textView);
        } else {//预约下载
            findApp.getFindAppHelper().updateReservationView(activity, findApp, textView);
        }
    }

    //下载状态监听

    @Download.onPre
    void onPre(DownloadTask task) {
        TextView textView = getTextViewByTask(task);
        if (textView != null) {
            textView.setText("准备下载中");
        }
    }

    @Download.onTaskStart
    void taskStart(DownloadTask task) {
        TextView textView = getTextViewByTask(task);
        if (textView != null) {
            textView.setText("开始下载中");
        }
    }

    @Download.onTaskResume
    void taskResume(DownloadTask task) {
        TextView textView = getTextViewByTask(task);
        if (textView != null) {
            textView.setText("恢复下载中");
        }
    }

    //在这里处理任务执行中的状态，如进度进度条的刷新
    @Download.onTaskRunning
    protected void running(DownloadTask task) {
        TextView textView = getTextViewByTask(task);
        if (textView != null) {
            textView.setText(String.format(Locale.CHINA, "%d%%", Math.abs(task.getPercent())));
        }
    }

    @Download.onTaskStop
    void taskStop(DownloadTask task) {
        TextView textView = getTextViewByTask(task);
        if (textView != null) {
            textView.setText(CommonUtil.CONTINUE_DOWNLOAD);
        }
    }

    @Download.onNoSupportBreakPoint
    void onNoSupportBreakPoint(DownloadTask task) {
    }

    @Download.onTaskCancel
    void taskCancel(DownloadTask task) {
        TextView textView = getTextViewByTask(task);
        if (textView != null) {
            textView.setText("已经取消");
        }
    }

    @Download.onTaskFail
    void taskFail(DownloadTask task) {
        TextView textView = getTextViewByTask(task);
        if (textView != null) {
            textView.setText(CommonUtil.FAIL_DOWNLOAD);
        }
    }

    @Download.onTaskComplete
    void taskComplete(DownloadTask task) {
        TextView textView = getTextViewByTask(task);
        if (textView != null) {
            textView.setText(CommonUtil.START_INSTALL);
        }
        if (findApp != null && TextUtils.equals(task.getKey(), findApp.getDownload_link()))
            findApp.updateState(DownloadUtil.STATUS_FINISH);
    }

    @Subscribe
    public void onEventMainThread(Intent intent) {
        if (intent != null && intent.getAction() != null && intent.getDataString() != null && intent.getDataString().contains("package:")) {
            String packageName = intent.getDataString().replace("package:", "");

            TextView textView = getTextViewByKey(packageName);
            if (textView != null && findApp != null) {
                switch (intent.getAction()) {
                    case ACTION_PACKAGE_ADDED:
                        textView.setText(CommonUtil.GAME_OPEN);
                        break;
                    case ACTION_PACKAGE_REMOVED:
                        String path = PackageUtil.isExistsFile(packageName, findApp.getDownload_url());
                        if (TextUtils.isEmpty(path)) {
                            textView.setText(CommonUtil.START_DOWNLOAD);
                        } else {
                            textView.setText(CommonUtil.START_INSTALL);
                        }
                        break;
                }
            }

            if (findApp != null && TextUtils.equals(packageName, findApp.getPackage_names())) {
                switch (intent.getAction()) {
                    case ACTION_PACKAGE_ADDED:
                        findApp.updateState(DownloadUtil.STATUS_INSTALLED);
                        break;
                    case ACTION_PACKAGE_REMOVED:
                        String path = PackageUtil.isExistsFile(packageName, findApp.getDownload_url());
                        if (TextUtils.isEmpty(path)) {
                            findApp.updateState(DownloadUtil.STATUS_INIT);
                        } else {
                            findApp.updateState(DownloadUtil.STATUS_FINISH);
                        }
                        break;
                }
            }
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        taskHelper.onResume();
        try {
            if (webView != null) {
//                webView.resumeTimers();
                webView.onResume();
                webView.getClass().getMethod("onResume").invoke(webView, (Object[]) null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        LogUtil.logI("释放资源");
        EventBus.getDefault().unregister(this);
        taskHelper.destroy();
        if (webView != null) {
//            webView.onPause();
//            webView.freeMemory();
//            webView.removeAllViews();
            webView.destroy();
//            webView = null;
        }
        super.onDestroy();
        ActFindInformation.this.finish();
    }

    @Override
    public void call(Integer integer) {
        switch (integer) {
            case 1://刷新底部
                loadBottom(bottomViewGroup);
                break;
        }
    }

    @Subscribe
    public void onEventMainThread(BigEvent event) {
        switch (event.getEventTypes()) {
            case ONFRESH_TRYMAKEMANY_PAGE:
                taskHelper.refreshTask();
                break;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (webView != null) {
            webView.onPause();
//            webView.pauseTimers();
            try {
                webView.getClass().getMethod("onPause").invoke(webView, (Object[]) null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (webView != null && webView.canGoBack()) {
            webView.goBack();
            return;
        }
        super.onBackPressed();
    }


    @Override
    public void onConfigurationChanged(Configuration config) {
        super.onConfigurationChanged(config);
        switch (config.orientation) {
            case Configuration.ORIENTATION_LANDSCAPE:
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                break;
            case Configuration.ORIENTATION_PORTRAIT:
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                break;
        }
    }
}
