package com.sheep.gamegroup.view.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sheep.gamegroup.absBase.AbsObserver;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.event.BigEvent;
import com.sheep.gamegroup.greendao.download.DownLoadInfo;
import com.sheep.gamegroup.helper.TaskHelper;
import com.sheep.gamegroup.model.entity.Applications;
import com.sheep.gamegroup.model.entity.Article;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.DownloadUtil;
import com.sheep.gamegroup.util.GlideImageLoader;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.SysAppUtil;
import com.sheep.gamegroup.util.TimeUtil;
import com.sheep.gamegroup.util.ViewHolder;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.util.viewHelper.WebViewVideoHelper;
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 io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import rx.functions.Action1;

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 ActArticle extends BaseActivity implements Action1<Integer> {
    @Override
    protected int getLayoutId() {
        return R.layout.net_empty_fresh_list;
    }

    private int id;


    @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;
    @BindView(R.id.bottom)
    RelativeLayout bottom;
    //输入框
    private EditText input_comment_input;
    private WebViewVideoHelper webViewVideoHelper = new WebViewVideoHelper();
    @Override
    public void initView() {
        id = DataUtil.getObject(getIntent(), Integer.class);

        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);
                        if(article == null){
                            Jump2View.getInstance().tryShare(ActArticle.this, "find_share_url", "find_id", id);
                        } else {
                            Jump2View.getInstance().tryShare(ActArticle.this, "find_share_url", "find_id", id, article.getDes());
                        }
                    }
                });

        EventBus.getDefault().register(this);

        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;
                }
            }
        });
    }
    //底部可跳转到评论
    private void initBottomCommentView(){
        if(input_comment_input != null || article == null){//保证只初始化一次
            return;
        }
        LayoutInflater.from(SheepApp.getInstance()).inflate(R.layout.include_input_comment, bottom);
        input_comment_input = bottom.findViewById(R.id.input_comment_input);
        input_comment_input.setCursorVisible(false);
        input_comment_input.setFocusable(false);
        input_comment_input.setFocusableInTouchMode(false);
        View.OnClickListener onClickListener;
        bottom.setOnClickListener(onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Jump2View.getInstance().goActFindInformationComment(ActArticle.this, article.getId());
            }
        });
        input_comment_input.setOnClickListener(onClickListener);
    }


    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, article.getTitle());
        ViewUtil.setText(find_information_time, String.format(Locale.CHINA, "发布时间：%s", TimeUtil.TimeStamp2Date(article.getCreated_at(), "yyyy-MM-dd HH:mm")));
        ViewUtil.setText(find_information_look, article.getClicks());

        WebView webView = itemView.findViewById(R.id.find_information_content_wb);
        webViewVideoHelper.init(this, webView);
        ViewUtil.loadDataWithBaseURL(webView, article.getContent());


    }


    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(ActArticle.this, article);
            }
        });
    }

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

    @Override
    public void initData() {
        empty_view.setVisibility(View.INVISIBLE);
        SysAppUtil.checkNet(new AbsObserver<Integer>() {
            @Override
            public void onNext(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);
                }
            }
        });
        Article data = DataUtil.getInstance().getCacheResult(ApiKey.articlesItem(id), Article.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) {
                            Article data = baseMessage.getData(Article.class);
                            loadFindItem(data);
                        }
                    }

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

    private void loadFindItem(Article data) {
        if (data != null) {
            taskHelper.clear();
            article = data;
            list.clear();
            list.add("top");
            list.add("bottom");
            notifyDataSetChanged();

            initBottomCommentView();
            if (article.getRelease_task_id() != 0) {//包含任务
                taskHelper.initAcceptedTask(ActArticle.this, article.getRelease_task_id());
            }
            if (article.getApplication_id() != 0) {//包含游戏
                initFindApp(article.getApplication_id());
            }
        } else {
            refresh.setRefreshing(false);
        }
    }

    private Applications findApp;

    private void initFindApp(int application_id) {
        Applications cacheResult = DataUtil.getInstance().getCacheResult(ApiKey.applications(id), Applications.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(Applications.class);
                            notifyDataSetChanged();
                        } else {
                            refresh.setRefreshing(false);
                        }
                    }

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

    private Article article;

    private void notifyDataSetChanged() {
        if (empty_view == null) {
            return;
        }
        CommonUtil.getInstance().updateEmptyView(empty_view, list.isEmpty());
        refresh.setRefreshing(false);
        ViewUtil.notifyDataSetChanged(view_list);
    }


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

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

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

    //更新按钮状态与添加点击事件
    private void updateView(Activity activity, Applications 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);
        }
    }

    //下载状态监听

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

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

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

    //在这里处理任务执行中的状态，如进度进度条的刷新
    protected void running(DownLoadInfo task) {
        TextView textView = getTextViewByTask(task);
        if (textView != null) {
            textView.setText(String.format(Locale.CHINA, "%d%%(%s)", Math.abs(task.getMPercent()), task.getAverageSpeed()));//添加下载速度
        }
    }

    void taskStop(DownLoadInfo task) {
        TextView textView = getTextViewByTask(task);
        if (textView != null) {
            textView.setText(CommonUtil.CONTINUE_DOWNLOAD);
        }
    }

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

    void taskFail(DownLoadInfo task) {
        TextView textView = getTextViewByTask(task);
        if (textView != null) {
            textView.setText(CommonUtil.FAIL_DOWNLOAD);
        }
    }

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

    @Subscribe
    public void onEventMainThread(BigEvent event) {
        switch (event.getEventTypes()) {
            case ONFRESH_TRYMAKEMANY_PAGE:
                taskHelper.refreshTask();
                break;
        }
        if (event.getData() instanceof DownLoadInfo) {
            DownLoadInfo task = (DownLoadInfo) event.getData();
            switch (event.getEventTypes()) {
                case DOWNLOAD_RUNNING:
                    running(task);
                    break;
                case DOWNLOAD_STOP:
                    taskStop(task);
                    break;
                case DOWNLOAD_COMPLETE:
                    taskComplete(task);
                    break;
                case DOWNLOAD_CANCEL:
                    taskCancel(task);
                    break;
                case DOWNLOAD_FAIL:
                    taskFail(task);
                    break;
            }
        }
    }

    @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();
        webViewVideoHelper.onResume();
    }



    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                webViewVideoHelper.onBackUp();
                return true;
            default:
                return super.onKeyUp(keyCode, event);
        }
    }
    @Override
    public void onBackPressed() {
        if(webViewVideoHelper.onBackPressed()){
            return;
        }
        super.onBackPressed();
    }
    @Override
    protected void onPause() {
        super.onPause();
        webViewVideoHelper.onPause();
    }
    @Override
    protected void onDestroy() {
//        LogUtil.logI("释放资源");
        EventBus.getDefault().unregister(this);
        taskHelper.destroy();
        webViewVideoHelper.onDestroy();
        super.onDestroy();
    }

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


    @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;
        }
    }
}
