package com.gh.common.util;

import android.app.Dialog;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.graphics.Color;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.gh.gamecenter.BuildConfig;
import com.gh.gamecenter.R;
import com.gh.gamecenter.adapter.LibaoDetailAdapter;
import com.gh.gamecenter.common.utils.DialogHelper;
import com.gh.gamecenter.common.utils.ExtensionsKt;
import com.gh.gamecenter.common.utils.NotificationHelper;
import com.gh.gamecenter.core.utils.ToastUtils;
import com.gh.gamecenter.core.utils.UrlFilterUtils;
import com.gh.gamecenter.entity.ApkEntity;
import com.gh.gamecenter.entity.LibaoEntity;
import com.gh.gamecenter.entity.LibaoStatusEntity;
import com.gh.gamecenter.entity.MeEntity;
import com.gh.gamecenter.common.entity.NotificationUgc;
import com.gh.gamecenter.entity.UserDataLibaoEntity;
import com.gh.gamecenter.common.eventbus.EBReuse;
import com.gh.gamecenter.eventbus.EBUISwitch;
import com.gh.gamecenter.geetest.GeetestUtils;
import com.gh.gamecenter.login.user.UserManager;
import com.gh.gamecenter.common.retrofit.JSONObjectResponse;
import com.gh.gamecenter.common.retrofit.Response;
import com.gh.gamecenter.retrofit.RetrofitManager;
import com.halo.assistant.HaloApp;
import com.lightgame.utils.Utils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
import retrofit2.HttpException;

/**
 * Created by khy on 2016/12/16.
 * 礼包工具类， 包括联网操作和领取按钮状态
 */
public class LibaoUtils {

    public static final String REFRESH_LIBAO_TIME = "refreshLiBaoTime";

    // 礼包去重
    public static List<LibaoEntity> removeDuplicateData(List<LibaoEntity> sourceList, List<LibaoEntity> rawList) {
        if (sourceList == null || sourceList.isEmpty()
                || rawList == null || rawList.isEmpty()) {
            return rawList;
        }
        String id;
        for (int i = 0; i < rawList.size(); i++) {
            id = rawList.get(i).getId();
            for (LibaoEntity libaoEntity : sourceList) {
                if (id.equals(libaoEntity.getId())) {
                    rawList.remove(i);
                    i--;
                    break;
                }
            }
        }
        return rawList;
    }

