package com.sheep.gamegroup.view.fragment;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.sheep.gamegroup.event.BigEvent;
import com.sheep.gamegroup.greendao.download.DownLoadInfo;
import com.sheep.gamegroup.helper.TaskHelper;
import com.sheep.gamegroup.model.api.ApiService;
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.entity.UserComment;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.ApiJSONUtil;
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.RefreshUtil;
import com.sheep.gamegroup.util.TestUtil;
import com.sheep.gamegroup.util.TimeUtil;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.util.viewHelper.WebViewVideoHelper;
import com.sheep.gamegroup.view.adapter.AdpArticleComment;
import com.sheep.gamegroup.view.dialog.DialogSuccessUtil;
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.Locale;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.Observable;
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/11/2.
 * realicing@sina.com
 * 用户评论详情界面
 */
public class FgtArticleComment extends BaseListFragment3<UserComment> implements Action1<Integer> {

    @Override
    public int getLayoutId() {
        return R.layout.net_empty_smart_refresh_rv;
    }

    @BindView(R.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R.id.bottom)
    RelativeLayout bottom;
    //输入框
    private EditText input_comment_input;

    //是否显示无数据占位图
    protected void updateEmptyView() {
        boolean isEmpty = list.isEmpty() && (article_id <= 0 || article == null);
        if (useSelfEmpty())
            CommonUtil.getInstance().updateEmptyView(empty_view, isEmpty);
        ViewUtil.setVisibility(find_article_comment_title_rl, !list.isEmpty());
    }

