package com.gh.common.databind;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.facebook.drawee.view.SimpleDraweeView;
import com.gh.common.chain.BrowserInstallHandler;
import com.gh.common.chain.CertificationHandler;
import com.gh.common.chain.ChainBuilder;
import com.gh.common.chain.ChainHandler;
import com.gh.common.chain.CheckDownloadHandler;
import com.gh.common.chain.DownloadDialogHelperHandler;
import com.gh.common.chain.GamePermissionHandler;
import com.gh.common.chain.OverseaDownloadHandler;
import com.gh.common.chain.PackageCheckHandler;
import com.gh.common.chain.ValidateVSpaceHandler;
import com.gh.common.chain.VersionNumberHandler;
import com.gh.common.constant.Config;
import com.gh.common.filter.RegionSetting;
import com.gh.common.filter.RegionSettingHelper;
import com.gh.common.history.HistoryHelper;
import com.gh.common.repository.ReservationRepository;
import com.gh.common.simulator.SimulatorDownloadManager;
import com.gh.common.simulator.SimulatorGameManager;
import com.gh.common.util.CheckLoginUtils;
import com.gh.common.util.DialogUtils;
import com.gh.common.util.GameUtils;
import com.gh.common.util.GameViewUtils;
import com.gh.common.util.LogUtils;
import com.gh.common.util.NewsUtils;
import com.gh.common.util.PackageInstaller;
import com.gh.common.util.PackageUtils;
import com.gh.common.util.ReservationHelper;
import com.gh.download.DownloadManager;
import com.gh.download.dialog.DownloadDialog;
import com.gh.gamecenter.DownloadManagerActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.WebActivity;
import com.gh.gamecenter.common.baselist.LoadStatus;
import com.gh.gamecenter.common.callback.OnViewClickListener;
import com.gh.gamecenter.common.entity.LinkEntity;
import com.gh.gamecenter.common.eventbus.EBReuse;
import com.gh.gamecenter.common.utils.DarkModeUtils;
import com.gh.gamecenter.common.utils.ExtensionsKt;
import com.gh.gamecenter.common.utils.ImageUtils;
import com.gh.gamecenter.common.view.DrawableView;
import com.gh.gamecenter.core.utils.DisplayUtils;
import com.gh.gamecenter.core.utils.MtaHelper;
import com.gh.gamecenter.core.utils.NumberUtils;
import com.gh.gamecenter.databinding.KaifuDetailItemRowBinding;
import com.gh.gamecenter.feature.entity.ApkEntity;
import com.gh.gamecenter.feature.entity.CommunityVideoEntity;
import com.gh.gamecenter.feature.entity.GameEntity;
import com.gh.gamecenter.feature.entity.PluginLocation;
import com.gh.gamecenter.feature.entity.ServerCalendarEntity;
import com.gh.gamecenter.feature.entity.TagStyleEntity;
import com.gh.gamecenter.feature.entity.TestEntity;
import com.gh.gamecenter.feature.exposure.ExposureEvent;
import com.gh.gamecenter.feature.utils.PlatformUtils;
import com.gh.gamecenter.feature.view.DownloadButton;
import com.gh.gamecenter.feature.view.GameIconView;
import com.gh.gamecenter.gamedetail.dialog.GamePermissionDialogFragment;
import com.gh.gamecenter.manager.PackagesManager;
import com.gh.vspace.VDownloadManagerActivity;
import com.gh.vspace.VHelper;
import com.lightgame.download.DownloadEntity;
import com.lightgame.download.FileUtils;
import com.lightgame.utils.Utils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by khy on 12/02/18.
 */

public class BindingAdapters {

    public static void loadIcon(SimpleDraweeView view, String imageUrl) {
        ImageUtils.displayIcon(view, imageUrl);
    }

    public static void loadImage(SimpleDraweeView view, String imageUrl) {
        ImageUtils.display(view, imageUrl);
    }

    public static void setTextSize(TextView view, int number) {
        view.setTextSize(number);
    }

    public static void setTypeface(TextView view, String type) {
        if (type == null) return;

        switch (type) {
            case "bold":
                view.setTypeface(null, Typeface.BOLD);
                break;
            case "italic":
                view.setTypeface(null, Typeface.ITALIC);
                break;
            case "bold_italic":
                view.setTypeface(null, Typeface.BOLD_ITALIC);
                break;
            default:
                view.setTypeface(null, Typeface.NORMAL);
                break;
        }
    }