    private static void postLibaoLing(final Context context, final String libaoId,
                                      final PostLibaoListener listener, final String captchaCode) {

        Observable<ResponseBody> observable;
        if (!TextUtils.isEmpty(captchaCode)) {
            observable = RetrofitManager.getInstance().getApi().postLibaoLing(captchaCode, libaoId);
        } else {
            observable = RetrofitManager.getInstance().getApi().postLibaoLing(libaoId);
        }
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new JSONObjectResponse() {
                    @Override
                    public void onResponse(JSONObject response) {
                        listener.postSucceed(response);
                    }

                    @Override
                    public void onFailure(HttpException e) {
                        if (e != null && e.code() == 410) { // 该接口已废弃
                            Utils.toast(context, "领取失败，请安装最新版本的光环助手");
                        }
                        listener.postFailed(e);
                    }
                });
    }

    private static void postLibaoTao(final String libaoId,
                                     final PostLibaoListener listener) {
        RetrofitManager.getInstance().getApi().postLibaoTao(libaoId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new JSONObjectResponse() {
                    @Override
                    public void onResponse(JSONObject response) {
                        listener.postSucceed(response);
                    }

                    @Override
                    public void onFailure(HttpException e) {
                        listener.postFailed(e);
                    }
                });
    }

    public static void deleteLibaoCode(final String code,
                                       final PostLibaoListener listener) {
        RetrofitManager.getInstance().getApi().deleteLibaoCode(UserManager.getInstance().getUserId(), code)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<ResponseBody>() {
                    @Override
                    public void onResponse(ResponseBody response) {
                        listener.postSucceed(response);
                    }

                    @Override
                    public void onFailure(HttpException e) {
                        listener.postFailed(e);
                    }
                });
    }

    public static void getLibaoStatus(String ids, final PostLibaoListener listener) {
        RetrofitManager.getInstance().getApi().getLibaoStatus(UrlFilterUtils.getFilterQuery("libao_ids", ids))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<List<LibaoStatusEntity>>() {
                    @Override
                    public void onResponse(List<LibaoStatusEntity> response) {
                        listener.postSucceed(response);
                    }

                    @Override
                    public void onFailure(HttpException e) {
                        listener.postFailed(e);
                    }
                });
    }

    public static void setLiBaoBtnStatusRound(final TextView libaoBtn, LibaoEntity libaoEntity, boolean shouldUpdateStatus, Context context) {
        String status = shouldUpdateStatus ? updateStatus(libaoEntity) : libaoEntity.getStatus();
        libaoBtn.setTextColor(Color.WHITE);
        if (status == null || TextUtils.isEmpty(status)) return;
        // 领取限制为活动发放且未领取显示查看
        if (ExtensionsKt.toResString(R.string.libao_activity_grant).equals(libaoEntity.getReceiveLimit()) && !status.equals("linged")) {
            libaoBtn.setText(R.string.libao_check);
            libaoBtn.setBackgroundResource(R.drawable.button_normal_round_style);
            return;
        }
        switch (status) {
            case "ling":
                libaoBtn.setText(R.string.libao_ling);
                libaoBtn.setBackgroundResource(R.drawable.button_normal_round_style);
                break;
            case "tao":
                libaoBtn.setText(R.string.libao_tao);
                libaoBtn.setBackgroundResource(R.drawable.button_normal_round_style);
                break;
            case "coming":
                libaoBtn.setText(R.string.libao_coming);
                libaoBtn.setBackgroundResource(R.drawable.button_round_gray_light);
                libaoBtn.setTextColor(context.getResources().getColor(R.color.text_subtitleDesc));
                break;
            case "used_up":
                libaoBtn.setText(R.string.libao_used_up);
                libaoBtn.setBackgroundResource(R.drawable.button_normal_round_border);
                libaoBtn.setTextColor(context.getResources().getColor(R.color.theme_font));
                break;
            case "finish":
                libaoBtn.setText(R.string.libao_finish);
                libaoBtn.setBackgroundResource(R.drawable.button_border_round_gray);
                libaoBtn.setTextColor(context.getResources().getColor(R.color.button_gray));
                break;
            case "linged":
                libaoBtn.setText(R.string.libao_linged);
                libaoBtn.setBackgroundResource(R.drawable.button_round_gray_light);
                libaoBtn.setTextColor(context.getResources().getColor(R.color.text_subtitleDesc));
                break;
            case "taoed":
                libaoBtn.setText(R.string.libao_taoed);
                libaoBtn.setBackgroundResource(R.drawable.button_normal_round_border);
                libaoBtn.setTextColor(context.getResources().getColor(R.color.theme_font));
                break;
            case "copy":
                libaoBtn.setText(R.string.libao_copy);
                libaoBtn.setBackgroundResource(R.drawable.button_normal_round_style);
                break;
            case "repeatLing":
            case "repeatLinged":
                libaoBtn.setText(R.string.libao_repeat_ling);
                libaoBtn.setBackgroundResource(R.drawable.button_normal_round_border);
                libaoBtn.setTextColor(context.getResources().getColor(R.color.theme_font));
                break;
            case "repeatTao":
            case "repeatTaoed":
                libaoBtn.setText(R.string.libao_repeat_tao);
                libaoBtn.setBackgroundResource(R.drawable.button_normal_round_border);
                libaoBtn.setTextColor(context.getResources().getColor(R.color.theme_font));
                break;
            case "unshelve":
                libaoBtn.setBackgroundResource(R.drawable.button_border_round_gray);
                libaoBtn.setText(R.string.libao_unshelve);
                libaoBtn.setTextColor(context.getResources().getColor(R.color.button_gray));
                break;
            case "check":
                libaoBtn.setText(R.string.libao_check);
                libaoBtn.setBackgroundResource(R.drawable.button_normal_round_style);
                break;
            default:
                libaoBtn.setBackgroundResource(R.drawable.button_border_round_gray);
                libaoBtn.setText("异常");
                libaoBtn.setTextColor(context.getResources().getColor(R.color.button_gray));
                break;
        }
    }

    public static String updateStatus(LibaoEntity libaoEntity) {
        String status = libaoEntity.getStatus();
        String beforeStatus = libaoEntity.getBeforeStatus();
        if (libaoEntity.getRepeat() > 0 && libaoEntity.getMe() != null
                && libaoEntity.getMe().getUserDataLibaoList() != null) {

            MeEntity userData = libaoEntity.getMe();
            List<UserDataLibaoEntity> userDataLibaoList = userData.getUserDataLibaoList();

            int repeat = libaoEntity.getRepeat();
            int curStatusCount = 0; // 当前状态的领取/淘号数量

            for (UserDataLibaoEntity userDataLibaoEntity : userDataLibaoList) {
                if (beforeStatus != null && beforeStatus.equals(userDataLibaoEntity.getType())) {
                    curStatusCount++;
                }
            }

            // 由领取到淘号的状态转换
            if (repeat <= curStatusCount || curStatusCount == 0) { // 当前领取/淘号总数是否超过总重复领取次数 / 当前状态的礼包没有领取/淘号过
                if (curStatusCount == 0 && ("ling".equals(beforeStatus) || "tao".equals(beforeStatus))) {
                    if (isCanLing(libaoEntity)) { // 恢复原始状态
                        return beforeStatus;
                    }
                }
                return status;
            }

            if ((("linged").equals(status) || ("taoed").equals(status)) &&
                    ("ling".equals(beforeStatus) || "tao".equals(beforeStatus))) { //检查是否到了重复领取时间
                if (isCanLing(libaoEntity)) {
                    if ("ling".equals(beforeStatus)) {
                        status = "repeatLinged"; // 可以重复领取
                    } else {
                        status = "repeatTaoed"; // 可以重复领取
                    }
                } else {
                    if ("ling".equals(beforeStatus)) {
                        status = "repeatLing"; // 预备重复领取
                    } else {
                        status = "repeatTao"; // 预备重复领取
                    }
                }
                libaoEntity.setStatus(status);
                return status;
            }
        }
        return status;
    }

    public static boolean isCanLing(LibaoEntity libaoEntity) {
        List<UserDataLibaoEntity> userDataLibaoList = libaoEntity.getMe().getUserDataLibaoList();
        UserDataLibaoEntity userDataLibaoEntity = userDataLibaoList.get(userDataLibaoList.size() - 1);
        SimpleDateFormat formatDay = new SimpleDateFormat("dd", Locale.CHINA);
        long lingTime = userDataLibaoEntity.getTime() * 1000;
        long curTime = Utils.getTime(HaloApp.getInstance()) * 1000;
        int lingDay = Integer.parseInt(formatDay.format(lingTime));
        int curDay = Integer.parseInt(formatDay.format(curTime));
        if (curDay != lingDay || curTime - lingTime > 24 * 60 * 60 * 1000) {
            return true;
        } else {
            return false;
        }
    }

    public static void initLibaoBtn(final Context context, final TextView libaoBtn, final LibaoEntity libaoEntity,
                                    final boolean isInstallRequired, final LibaoDetailAdapter adapter, boolean shouldUpdateStatus,
                                    final String entrance, final OnLibaoStatusChangeListener listener) {
        setLiBaoBtnStatusRound(libaoBtn, libaoEntity, shouldUpdateStatus, context);
        String status = libaoEntity.getStatus();

        if (adapter != null) {
            if (libaoBtn.getText().toString().equals("再领")) {
                libaoBtn.setText("再领一个");
            }
            if (libaoBtn.getText().toString().equals("再淘")) {
                libaoBtn.setText("再淘一个");
            }
        }

        libaoBtn.setOnClickListener(v -> {
            String btnStatus = libaoBtn.getText().toString();
            // 领取限制
            CheckLoginUtils.checkLogin(context, "礼包详情-[" + btnStatus + "]", () -> {
                if ("领取".equals(btnStatus) || "淘号".equals(btnStatus)) {
                    if (isInstallRequired && !isAppInstalled(context, libaoEntity.getPackageName()) && adapter != null) {
                        String platform;
                        if (TextUtils.isEmpty(libaoEntity.getPlatform())) {
                            platform = "";
                        } else {
                            platform = PlatformUtils.getInstance(context).getPlatformName(libaoEntity.getPlatform());
                        }

                        boolean isExistPlatform = false;
                        ArrayList<ApkEntity> apk = adapter.getGameEntity().getApk();
                        for (ApkEntity apkEntity : apk) {
                            if (TextUtils.isEmpty(libaoEntity.getPlatform())) break;
                            if (libaoEntity.getPlatform().equals(apkEntity.getPlatform())) {
                                isExistPlatform = true;
                                break;
                            }
                        }

                        String dialogContent = context.getString(R.string.ling_rules_dialog, libaoEntity.getGame().getName(), platform);
                        boolean finalIsExistPlatform = isExistPlatform;
                        DialogHelper.showCenterWarningDialog(context, "条件不符",
                                Html.fromHtml(dialogContent), isExistPlatform ? "关闭" : "",
                                isExistPlatform ? "立即安装" : "关闭",
                                () -> {
                                    if (finalIsExistPlatform) {
                                        adapter.openDownload(libaoEntity.getPlatform());
                                    }
                                    return null;
                                }, () -> null);
                        return;
                    }
                }

                switch (btnStatus) {
                    case "未开始":
                        Utils.toast(context, "还没到开始领取时间");
                        break;
                    case "查看":
                        if (ExtensionsKt.toResString(R.string.libao_activity_grant).equals(libaoEntity.getReceiveLimit())) {
                            String url = libaoEntity.getActivityLink().getUrl();
                            DialogHelper.showLibaoActivityDialog(
                                    v.getContext(),
                                    TextUtils.isEmpty(url),
                                    () -> DirectUtils.directToWebView(v.getContext(), url, "查看礼包码弹窗-查看活动详情")
                            );
                        } else if (!TextUtils.isEmpty(libaoEntity.getDes())) {
                            DialogHelper.showCenterDialog(v.getContext(), "使用说明", Html.fromHtml(libaoEntity.getDes()), "关闭", "", () -> {
                            }, () -> {
                            });
                        }
                        break;
                    case "再领":
                    case "再领一个":
                    case "领取":
                        if ("repeatLing".equals(status)) {
                            ToastUtils.showToast("礼包每天0点刷新，明日0点后可再领一个");
                        } else {
                            libaoLing(context, libaoBtn, libaoEntity, adapter, isInstallRequired, null, entrance, listener);
                        }
                        break;
                    case "再淘":
                    case "再淘一个":
                    case "淘号":
                        libaoTao(context, libaoBtn, libaoEntity, isInstallRequired, adapter, status, entrance, listener);
                        break;
                }
            });
        });
    }

    public static void libaoBtnClick(final Context context, final TextView libaoBtn, final LibaoEntity libaoEntity,
                                     final boolean isInstallRequired, final LibaoDetailAdapter adapter,
                                     final String entrance, final String loginEntrance, final OnLibaoStatusChangeListener listener) {
        String status = libaoEntity.getStatus();
        // 领取限制
        CheckLoginUtils.checkLogin(context, loginEntrance, () -> {// "礼包详情-[" + btnStatus + "]"
            if ("ling".equals(status) || "tao".equals(status)) {
                if (isInstallRequired && !isAppInstalled(context, libaoEntity.getPackageName()) && adapter != null) {
                    String platform;
                    if (TextUtils.isEmpty(libaoEntity.getPlatform())) {
                        platform = "";
                    } else {
                        platform = PlatformUtils.getInstance(context).getPlatformName(libaoEntity.getPlatform());
                    }

                    boolean isExistPlatform = false;
                    ArrayList<ApkEntity> apk = adapter.getGameEntity().getApk();
                    for (ApkEntity apkEntity : apk) {
                        if (TextUtils.isEmpty(libaoEntity.getPlatform())) break;
                        if (libaoEntity.getPlatform().equals(apkEntity.getPlatform())) {
                            isExistPlatform = true;
                            break;
                        }
                    }

                    String dialogContent = context.getString(R.string.ling_rules_dialog, libaoEntity.getGame().getName(), platform);
                    boolean finalIsExistPlatform = isExistPlatform;
                    DialogHelper.showWarningDialog(context, "条件不符",
                            Html.fromHtml(dialogContent), isExistPlatform ? "关闭" : "",
                            isExistPlatform ? "立即安装" : "关闭",
                            () -> {
                                if (finalIsExistPlatform) {
                                    adapter.openDownload(libaoEntity.getPlatform());
                                }
                                return null;
                            }, null);
                    return;
                }
            }

            switch (Objects.requireNonNull(status)) {
                case "coming":
                    Utils.toast(context, "还没到开始领取时间");
                    break;
                case "check":
                    if (!TextUtils.isEmpty(libaoEntity.getDes())) {
                        DialogHelper.showDialog(context, "使用说明", Html.fromHtml(libaoEntity.getDes()), "关闭", "", () -> {
                        }, () -> {
                        }, false, "", "");
                    }
                    break;
                case "repeatLing":
                    ToastUtils.showToast("礼包每天0点刷新，明日0点后可再领一个");
                    break;
                case "repeatLinged":
                case "ling":
                    libaoLing(context, libaoBtn, libaoEntity, adapter, isInstallRequired, null, entrance, listener);
                    break;
                case "repeatTao":
                case "repeatTaoed":
                case "tao":
                    libaoTao(context, libaoBtn, libaoEntity, isInstallRequired, adapter, status, entrance, listener);
                    break;
            }
        });
    }

    private static void libaoTao(Context context, TextView libaoBtn, LibaoEntity libaoEntity, boolean isInstallRequired, LibaoDetailAdapter adapter,
                                 String status, String entrance, final OnLibaoStatusChangeListener listener) {
        if ("repeatTao".equals(status)) {
            Utils.toast(context, "没到重复淘号时间, 礼包每天0点刷新");
            return;
        }
        final Dialog loadingDialog = DialogUtils.showWaitDialog(context, "淘号中...");
        postLibaoTao(libaoEntity.getId(), new PostLibaoListener() {
            @Override
            public void postSucceed(Object response) {

                if (loadingDialog != null) loadingDialog.dismiss();

                JSONObject responseBody = (JSONObject) response;
                String libaoCode = null;
                boolean hasSame = false;
                try {
                    hasSame = responseBody.getBoolean("has_same");
                    libaoCode = responseBody.getString("code");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (TextUtils.isEmpty(libaoCode)) {
                    try {
                        String detail = responseBody.getString("detail").toLowerCase();
                        switch (detail) {
                            case "maintaining":
                                Utils.toast(context, "网络状态异常，请稍后再试");
                                break;
                            case "fail to compete":
                                Utils.toast(context, "淘号失败，稍后重试");
                                break;
                            default:
                                Utils.toast(context, "淘号异常");
                                break;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    return;
                }
                libaoEntity.setStatus("taoed");
                UserDataLibaoEntity me = new UserDataLibaoEntity(libaoCode, "ling", Utils.getTime(context));
                initLibaoCode(libaoEntity, me);
                if (adapter != null) adapter.initLibaoCode(me);
                EventBus.getDefault().post(new EBReuse("libaoChanged"));
                if (listener != null) listener.onLibaoStatusChange();
                uploadEvent(libaoEntity, true, entrance);
                String des;
                if (!hasSame) {
                    des = "淘号成功，请进入礼包详情查看兑换方法";
                } else {
                    des = "您已领取过相同的礼包，可能无法成功兑换";
                }
                ToastUtils.showToast(des);
            }

            @Override
            public void postFailed(Throwable error) {
                Utils.log("---" + error.toString());

                if (loadingDialog != null) loadingDialog.dismiss();

                if (error instanceof HttpException) {
                    HttpException exception = (HttpException) error;
                    if (exception.code() == 403) {
                        try {
                            JSONObject errorJson = new JSONObject(exception.response().errorBody().string());
                            String detail = errorJson.getString("detail").toLowerCase();
                            switch (detail) {
                                case "coming":
                                    Utils.toast(context, "礼包领取时间未开始");
                                    break;
                                case "finish":
                                    Utils.toast(context, "礼包领取时间已结束");
                                    break;
                                case "fetched":
                                    Utils.toast(context, "你今天已领过这个礼包了, 不能再淘号");

                                    if (libaoBtn != null) {
                                        libaoBtn.setText("已淘号");
                                        libaoBtn.setBackgroundResource(R.drawable.libao_taoed_style);
                                        libaoBtn.setTextColor(ContextCompat.getColorStateList(context, R.color.libao_taoed_selector));
                                    }
                                    libaoEntity.setStatus("taoed");
                                    break;
                                case "try tao":
                                case "used up":
                                    DialogUtils.showHintDialog(context, "礼包已领光"
                                            , "手速不够快，礼包已经被抢光了，十分抱歉", "知道了");
                                    break;
                                case "maintaining":
                                    Utils.toast(context, "网络状态异常，请稍后再试");
                                    break;
                                case "fail to compete":
                                    Utils.toast(context, "淘号失败，稍后重试");
                                    break;
                                default:
                                    Utils.toast(context, "操作失败");
                                    break;

                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            Utils.toast(context, "礼包处理异常" + ex.toString());
                        }
                        return;
                    } else if (exception.code() == 401) {
                        return;
                    }
                }
                Utils.toast(context, "发生异常");
            }
        });
    }

    private static void libaoLing(final Context context, TextView libaoBtn, final LibaoEntity libaoEntity, final LibaoDetailAdapter adapter,
                                  final boolean isInstallRequired, String captchaCode, final String entrance, final OnLibaoStatusChangeListener listener) {

        if (BuildConfig.DEBUG) {
            if (libaoBtn != null) {
                Log.e("LIBAO", "context? " + context + libaoBtn.getContext());
            } else {
                Log.e("LIBAO", "context? " + context);
            }

        }

        final Dialog loadingDialog = DialogUtils.showWaitDialog(context, "领取中...");

        postLibaoLing(context, libaoEntity.getId(), new PostLibaoListener() {
            @Override
            public void postSucceed(Object response) {
                if (loadingDialog != null) loadingDialog.dismiss();

                JSONObject responseBody = (JSONObject) response;
                boolean hasSame = false; //是否领取过相同的礼包
                String libaoCode = null;
                int gameApkSize = 1;//游戏apk的size，大于1为“多版本插件游戏”，否则为“非插件游戏/单版本插件游戏”
                try {
                    hasSame = responseBody.getBoolean("has_same");
                    libaoCode = responseBody.getString("code");
                    gameApkSize = responseBody.getInt("game_apk_size");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (TextUtils.isEmpty(libaoCode)) {
                    Utils.toast(context, "领取异常");
                    return;
                }
                libaoEntity.setAvailable(libaoEntity.getAvailable() - 1);
                libaoEntity.setStatus("linged");
                UserDataLibaoEntity me = new UserDataLibaoEntity(libaoCode, "ling", Utils.getTime(context));
                initLibaoCode(libaoEntity, me);
                if (listener != null) listener.onLibaoStatusChange();
                EventBus.getDefault().post(new EBReuse("libaoChanged"));
                uploadEvent(libaoEntity, false, entrance);

                if (adapter != null) {
                    adapter.initLibaoCode(new UserDataLibaoEntity(libaoCode, "ling", Utils.getTime(context)));
                    adapter.notifyDataSetChanged();
                }
                boolean finalHasSame = hasSame;
                NotificationHelper.showNotificationHintDialog(NotificationUgc.GIFT, isShow -> {
                    if (!isShow) {
                        String des;
                        if (!finalHasSame) {
                            des = "领取成功，请进入礼包详情查看兑换方法";
                        } else {
                            des = "您已领取过相同的礼包，可能无法成功兑换";
                        }
                        ToastUtils.showToast(des);
                    }
                    return null;
                });
            }

            @Override
            public void postFailed(Throwable error) {
                if (loadingDialog != null) loadingDialog.dismiss();

                if (error instanceof HttpException) {
                    HttpException exception = (HttpException) error;
                    if (exception.code() == 403) {
                        try {
                            String string = exception.response().errorBody().string();
                            JSONObject errorJson = new JSONObject(string);
                            String detail = errorJson.getString("detail").toLowerCase();
                            switch (detail) {
                                case "coming":
                                    Utils.toast(context, "礼包领取时间未开始");
                                    break;
                                case "finish":
                                    Utils.toast(context, "礼包领取时间已结束");
                                    break;
                                case "fetched":
                                    Utils.toast(context, "你已领过这个礼包了");
                                    int countdown = 0;
                                    if (errorJson.toString().contains("countdown")) {
                                        JSONObject data = errorJson.getJSONObject("data");
                                        countdown = data.getInt("countdown");
                                    }
                                    if (countdown > 0 && countdown < 60 * 10) {
                                        EventBus.getDefault().post(new EBUISwitch(REFRESH_LIBAO_TIME, countdown));
                                    }

                                    if (libaoBtn != null) {
                                        libaoBtn.setText(R.string.libao_linged);
                                        libaoBtn.setBackgroundResource(R.drawable.libao_linged_style);
                                        libaoBtn.setTextColor(ContextCompat.getColorStateList(context, R.color.libao_linged_selector));
                                    }
                                    libaoEntity.setStatus("linged");
                                    break;
                                case "try tao":
                                case "used up":
                                    DialogUtils.showHintDialog(context, "礼包已领光"
                                            , "手速不够快，礼包已经被抢光了，十分抱歉", "知道了");
                                    libaoEntity.setStatus("used_up");
                                    if (libaoBtn != null) {
                                        initLibaoBtn(context, libaoBtn, libaoEntity, isInstallRequired, adapter, false, entrance, listener);
                                    }
                                    break;
                                case "maintaining":
                                    Utils.toast(context, "网络状态异常，请稍后再试");
                                    break;
                                default:
                                    Utils.toast(context, "操作失败");
                                    break;
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            Utils.toast(context, "礼包处理异常");
                        }
                        return;
                    } else if (exception.code() == 412) {
                        // 需要验证
                        GeetestUtils.getInstance().showDialog(context, captcha ->
                                libaoLing(context, libaoBtn, libaoEntity, adapter, isInstallRequired, captcha, entrance, listener));
                        return;
                    } else if (exception.code() == 401) {
                        return;
                    }
                }
                Utils.toast(context, "发生异常");
            }
        }, captchaCode);
    }

    public static void initLibaoCode(LibaoEntity libaoEntity, UserDataLibaoEntity userDataLibaoEntity) {
        MeEntity userData = libaoEntity.getMe();
        if (userData == null) {
            userData = new MeEntity();
            libaoEntity.setMe(userData);
        }

        List<UserDataLibaoEntity> userDataLibaoList = userData.getUserDataLibaoList();
        if (userDataLibaoList == null) {
            userDataLibaoList = new ArrayList<>();
            userData.setUserDataLibaoList(userDataLibaoList);
        }
        userDataLibaoList.add(userDataLibaoEntity);

    }

    private static void uploadEvent(LibaoEntity libaoEntity, boolean isTao, String entrance) {
        String location = "";
        if (!libaoEntity.getClickReceiveBtnIn()) {
            location = "礼包详情";
        } else {
            if (entrance.contains("游戏详情")) {
                location = "游戏详情";
            } else if (entrance.contains("礼包中心:最新")) {
                location = "礼包中心-最新";
            } else if (entrance.contains("礼包中心:关注")) {
                location = "礼包中心-关注";
            }
        }
        String event = isTao ? "game_gift_dig_successful" : "game_gift_get_successful";
        LogUtils.uploadReceiveGift(event, libaoEntity.getId(), libaoEntity.getName(), location,
                libaoEntity.getGame() == null ? "" : libaoEntity.getGame().getId(), libaoEntity.getGame() == null ? "" : libaoEntity.getGame().getName());
    }

    public static boolean isAppInstalled(Context context, String packageName) {
        List<PackageInfo> pinfo = PackageUtils.getInstalledPackages(context, 0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals(packageName)) {
                    return true;
                }
            }
        }
        return false;
    }

    public static void lunningAppDialog(final Context context, Spanned msg, final LibaoEntity libaoEntity) {
        DialogHelper.showCenterWarningDialog(context, "复制成功", msg
                , "关闭", "启动游戏"
                , () -> {
                    if (LibaoUtils.isAppInstalled(context, libaoEntity.getPackageName())) {
                        PackageUtils.launchApplicationByPackageName(context, libaoEntity.getPackageName());
                    } else {
                        Utils.toast(context, "请安装游戏：" + libaoEntity.getGame().getName()
                                + PlatformUtils.getInstance(context).getPlatformName(libaoEntity.getPlatform()) + "版");
                    }
                    return null;
                }, () -> null);
    }

    //复制文字
    public static void copyLink(String copyContent, Context context) {
        ExtensionsKt.copyTextAndToast(copyContent, copyContent + "  复制成功");
    }


    // 合并List<LibaoStatusEntity> 和 List<LibaoEntity>
    public static void initLiBaoEntity(List<LibaoStatusEntity> statusList,
                                       List<LibaoEntity> libaoEntities) {

        for (LibaoEntity libaoEntity : libaoEntities) {
            for (LibaoStatusEntity libaoStatusEntity : statusList) {
                if (libaoEntity.getId().equals(libaoStatusEntity.getId())) {
                    libaoEntity.setBeforeStatus(libaoStatusEntity.getStatus());
                    libaoStatusEntity.setBeforeStatus(libaoStatusEntity.getStatus());

                    MeEntity userData = libaoEntity.getMe();
                    if (userData != null && userData.getUserDataLibaoList() != null && userData.getUserDataLibaoList().size() > 0) {
                        List<UserDataLibaoEntity> userDataLibaoList = userData.getUserDataLibaoList();
                        UserDataLibaoEntity userDataLibaoEntity = userDataLibaoList.get(userDataLibaoList.size() - 1);
                        if ("ling".equals(userDataLibaoEntity.getType())) { // 拿最后一次领取的状态判断
                            libaoEntity.setStatus("linged");
                        } else {
                            libaoEntity.setStatus("taoed");
                        }
                    } else {
                        libaoEntity.setStatus(libaoStatusEntity.getStatus());
                    }
                    libaoEntity.setAvailable(libaoStatusEntity.getAvailable());
                    libaoEntity.setTotal(libaoStatusEntity.getTotal());
                }
            }
        }
    }

    public static void initLiBaoEntity(LibaoStatusEntity libaoStatusEntity,
                                       LibaoEntity libaoEntity) {
        if (libaoEntity.getId().equals(libaoStatusEntity.getId())) {
            libaoEntity.setBeforeStatus(libaoStatusEntity.getStatus());
            libaoStatusEntity.setBeforeStatus(libaoStatusEntity.getStatus());

            MeEntity userData = libaoEntity.getMe();
            if (userData != null && userData.getUserDataLibaoList() != null && userData.getUserDataLibaoList().size() > 0) {
                List<UserDataLibaoEntity> userDataLibaoList = userData.getUserDataLibaoList();
                UserDataLibaoEntity userDataLibaoEntity = userDataLibaoList.get(userDataLibaoList.size() - 1);
                if ("ling".equals(userDataLibaoEntity.getType())) { // 拿最后一次领取的状态判断
                    libaoEntity.setStatus("linged");
                } else {
                    libaoEntity.setStatus("taoed");
                }
            } else {
                libaoEntity.setStatus(libaoStatusEntity.getStatus());
            }
            libaoEntity.setAvailable(libaoStatusEntity.getAvailable());
            libaoEntity.setTotal(libaoStatusEntity.getTotal());
        }
    }


    public interface PostLibaoListener {
        void postSucceed(Object response);

        void postFailed(Throwable error);
    }

    public interface OnLibaoStatusChangeListener {
        void onLibaoStatusChange();
    }
}