    @Override
    public void initView() {
        TitleBarUtils.getInstance().setTitle(getActivity(), "详情")
                .setTitleFinish(getActivity())
                .setShowOrHide(getActivity(), true)
                .setRightImgBotton(getActivity(), R.mipmap.share, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        FIND_SHARE.onEvent("find_id", article_id);
                        if(article == null){
                            Jump2View.getInstance().tryShare(activity, "find_share_url", "find_id", article_id);
                        } else {
                            Jump2View.getInstance().tryShare(activity, "find_share_url", "find_id", article_id, article.getTitle());
                        }
                    }
                });
        smartRefreshLayout = refresh;
        refresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadMoreData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshData();
            }
        });
        RefreshUtil.newInstance().publicParameterLoadMore(refresh, activity);

        //头部view
        initHeaderView();
        //底部可发表评论
        LayoutInflater.from(SheepApp.getInstance()).inflate(R.layout.include_input_comment, bottom);
        input_comment_input = bottom.findViewById(R.id.input_comment_input);
        bottom.findViewById(R.id.input_comment_commit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String content = input_comment_input.getText().toString();
                commitContent(content);
            }
        });
        EventBus.getDefault().register(this);

    }

    @Override
    public void refreshData() {
        initArticle();
        super.refreshData();
    }

    private Article article;


    //用户评论一个用户对游戏的评论
    private void commitContent(String content) {
        if (TestUtil.isDev()) G.showToast("评论内容：" + content);
        if (content.isEmpty()) {
            G.showToast("评论内容不能为空");
            return;
        }
        // 发表评论
        ApiJSONUtil.postGameUserUserGameComment(type, article_id, content, 0)
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        input_comment_input.setText("");
                        DialogSuccessUtil.showSuccess("发表成功", new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialogInterface) {
                                refreshData();
                            }
                        });
                    }

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

    //    ------------------------------start header------------------------------------
    private View headerView;
    private View find_information_bottom_item;
    private View find_information_bottom_item_line;
    private View find_information_bottom_item_game;
    private View find_article_comment_title_rl;

    //初始化headerView
    private void initHeaderView() {
        headerView = LayoutInflater.from(SheepApp.getInstance()).inflate(R.layout.header_act_article, null);
        find_article_comment_title_rl = headerView.findViewById(R.id.find_article_comment_title_rl);
        find_information_bottom_item = headerView.findViewById(R.id.find_information_bottom_item);
        find_information_bottom_item_line = headerView.findViewById(R.id.find_information_bottom_item_line);
        find_information_bottom_item_game = headerView.findViewById(R.id.find_information_bottom_item_game);
        ViewUtil.setVisibility(find_information_bottom_item, false);
        ViewUtil.setVisibility(find_information_bottom_item_line, false);
        ViewUtil.setVisibility(find_information_bottom_item_game, false);
    }

    //    ------------------------------end header------------------------------------

    private int article_id;
    private int type = ApiJSONUtil.COMMENT_TYPE_ARTICLE;

    public void setArticle_id(int article_id) {
        this.article_id = article_id;
    }

    @Override
    protected RecyclerView.Adapter getAdapter() {
        //用户评论的回复列表
        AdpArticleComment adapter = new AdpArticleComment(list);
        adapter.addHeaderView(headerView);
        return adapter;
    }

    @Override
    protected String getKey(int page, int per_page) {
        return String.format(Locale.CHINA, "app/game_user/app_comment_list?page_no=%d&page_size=%d&app_id=%d&comment_type=%d", page, per_page, article_id, type);
    }

    @Override
    protected Observable<BaseMessage> getApi(ApiService apiService) {
        return apiService.getGameUserAppCommentList(page, per_page, article_id, type);
    }


    private WebViewVideoHelper webViewVideoHelper = new WebViewVideoHelper();
    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(activity, webView);
        ViewUtil.loadDataWithBaseURL(webView, article.getContent());


    }
    private TaskHelper taskHelper = new TaskHelper(this);

    private void loadBottom() {
        if (taskHelper.hasTask()) {
            taskHelper.loadTask(find_information_bottom_item);
        } else {
            find_information_bottom_item.setVisibility(View.GONE);
        }
        find_information_bottom_item_line.setVisibility(taskHelper.hasTask() && findApp != null ? View.VISIBLE : View.GONE);
        if (findApp != null) {
            loadGame(find_information_bottom_item_game);
        } else {
            find_information_bottom_item_game.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(activity, findApp, find_information_game_task_center);

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

    public void initArticle() {
        if(article == null) {//第一次才调用该方法，之后都是刷新操作
            Article data = DataUtil.getInstance().getCacheResult(ApiKey.articlesItem(article_id), Article.class);
            if (data != null) {
                loadFindItem(data);
            }
        }
        SheepApp.getInstance().getNetComponent().getApiService().getFindDetail(article_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(article_id));
                        if (isNewData) {
                            Article data = baseMessage.getData(Article.class);
                            loadFindItem(data);
                        }
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        taskHelper.clear();
                    }
                });
    }
    private void loadFindItem(Article data) {
        if (data != null) {
            taskHelper.clear();
            article = data;
            if (article.getRelease_task_id() != 0) {//包含任务
                taskHelper.initAcceptedTask(activity, article.getRelease_task_id());
            }
            if (article.getApplication_id() != 0) {//包含游戏
                initFindApp(article.getApplication_id());
            }
            loadTop(headerView);
        }
    }

    private Applications findApp;

    private void initFindApp(final int application_id) {
        if(findApp == null) {
            Applications cacheResult = DataUtil.getInstance().getCacheResult(ApiKey.applications(application_id), Applications.class);
            if (cacheResult != null) {
                findApp = cacheResult;
                loadGame(find_information_bottom_item_game);
            }
        }
        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(application_id));
                        if (isNewData) {
                            findApp = baseMessage.getData(Applications.class);
                            loadGame(find_information_bottom_item_game);
                        }
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        G.showToast(baseMessage);
                    }
                });
    }
    @Override
    protected Class<UserComment> getTClass() {
        return UserComment.class;
    }

    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
    public void onResume() {
        super.onResume();
        taskHelper.onResume();
        webViewVideoHelper.onResume();
    }
    @Override
    public void onPause() {
        super.onPause();
        webViewVideoHelper.onPause();
    }
    @Override
    public 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();
                break;
        }
    }



    public boolean onBackUp() {
        webViewVideoHelper.onBackUp();
        return true;
    }
    public boolean onBackPressed() {
        return webViewVideoHelper.onBackPressed();
    }
}