    public static void addDetailKaiFuView(LinearLayout view, List<ServerCalendarEntity> list
            , OnViewClickListener listener, Boolean isReadyPatch) {
        if (list == null) return;
        view.removeAllViews();
        for (int i = 0; i < list.size() + 1; i++) { // 1 is Title
            View inflate = LayoutInflater.from(view.getContext()).inflate(R.layout.kaifu_detail_item_row, null);
            KaifuDetailItemRowBinding binding = KaifuDetailItemRowBinding.bind(inflate);
            binding.getRoot().setBackgroundColor(isReadyPatch != null && isReadyPatch ? ExtensionsKt.toColor(R.color.theme) : ExtensionsKt.toColor(R.color.white));
            binding.getRoot().setPadding(DisplayUtils.dip2px(1), DisplayUtils.dip2px(1), DisplayUtils.dip2px(1), i == list.size() ? DisplayUtils.dip2px(1) : 0);
            ServerCalendarEntity serverEntity = list.get(i - 1);
            binding.timeTv.setText(i == 0 ? "时间" : serverEntity.getFormatTime("HH:mm"));
            binding.remarkTv.setText(i == 0 ? "备注" : serverEntity.getRemark());
            binding.nameTv.setText(i == 0 ? "名字" : (TextUtils.isEmpty(serverEntity.getNote()) ? "-" : serverEntity.getNote()));
            if (i != 0) {
                binding.getRoot().setOnClickListener(v -> {
                    listener.onClick(v, isReadyPatch != null && isReadyPatch ? serverEntity : null);
                });

                // 滑动冲突处理
                binding.getRoot().setOnTouchListener((v, event) -> {
                    if (list.size() > 5) {
                        if (event.getAction() == MotionEvent.ACTION_DOWN) {
                            EventBus.getDefault().post(new EBReuse("CalenderDown"));
                        } else if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
                            EventBus.getDefault().post(new EBReuse("CalenderCancel"));
                        }
                    }
                    return false;
                });
            }
            view.addView(inflate);
        }
    }

    // 如果超过10000，则转换为1.0W
    public static void transSimpleCount(TextView view, int count) {
        view.setText(NumberUtils.transSimpleCount(count));
    }

    public static void textColorFromString(TextView tv, String hexString) {
        if (TextUtils.isEmpty(hexString)) return;

        try {
            tv.setTextColor(Color.parseColor(hexString));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void showHide(View view, Boolean show) {
        if (show != null && show) {
            view.setVisibility(View.VISIBLE);
        } else {
            view.setVisibility(View.GONE);
        }
    }

    public static void goneIf(View view, Boolean gone) {
        if (gone != null && gone) {
            view.setVisibility(View.GONE);
        } else {
            view.setVisibility(View.VISIBLE);
        }
    }

    /**
     * lazy 的 paddingTop
     */
    public static void lazyPaddingLeft(View view, int paddingLeftInDp) {
        view.setPadding(DisplayUtils.dip2px(paddingLeftInDp), view.getPaddingTop(), view.getPaddingRight(), view.getPaddingBottom());
    }

    /**
     * lazy 的 paddingTop
     */
    public static void lazyPaddingTop(View view, int paddingTopInDp) {
        view.setPadding(view.getPaddingLeft(), DisplayUtils.dip2px(paddingTopInDp), view.getPaddingRight(), view.getPaddingBottom());
    }

    /**
     * lazy 的 paddingBottom
     */
    public static void lazyPaddingBottom(View view, int paddingBottomInDp) {
        view.setPadding(view.getPaddingLeft(), view.getPaddingTop(), view.getPaddingRight(), DisplayUtils.dip2px(paddingBottomInDp));
    }

    public static void visibleInvisible(View view, Boolean show) {
        if (show != null && show) {
            view.setVisibility(View.VISIBLE);
        } else {
            view.setVisibility(View.INVISIBLE);
        }
    }

    public static void setMessageUnread(TextView view, int unreadCount) {
        if (unreadCount < 100) {
            view.setText(String.valueOf(unreadCount));
        } else {
            view.setText("99+");
        }
    }

    public static void setServerTypePadding(TextView view, String serverType) {
        int paddRight = 0;
        if (TextUtils.isEmpty(serverType)) {
        } else {
            if ("删档内测".equals(serverType) || "不删档内测".equals(serverType)) {
                if ("删档内测".equals(serverType)) {
                    paddRight = DisplayUtils.dip2px(view.getContext(), 50);
                } else {
                    paddRight = DisplayUtils.dip2px(view.getContext(), 60);
                }
            } else {
                paddRight = DisplayUtils.dip2px(view.getContext(), 30);
            }
        }
        view.setPadding(0, 0, paddRight, 0);
    }

    public static void setServerType(TextView view, String serverType) {
        view.setText(serverType);
        if ("删档内测".equals(serverType) || "不删档内测".equals(serverType)) {
            view.setBackgroundResource(R.drawable.textview_server_tag);
        } else {
            view.setBackgroundResource(R.drawable.textview_orange_up);
        }
    }

    public static void setGame(View view, GameEntity gameEntity) {
        if (gameEntity != null && view instanceof GameIconView) {
            ((GameIconView) view).displayGameIcon(gameEntity);
        }
    }

    public static void setGameIcon(View view, GameEntity gameEntity) {
        if (gameEntity != null && view instanceof GameIconView) {
            ((GameIconView) view).displayGameIcon(gameEntity.getIcon(), gameEntity.getIconSubscript(), gameEntity.getIconFloat());
        }
    }

    public static void setArticleType(TextView view, String articleType) {
        NewsUtils.setNewsType(view, articleType, 0, 0);
    }

    public static void setDetailDownloadText(TextView view, GameEntity gameEntity) {
        if (gameEntity == null || gameEntity.getApk().isEmpty()) {
            view.setBackgroundResource(R.drawable.game_item_btn_pause_style);
            view.setTextColor(0xFF999999);
            view.setClickable(false);
        }
    }

    public static void setLiBaoBtn(TextView view, String status) {
        if (TextUtils.isEmpty(status)) return;
        switch (status) {
            case "coming":
                view.setText(R.string.libao_coming);
                view.setBackgroundResource(R.drawable.textview_blue_style);
                break;
            case "ling":
                view.setText(R.string.libao_ling);
                view.setBackgroundResource(R.drawable.textview_green_style);
                break;
            case "tao":
                view.setText(R.string.libao_tao);
                view.setBackgroundResource(R.drawable.textview_orange_style);
                break;
            case "used_up":
                view.setText(R.string.libao_used_up);
                view.setBackgroundResource(R.drawable.textview_cancel_up);
                break;
            case "finish":
                view.setText(R.string.libao_finish);
                view.setBackgroundResource(R.drawable.textview_cancel_up);
                break;
            case "linged":
                view.setText(R.string.libao_linged);
                view.setBackgroundResource(R.drawable.libao_linged_style);
                view.setTextColor(ContextCompat.getColorStateList(view.getContext(), R.color.libao_linged_selector));
                break;
            case "taoed":
                view.setText(R.string.libao_taoed);
                view.setBackgroundResource(R.drawable.libao_taoed_style);
                view.setTextColor(ContextCompat.getColorStateList(view.getContext(), R.color.libao_taoed_selector));
                break;
            case "copy":
                view.setText(R.string.libao_copy);
                view.setBackgroundResource(R.drawable.textview_blue_style);
                break;
            case "repeatLing":
                view.setText(R.string.libao_repeat_ling);
                view.setBackgroundResource(R.drawable.textview_cancel_up);
                break;
            case "repeatLinged":
                view.setText(R.string.libao_repeat_ling);
                view.setBackgroundResource(R.drawable.textview_green_style);
                break;
            case "repeatTao":
                view.setText(R.string.libao_repeat_tao);
                view.setBackgroundResource(R.drawable.textview_cancel_up);
                break;
            case "repeatTaoed":
                view.setText(R.string.libao_repeat_tao);
                view.setBackgroundResource(R.drawable.textview_orange_style);
                break;
            case "unshelve":
                view.setBackgroundResource(R.drawable.textview_cancel_style);
                view.setText(R.string.libao_unshelve);
                break;
            default:
                view.setBackgroundResource(R.drawable.textview_cancel_style);
                view.setText("异常");
        }
    }

    // 大图下的进度条
    public static void setDownloadButton(DownloadButton progressBar,
                                         GameEntity gameEntity,
                                         ExposureEvent traceEvent,
                                         @Nullable View.OnClickListener clickCallBack,
                                         @Nullable String entrance,
                                         @Nullable String location) {

        // 恢复DialogFragment
        restoreDialogFragment(progressBar);

        // 判断是否显示按钮
        if (gameEntity != null
                && Config.isShowDownload(gameEntity.getId())
                && !"光环助手".equals(gameEntity.getName())) {
            progressBar.setVisibility(View.VISIBLE);
        } else {
            progressBar.setVisibility(View.GONE);
            return;
        }

        // 点击事件
        progressBar.setOnClickListener(v -> {
            if (clickCallBack != null) clickCallBack.onClick(v);
            switch (progressBar.getButtonStyle()) {
                case DOWNLOADING_PLUGIN:
                case DOWNLOADING_NORMAL:
                    if (gameEntity.isVGame()) {
                        v.getContext().startActivity(VDownloadManagerActivity.getIntent(v.getContext(), true));
                    } else {
                        Intent intent = DownloadManagerActivity.getDownloadMangerIntent(v.getContext(),
                                gameEntity.getApk().get(0).getUrl(), entrance);
                        v.getContext().startActivity(intent);
                    }
                    break;
                case NONE:
                    Utils.toast(v.getContext(), "该游戏已关闭下载");
                    break;
                case NORMAL:
                case PLUGIN:
                    final RegionSetting.GameH5Download gameH5Download = RegionSettingHelper.getGameH5DownloadByGameId(gameEntity.getId());
                    if (gameH5Download != null) {
                        DialogUtils.showGameH5DownloadDialog(v.getContext(), gameEntity, gameH5Download);
                    } else {
                        if (gameEntity.getApk().size() == 1) {
                            ApkEntity apk = gameEntity.getApk().get(0);
                            DownloadEntity downloadEntity = SimulatorGameManager.findDownloadEntityByUrl(apk.getUrl());
                            if (gameEntity.getSimulator() != null) {
                                boolean isInstalled = PackageUtils.isInstalledFromAllPackage(v.getContext(), gameEntity.getSimulator().getApk().getPackageName());
                                if (downloadEntity != null && SimulatorGameManager.isSimulatorGame(gameEntity) && !isInstalled) {
                                    SimulatorDownloadManager.getInstance().showDownloadDialog(v.getContext(), gameEntity.getSimulator(),
                                            SimulatorDownloadManager.SimulatorLocation.LAUNCH, gameEntity.getId(), gameEntity.getName(), null);
                                    return;
                                }
                            }

                            ChainBuilder builder = new ChainBuilder();
                            builder.addHandler(new ValidateVSpaceHandler());
                            builder.addHandler(new GamePermissionHandler());
                            builder.addHandler(new BrowserInstallHandler());
                            builder.addHandler(new PackageCheckHandler());
                            builder.addHandler(new DownloadDialogHelperHandler());
                            builder.addHandler(new CertificationHandler());
                            builder.addHandler(new VersionNumberHandler());
                            builder.addHandler(new OverseaDownloadHandler());
                            builder.addHandler(new CheckDownloadHandler());

                            builder.setProcessEndCallback(o -> {
                                download(progressBar, gameEntity, traceEvent, (boolean) o, entrance, location);
                                return null;
                            });
                            final ChainHandler chainHandler = builder.buildHandlerChain();
                            if (chainHandler != null) {
                                chainHandler.handleRequest(v.getContext(), gameEntity);
                            }
                        } else {
                            ChainBuilder builder = new ChainBuilder();
                            builder.addHandler(new GamePermissionHandler());
                            builder.addHandler(new CertificationHandler());
                            builder.addHandler(new VersionNumberHandler());

                            builder.setProcessEndCallback(o -> {
                                DownloadDialog.showDownloadDialog(
                                        v.getContext(),
                                        gameEntity,
                                        traceEvent,
                                        entrance,
                                        location + ":" + gameEntity.getName());
                                return null;
                            });
                            final ChainHandler chainHandler = builder.buildHandlerChain();
                            if (chainHandler != null) {
                                chainHandler.handleRequest(v.getContext(), gameEntity);
                            }
                        }
                    }
                    break;
                case LAUNCH_OR_OPEN:
                    if (gameEntity.getApk().size() == 1) {
                        //启动模拟器游戏
                        if (SimulatorGameManager.isSimulatorGame(gameEntity)) {
                            DownloadEntity downloadEntity = SimulatorGameManager.findDownloadEntityByUrl(gameEntity.getApk().get(0).getUrl());
                            if (downloadEntity != null) {
                                File file = new File(downloadEntity.getPath());
                                if (!file.exists()) {
                                    download(progressBar, gameEntity, traceEvent, false, entrance, location);
                                    return;
                                }

                                SimulatorGameManager.launchSimulatorGame(downloadEntity, gameEntity);
                            }
                            return;
                        }

                        if (gameEntity.isVGame()) {
                            VHelper.installOrLaunch((AppCompatActivity) v.getContext(), gameEntity);
                            return;
                        }

                        PackageUtils.launchApplicationByPackageName(v.getContext(), gameEntity.getApk().get(0).getPackageName());
                    } else {
                        DownloadDialog.showDownloadDialog(
                                v.getContext(),
                                gameEntity,
                                traceEvent,
                                entrance,
                                location + ":" + gameEntity.getName());
                    }
                    break;
                case INSTALL_PLUGIN:
                case INSTALL_NORMAL:
                    if (gameEntity.getApk().size() == 1) {
                        DownloadEntity downloadEntity = DownloadManager.getInstance().getDownloadEntitySnapshot(gameEntity);

                        if (gameEntity.isVGame()) {
                            VHelper.installOrLaunch(v.getContext(), gameEntity);
                            return;
                        }

                        if (downloadEntity != null) {
                            PackageInstaller.install(v.getContext(), downloadEntity);
                        }
                    }
                    break;
                case RESERVABLE:
                    GamePermissionDialogFragment.show((AppCompatActivity) v.getContext(), gameEntity, gameEntity.getInfo(), () -> {
                        CheckLoginUtils.checkLogin(progressBar.getContext(), "", () -> {
                            ReservationHelper.reserve(v.getContext(), gameEntity.getId(), gameEntity.getName(), () -> {
                                LogUtils.logReservation(gameEntity, traceEvent);
                                updateReservation(progressBar, gameEntity);
                            });
                        });
                    });
                    break;
                case RESERVED:
                    if ("download".equals(gameEntity.getReserveStatus())) {
                        ReservationHelper.showDeleteReservationDialog(progressBar.getContext(), () -> {
                            ReservationHelper.deleteReservation(gameEntity, () -> {
                                updateReservation(progressBar, gameEntity);
                            });
                        });
                    } else {
                        ReservationHelper.showCancelReservationDialog(progressBar.getContext(), () -> {
                            ReservationHelper.cancelReservation(gameEntity, () -> {
                                updateReservation(progressBar, gameEntity);
                            });
                        });
                    }
                    break;
                case H5_GAME:
                    LinkEntity linkEntity = gameEntity.getH5Link();
                    boolean isPlay = "play".equals(linkEntity.getType()); // 是否为开始玩
                    MtaHelper.onEvent("H5页面", "入口", "列表页_" + gameEntity.getName());

                    if (isPlay) {
                        HistoryHelper.insertGameEntity(gameEntity);
                    }

                    GamePermissionDialogFragment.show((AppCompatActivity) v.getContext(), gameEntity, gameEntity.getInfo(), () -> {
                        Intent i = new Intent(WebActivity.getIntentForWebGame(progressBar.getContext(), linkEntity.getLink(), gameEntity.getName(), isPlay, linkEntity.getCloseButton()));
                        progressBar.getContext().startActivity(i);
                    });
                    break;
                case UPDATING:
                    Utils.toast(progressBar.getContext(), "正在加急更新版本，敬请后续留意");
                    break;
            }
        });

        // 显示预约
        if (gameEntity.isReservable()) {
            if (!ReservationRepository.thisGameHasBeenReserved(gameEntity.getId())) {
                progressBar.setText("预约");
                progressBar.setButtonStyle(DownloadButton.ButtonStyle.RESERVABLE);
            } else {
                progressBar.setText("已预约");
                progressBar.setButtonStyle(DownloadButton.ButtonStyle.RESERVED);
            }
            return;
        }

        // 显示下载按钮状态
        if (gameEntity.getApk().isEmpty() || gameEntity.getDownloadOffStatus() != null) {
            LinkEntity h5LinkEntity = gameEntity.getH5Link();
            String offStatus = gameEntity.getDownloadOffStatus();
            if (h5LinkEntity != null) {
                if ("play".equals(h5LinkEntity.getType())) {
                    progressBar.setText("开始玩");
                } else {
                    progressBar.setText("查看");
                }
                progressBar.setButtonStyle(DownloadButton.ButtonStyle.H5_GAME);
            } else {
                if (offStatus != null && "dialog".equals(offStatus)) {
                    progressBar.setText("查看");
                    progressBar.setButtonStyle(DownloadButton.ButtonStyle.NONE);
                } else if ("updating".equals(offStatus)) {
                    progressBar.setText("更新中");
                    progressBar.setButtonStyle(DownloadButton.ButtonStyle.UPDATING);
                } else {
                    progressBar.setText("暂无");
                    progressBar.setButtonStyle(DownloadButton.ButtonStyle.NONE);
                }
            }

        } else {
            String status = GameUtils.getDownloadBtnText(progressBar.getContext(), gameEntity, PluginLocation.only_game);
            switch (status) {
                case "插件化":
                    progressBar.setButtonStyle(DownloadButton.ButtonStyle.PLUGIN);
                    break;
                case "打开":
                case "启动":
                    progressBar.setButtonStyle(DownloadButton.ButtonStyle.LAUNCH_OR_OPEN);
                    break;
                default:
                    progressBar.setButtonStyle(DownloadButton.ButtonStyle.NORMAL);
                    break;
            }
            progressBar.setText(status);
        }

        // 显示下载过程状态
        if (gameEntity.getApk().size() == 1) {
            DownloadEntity downloadEntity = DownloadManager.getInstance().getDownloadEntitySnapshot(gameEntity);
            if (downloadEntity != null) {
                progressBar.setProgress((int) (downloadEntity.getPercent() * 10));
                switch (downloadEntity.getStatus()) {
                    case downloading:
                    case pause:
                    case timeout:
                    case neterror:
                    case diskisfull:
                    case diskioerror:
                    case waiting:
                        progressBar.setText(R.string.downloading);
                        if (downloadEntity.isPluggable() && PackagesManager.isInstalled(downloadEntity.getPackageName())) {
                            progressBar.setButtonStyle(DownloadButton.ButtonStyle.DOWNLOADING_PLUGIN);
                        } else {
                            progressBar.setButtonStyle(DownloadButton.ButtonStyle.DOWNLOADING_NORMAL);
                        }
                        break;
                    case done:
                        progressBar.setText(R.string.install);
                        if (downloadEntity.isPluggable()
                                && PackagesManager.isInstalled(downloadEntity.getPackageName())) {
                            progressBar.setButtonStyle(DownloadButton.ButtonStyle.INSTALL_PLUGIN);
                        } else {
                            progressBar.setButtonStyle(DownloadButton.ButtonStyle.INSTALL_NORMAL);
                        }
                        break;
                    case cancel:
                    case hijack:
                    case notfound:
                    case uncertificated:
                    case unqualified:
                    case unavailable:
                    case banned:
                        break;
                    default:
                        break;
                }
            }
        }
    }

    /**
     * 当页面完全重建时，若存在重建的DialogFragment，则需要手动恢复该DialogFragment之前配置的回调(因为DialogFragment重建时只会从arguments中获取之前的配置内容，
     * 而arguments无法传递回调)，或者dismiss该DialogFragment
     */
    private static void restoreDialogFragment(DownloadButton progressBar) {
        GamePermissionDialogFragment gamePermissionDialogFragment =
                ((GamePermissionDialogFragment) ((AppCompatActivity) progressBar.getContext()).getSupportFragmentManager().findFragmentByTag(GamePermissionDialogFragment.class.getName()));
        if (gamePermissionDialogFragment != null) {
            gamePermissionDialogFragment.dismissAllowingStateLoss();
        }
    }

    /*private static void download(DownloadProgressBar progressBar, GameEntity gameEntity, ExposureEvent traceEvent, @Nullable String entrance, @Nullable String location, View v) {
        if (gameEntity.getApk().size() == 1) {
            ApkEntity apk = gameEntity.getApk().get(0);
            DownloadDialogHelper.findAvailableDialogAndShow(
                    v.getContext(),
                    gameEntity,
                    apk,
                    () -> {
                        DialogUtils.checkDownload(v.getContext(), apk.getSize(),
                                isSubscribe -> download(progressBar, gameEntity, traceEvent, isSubscribe, entrance, location));
                    });
        } else {
            DownloadDialog.getInstance(v.getContext()).showPopupWindow(v, gameEntity,
                    entrance, location + gameEntity.getName(), traceEvent);
        }
    }*/


    private static void updateReservation(DownloadButton progressBar, GameEntity gameEntity) {
        // 显示预约
        if (gameEntity.isReservable()) {
            if (!ReservationRepository.thisGameHasBeenReserved(gameEntity.getId())) {
                progressBar.setText("预约");
                progressBar.setButtonStyle(DownloadButton.ButtonStyle.RESERVABLE);
            } else {
                progressBar.setText("已预约");
                progressBar.setButtonStyle(DownloadButton.ButtonStyle.RESERVED);
            }
        }
    }


    // 开始下载
    private static void download(DownloadButton progressBar,
                                 GameEntity gameEntity,
                                 ExposureEvent traceEvent,
                                 boolean isSubscribe,
                                 String entrance,
                                 String location) {
        String str = progressBar.getText().toString();
        String method;
        if (str.contains("更新")) {
            method = "更新";
        } else if (str.contains("插件化")) {
            method = "插件化";
        } else {
            method = progressBar.getContext().getString(R.string.download);
        }
        ApkEntity apkEntity = gameEntity.getApk().get(0);
        String msg = FileUtils.isCanDownload(progressBar.getContext(), apkEntity.getSize());
        if (TextUtils.isEmpty(msg)) {
            DownloadManager.createDownload(progressBar.getContext(),
                    apkEntity,
                    gameEntity,
                    method,
                    entrance,
                    location + gameEntity.getName(),
                    isSubscribe,
                    traceEvent);

            progressBar.setProgress(0);
            progressBar.setButtonStyle("插件化".equals(method) ?
                    DownloadButton.ButtonStyle.DOWNLOADING_PLUGIN : DownloadButton.ButtonStyle.DOWNLOADING_NORMAL);
        } else {
            Utils.toast(progressBar.getContext(), msg);
        }
    }

    public static void setGameLabelList(LinearLayout layout, List<TagStyleEntity> tagStyle) {
        GameViewUtils.setLabelList(layout.getContext(), layout, tagStyle);
    }

    // 包含测试开服标签
    public static void setGameTags(LinearLayout layout, GameEntity gameEntity) {
        try {
            if (layout.getVisibility() == View.GONE) return;
            ArrayList<TagStyleEntity> tagStyle = new ArrayList<>();
            TestEntity test = gameEntity.getTest();
            if (test != null
                    // 这个判断用于开测表列表
                    && !"type_tag".equals(test.getGameTag())) {
                if ("custom".equals(test.getGameTag())) {
                    TagStyleEntity typeTag = new TagStyleEntity();
                    if (!TextUtils.isEmpty(test.getText())) {
                        typeTag.setName(test.getText() != null ? test.getText() : "");
                    } else {
                        typeTag.setName(test.getType() != null ? test.getType() : "");
                    }
                    typeTag.setBackground("E8F3FF");
                    typeTag.setColor("1383EB");
                    tagStyle.add(typeTag);
                } else {
                    TagStyleEntity typeTag = new TagStyleEntity();
                    boolean isDarkModeOn = DarkModeUtils.INSTANCE.isDarkModeOn(layout.getContext());
                    typeTag.setName(test.getType() != null ? test.getType() : "");
                    typeTag.setBackground("1AFFA142");
                    typeTag.setColor(isDarkModeOn ? "EB9238" : "FFA142");
                    tagStyle.add(typeTag);

                    TagStyleEntity timeTag = new TagStyleEntity();
                    timeTag.setName(GameViewUtils.getGameTestDate(test.getStart()));
                    timeTag.setBackground("1A06CEA8");
                    timeTag.setColor(isDarkModeOn ? "07A385" : "06CEA8");
                    tagStyle.add(timeTag);
                }
            } else {
                tagStyle = gameEntity.getTagStyle();
            }
            GameViewUtils.setLabelList(layout.getContext(), layout, tagStyle);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void setVideoDetailGameTags(LinearLayout layout, GameEntity gameEntity) {
        try {
            ArrayList<TagStyleEntity> tagStyle = new ArrayList<>();
            TestEntity test = gameEntity.getTest();
            if (test != null
                    // 这个判断用于开测表列表
                    && !"type_tag".equals(test.getGameTag())) {
                TagStyleEntity typeTag = new TagStyleEntity();
                typeTag.setName(test.getType() != null ? test.getType() : "");
                typeTag.setBackground("FFF3E0");
                typeTag.setColor("FA8500");
                tagStyle.add(typeTag);

                TagStyleEntity timeTag = new TagStyleEntity();
                timeTag.setName(GameViewUtils.getGameTestDate(test.getStart()));
                timeTag.setBackground("E0FFF9");
                timeTag.setColor("00A887");
                tagStyle.add(timeTag);
            } else {
                tagStyle = gameEntity.getTagStyle();
            }
            GameViewUtils.setLabelList(layout.getContext(), layout, tagStyle, 4);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void isRefreshing(SwipeRefreshLayout layout, LoadStatus status) {
        if (status != LoadStatus.INIT_LOADING && status != LoadStatus.LIST_LOADING) {
            layout.setRefreshing(false);
        }
    }

    public static void setGameName(TextView view, GameEntity game, boolean isShowPlatform, @Nullable Boolean isShowSuffix) {
        if (isShowSuffix == null) isShowSuffix = true; // 默认显示
        String gameName;
        if (isShowPlatform && game.getApk().size() > 0) {
            gameName = String.format("%s - %s", !isShowSuffix ? game.getNameWithoutSuffix() : game.getName(),
                    PlatformUtils.getInstance(view.getContext()).getPlatformName(
                            game.getApk().get(0).getPlatform()));
            if (!gameName.equals((String) view.getTag(R.string.tag_game_name_id))) {
                view.setText(gameName);
                view.setTag(R.string.tag_game_name_id, gameName);
            }
        } else {
            gameName = !isShowSuffix ? game.getNameWithoutSuffix() : game.getName();
            if (gameName != null && !gameName.equals((String) view.getTag(R.string.tag_game_name_id))) {
                view.setText(gameName);
                view.setTag(R.string.tag_game_name_id, gameName);
            }
        }

    }

    public static void setCommunityImage(SimpleDraweeView imageView, List<String> images, List<CommunityVideoEntity> videos) {
        if (videos.size() > 0) {
            CommunityVideoEntity videoEntity = videos.get(0);
            ImageUtils.display(imageView, videoEntity.getPoster());
            imageView.setVisibility(View.VISIBLE);
        } else if (images.size() > 0) {
            imageView.setVisibility(View.VISIBLE);
            ImageUtils.display(imageView, images.get(0));
        } else {
            imageView.setVisibility(View.GONE);
        }
    }

    public static void setCommunityVideoDuration(TextView mVideoDuration, List<CommunityVideoEntity> videos) {
        if (videos != null && videos.size() > 0) {
            CommunityVideoEntity videoEntity = videos.get(0);
            mVideoDuration.setBackground(DrawableView.getOvalDrawable(R.color.black_alpha_50, 999F));
            mVideoDuration.setText(videoEntity.getDuration());
            mVideoDuration.setVisibility(View.VISIBLE);
        } else {
            mVideoDuration.setVisibility(View.GONE);
        }
    }

    public static void setGameTags(TextView view, List<TagStyleEntity> tags, int maxTags) {
        if (tags == null) {
            view.setText("");
            return;
        }

        int showCount = tags.size() > maxTags ? maxTags : tags.size(); // 最多显示3个

        StringBuilder content = new StringBuilder();
        for (int i = 0; i < showCount; i++) {
            TagStyleEntity tag = tags.get(i);
            content.append(tag.getName());
            if (i != showCount - 1) content.append("/");
        }

        Spannable span = new SpannableString(content);
        int index = 0;
        for (int i = 0; i < showCount; i++) {
            TagStyleEntity tag = tags.get(i);
            int start = index;
            int end = start + tag.getName().length() + ((i != showCount - 1) ? 1 : 0);
            index = end;
            span.setSpan(new ForegroundColorSpan(ExtensionsKt.hexStringToIntColor("#" + tag.getColor(), Color.WHITE)),
                    start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        view.setText(span);
    }

    public static void setVideoData(TextView view, int count) {
        if (count > 0) {
            ExtensionsKt.setDrawableStart(view, ContextCompat.getDrawable(view.getContext(), R.drawable.ic_video_data_up), null, null);
            view.setTextColor(ContextCompat.getColor(view.getContext(), R.color.text_EA3333));
            view.setText(count + "");
        } else {
            ExtensionsKt.removeDrawable(view);
            view.setTextColor(ContextCompat.getColor(view.getContext(), R.color.text_subtitleDesc));
            view.setText("-");
        }
    }
}
