package com.gh.gamecenter.common.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.gh.gamecenter.common.R;
import com.gh.gamecenter.common.callback.BiCallback;
import com.gh.gamecenter.common.constant.EntranceConsts;
import com.gh.gamecenter.common.constant.RouteConsts;
import com.gh.gamecenter.common.entity.AdditionalParamsEntity;
import com.gh.gamecenter.common.entity.ShareEntity;
import com.gh.gamecenter.common.eventbus.EBShare;
import com.gh.gamecenter.core.provider.IConfigProvider;
import com.gh.gamecenter.core.provider.IEnergyTaskProvider;
import com.gh.gamecenter.core.provider.IPackageHelperProvider;
import com.gh.gamecenter.core.provider.IPackageUtilsProvider;
import com.gh.gamecenter.core.utils.DisplayUtils;
import com.gh.gamecenter.core.utils.IntentUtils;
import com.gh.gamecenter.core.utils.MtaHelper;
import com.lightgame.utils.Utils;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.greenrobot.eventbus.EventBus;

import java.io.ByteArrayOutputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by khy on 2016/9/4.
 */
public class ShareUtils {

    private static ShareUtils sInstance;
    private IWXAPI mIWXAPI;
    private Tencent mTencent;
    private String shareUrl;
    private String shareIcon;
    private String mTitle;
    private String mSummary;

    private int[] arrLogo = {
            R.drawable.share_wechat_logo,
            R.drawable.share_wechatmoments_logo,
            R.drawable.share_qq_logo,
            R.drawable.share_qzone_logo,
            R.drawable.share_sinaweibo_logo,
            R.drawable.share_shortmessage_logo,
            R.drawable.share_copyfont_logo,
            R.drawable.share_cancel_logo
    };

    public enum ShareEntrance {
        news("资讯文章"),
        game("游戏详情"),      // 普通游戏
        plugin("游戏详情"),    // 插件游戏
        tools("工具箱"),
        askInvite("邀请回答"),
        askNormal("问题详情"),  //问答问题
        answerNormal("回答详情"),  //问答答案
        shareGh("APP分享"),
        communityArticle("文章详情"),
        video("视频"),
        web("web链接"),
        userHome("个人主页"),
        qaDetail("QA内容详情"),
        inviteFriends("邀请好友"),
        gameCollection("游戏单");

        private String name;

        ShareEntrance(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }
    }

    public enum ShareType {
        qq("qq"),
        qqZone("qq空间"),
        weibo("微博"),
        wechat("微信"),
        wechatMoments("朋友圈");

        private String name;

        ShareType(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }
    }

    private String[] arrLabel = {"微信好友", "朋友圈", "QQ好友", "QQ空间", "新浪微博", "短信", "复制链接", "取消"};

    private WeakReference<PopupWindow> popupWindow;

    private ShareEntrance mShareEntrance;
    public static String shareType = "";//分享类型(事件上报用)
    public static ShareEntrance shareEntrance;//分享入口(事件上报和视频分享统计用)
    public static String resourceId = "";//分享内容的id(事件上报用)
    public static ShareEntity shareEntity;//分享信息(事件上报用)
    private static ShareType mShareType;//分享类型(事件上报用)
    public static AdditionalParamsEntity additionalParams;//附加参数(事件上报用)

    private WeakReference<Activity> mActivity;

    private Context mContext; // application context
    //QQ或者QQ空间分享回调处理
    public IUiListener QqShareListener = new IUiListener() {
        @Override
        public void onComplete(Object o) {
            Utils.toast(mContext, R.string.share_success_hint);
            IEnergyTaskProvider energyTaskProvider = (IEnergyTaskProvider) ARouter.getInstance().build(RouteConsts.provider.energyTask).navigation();
            EventBus.getDefault().post(new EBShare(ShareUtils.shareEntrance));
            LogUtils.uploadShareResult(shareType, ShareUtils.shareEntrance.getName(), "success",
                    ShareUtils.shareEntity.getShareUrl(), ShareUtils.shareEntity.getShareTitle(), ShareUtils.shareEntity.getSummary(), ShareUtils.resourceId);

            if (energyTaskProvider != null) {
                energyTaskProvider.postEnergyTaskForShare(ShareUtils.shareEntrance.getName(), ShareUtils.resourceId, ShareUtils.shareEntity.getShareUrl());
                if (ShareUtils.shareEntrance == ShareEntrance.inviteFriends) {
                    energyTaskProvider.logInviteResult("成功", mShareType.getName());
                }
            }

            if (ShareUtils.shareEntrance == ShareUtils.ShareEntrance.askNormal ||
                    ShareUtils.shareEntrance == ShareEntrance.communityArticle ||
                    ShareUtils.shareEntrance == ShareUtils.ShareEntrance.video) {
                NewLogUtils.logShareResult(ShareUtils.additionalParams, true);
            } else if (ShareUtils.shareEntrance == ShareEntrance.gameCollection) {
                String shareType;
                if (mShareType == ShareType.qq) {
                    shareType = "QQ好友";
                } else {
                    shareType = "QQ空间";
                }
                NewLogUtils.logViewOrClickGameCollectionDetail(
                        "click_game_collect_detail_favorite_success",
                        shareEntity.getShareTitle(),
                        resourceId,
                        shareType
                );
            }
        }

        @Override
        public void onError(UiError uiError) {
            Utils.toast(mContext, R.string.share_fail_hint);
            LogUtils.uploadShareResult(shareType, ShareUtils.shareEntrance.getName(), "fail",
                    ShareUtils.shareEntity.getShareUrl(), ShareUtils.shareEntity.getShareTitle(), ShareUtils.shareEntity.getSummary(), ShareUtils.resourceId);
            if (ShareUtils.shareEntrance == ShareEntrance.inviteFriends) {
                IEnergyTaskProvider energyTaskProvider = (IEnergyTaskProvider) ARouter.getInstance().build(RouteConsts.provider.energyTask).navigation();
                if (energyTaskProvider != null) {
                    energyTaskProvider.logInviteResult("失败", mShareType.getName());
                }
            }
            if (ShareUtils.shareEntrance == ShareUtils.ShareEntrance.askNormal ||
                    ShareUtils.shareEntrance == ShareEntrance.communityArticle ||
                    ShareUtils.shareEntrance == ShareUtils.ShareEntrance.video) {
                NewLogUtils.logShareResult(ShareUtils.additionalParams, false);
            }
        }

        @Override
        public void onCancel() {
            Utils.toast(mContext, R.string.share_cancel_hint);
            LogUtils.uploadShareResult(shareType, ShareUtils.shareEntrance.getName(), "cancel",
                    ShareUtils.shareEntity.getShareUrl(), ShareUtils.shareEntity.getShareTitle(), ShareUtils.shareEntity.getSummary(), ShareUtils.resourceId);
            if (ShareUtils.shareEntrance == ShareEntrance.inviteFriends) {
                IEnergyTaskProvider energyTaskProvider = (IEnergyTaskProvider) ARouter.getInstance().build(RouteConsts.provider.energyTask).navigation();
                if (energyTaskProvider != null) {
                    energyTaskProvider.logInviteResult("取消", mShareType.getName());
                }
            }
            if (ShareUtils.shareEntrance == ShareUtils.ShareEntrance.askNormal ||
                    ShareUtils.shareEntrance == ShareEntrance.communityArticle ||
                    ShareUtils.shareEntrance == ShareUtils.ShareEntrance.video) {
                NewLogUtils.logShareResult(ShareUtils.additionalParams, false);
            }
        }

        @Override
        public void onWarning(int i) {

        }
    };

    private ShareUtils(Context context) {
        IConfigProvider configProvider = (IConfigProvider) ARouter.getInstance().build(RouteConsts.provider.config).navigation();
        Tencent.setIsPermissionGranted(true);

        mContext = context.getApplicationContext();
        mTencent = Tencent.createInstance(configProvider.getTencentAppId(), mContext); //初始化QQ分享
        mIWXAPI = WXAPIFactory.createWXAPI(mContext, configProvider.getWechatAppId()); //初始化微信分享
    }

    public static ShareUtils getInstance(Context context) {
        if (sInstance == null) {
            sInstance = new ShareUtils(context);
        }
        return sInstance;
    }

    //检查是否安装手机QQ
    public static boolean isQQClientAvailable(Context context) {
        IPackageUtilsProvider packageUtilsConfig = (IPackageUtilsProvider) ARouter.getInstance().build(RouteConsts.provider.packageUtils).navigation();
        List<PackageInfo> pinfo = packageUtilsConfig.getInstalledPackages(context, 0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if ("com.tencent.mobileqq".equals(pn) || "com.tencent.tim".equals(pn)) {
                    return true;
                }
            }
        }
        return false;
    }

    // 邀请好友（专属链接）
    public void shareInviteFriends(Activity activity, String url, String way) {
        if (activity.isFinishing()) return;
        this.mActivity = new WeakReference<>(activity);
        this.shareIcon = getHttpsUrl(activity.getString(R.string.gh_icon_url));
        this.shareUrl = url;
        this.mSummary = "卡牌神器，海量游戏下载，积分大礼，等你尝鲜";
        this.mTitle = "推荐一款好玩的游戏下载APP【光环助手】";
        this.mShareEntrance = ShareEntrance.inviteFriends;
        ShareUtils.shareEntrance = mShareEntrance;
        ShareUtils.resourceId = "";
        ShareUtils.shareEntity = new ShareEntity(shareUrl, mTitle, mSummary);
        LogUtils.uploadShareEnter(mShareEntrance.getName(), shareUrl, mTitle, mSummary, "");

        // 分享
        switch (way) {
            case "qq":
                mShareType = ShareType.qq;
                qqShare();
                break;
            case "qq_zone":
                mShareType = ShareType.qqZone;
                qZoneShare();
                break;
            case "wechat":
                mShareType = ShareType.wechat;
                wechatShare();
                break;
            case "wechat_moments":
                mShareType = ShareType.wechatMoments;
                wechatMomentsShare();
                break;
            case "weibo":
                mShareType = ShareType.weibo;
                sinaWeiboShare();
                break;
        }
    }

    public void showShareUserHomeWindows(Activity activity, View view, String url, String icon, String shareTitle, String shareSummary, ShareEntrance shareEntrance, String id, ShareCallBack callBack) {
        if (activity.isFinishing()) return;
        this.mActivity = new WeakReference<>(activity);
        this.shareIcon = getHttpsUrl(icon);
        this.shareUrl = url;
        this.mSummary = shareSummary;
        this.mTitle = shareTitle;
        this.mShareEntrance = shareEntrance;
        ShareUtils.shareEntrance = mShareEntrance;
        ShareUtils.resourceId = id;
        ShareUtils.shareEntity = new ShareEntity(shareUrl, mTitle, mSummary);
        LogUtils.uploadShareEnter(mShareEntrance.getName(), shareUrl, mTitle, mSummary, id);

        View contentView = View.inflate(mActivity.get(), R.layout.popup_share_dialog, null);
        contentView.setFocusable(true);
        contentView.setFocusableInTouchMode(true);

        View wechatType = contentView.findViewById(R.id.item_wechat);
        View wechatMomentsType = contentView.findViewById(R.id.item_wechat_moments);
        View qqType = contentView.findViewById(R.id.item_qq);
        View qqZoneType = contentView.findViewById(R.id.item_qq_zone);
        View weiboType = contentView.findViewById(R.id.item_weibo);

        wechatType.setOnClickListener((v) -> wechatShare());
        wechatMomentsType.setOnClickListener((v) -> wechatMomentsShare());
        qqType.setOnClickListener((v) -> qqShare());
        qqZoneType.setOnClickListener((v) -> qZoneShare());
        weiboType.setOnClickListener((v) -> sinaWeiboShare());

        popupWindow = new WeakReference<>(new SharePopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT
                , LinearLayout.LayoutParams.MATCH_PARENT, true));
//        popupWindow.get().setAnimationStyle(R.style.popwindow_exit_only_anim_style);
        //解决PopupWindow无法覆盖状态栏
        popupWindow.get().setClippingEnabled(false);

        int bottomLocation = -DisplayUtils.retrieveNavigationHeight(activity);
        if (!DisplayUtils.isNavigationBarShow(activity)) {
            bottomLocation = 0;
        }
        try {
            popupWindow.get().showAtLocation(view, Gravity.NO_GRAVITY, 0, bottomLocation);
        } catch (Exception e) {
            e.printStackTrace();
        }

        contentView.setOnClickListener(v -> safelyDismiss());

        contentView.setOnKeyListener((v, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_BACK
                    && event.getRepeatCount() == 0
                    && popupWindow.get() != null
                    && popupWindow.get().isShowing()) {
                if (callBack != null) {
                    callBack.onCancel();
                }
                safelyDismiss();
            }
            return false;
        });
    }

    public void showShareWindowsCallback(Activity activity, View view, String url, String icon, String shareTitle, String shareSummary, ShareEntrance shareEntrance, String id, ShareCallBack callBack) {
        if (activity.isFinishing()) return;
        this.mActivity = new WeakReference<>(activity);
        this.shareIcon = getHttpsUrl(icon);
        this.shareUrl = url;
        this.mSummary = shareSummary;
        this.mTitle = shareTitle;
        this.mShareEntrance = shareEntrance;
        ShareUtils.shareEntrance = mShareEntrance;
        ShareUtils.resourceId = id;
        ShareUtils.shareEntity = new ShareEntity(shareUrl, mTitle, mSummary);
        LogUtils.uploadShareEnter(mShareEntrance.getName(), shareUrl, mTitle, mSummary, id);

        View contentView = View.inflate(mActivity.get(), R.layout.share_popup_layout, null);
        contentView.setFocusable(true);
        contentView.setFocusableInTouchMode(true);
        RecyclerView shareRecyclerView = contentView.findViewById(R.id.share_rv);

        shareRecyclerView.setPadding(DisplayUtils.dip2px(mContext, 20), DisplayUtils.dip2px(mContext, 10), DisplayUtils.dip2px(mContext, 20), 0);

        //RecyclerView禁止滑动
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 4) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };

        shareRecyclerView.setLayoutManager(gridLayoutManager);
        ShareRecyclerViewAdapter shareRecyclerViewAdapter = new ShareRecyclerViewAdapter();
        shareRecyclerView.setAdapter(shareRecyclerViewAdapter);
        shareRecyclerViewAdapter.setOnItemClickListener(position -> {
            if (callBack != null) {
                if (position == arrLabel.length - 1) {
                    callBack.onCancel();
                } else {
                    callBack.onSuccess(arrLabel[position]);
                }
            }
        });

        if (mShareEntrance == ShareEntrance.shareGh) {
            RelativeLayout layout = (RelativeLayout) view;
            layout.addView(contentView);
            arrLabel[6] = "邮件";
            arrLogo[6] = R.drawable.share_email_logo;
            arrLabel[7] = "复制链接";
            arrLogo[7] = R.drawable.share_copyfont_logo;
            return;
        } else {
            arrLabel[6] = "复制链接";
            arrLogo[6] = R.drawable.share_copyfont_logo;
            arrLabel[7] = "取消";
            arrLogo[7] = R.drawable.share_cancel_logo;
        }

        popupWindow = new WeakReference<>(new SharePopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT
                , LinearLayout.LayoutParams.MATCH_PARENT, true));
        popupWindow.get().setAnimationStyle(R.style.popwindow_exit_only_anim_style);
        //解决PopupWindow无法覆盖状态栏
        popupWindow.get().setClippingEnabled(false);

        int bottomLocation = -DisplayUtils.retrieveNavigationHeight(activity);
        if (!DisplayUtils.isNavigationBarShow(activity)) {
            bottomLocation = 0;
        }
        try {
            popupWindow.get().showAtLocation(view, Gravity.NO_GRAVITY, 0, bottomLocation);
        } catch (Exception e) {
            e.printStackTrace();
        }

        contentView.setOnClickListener(v -> safelyDismiss());

        contentView.setOnKeyListener((v, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_BACK
                    && event.getRepeatCount() == 0
                    && popupWindow.get() != null
                    && popupWindow.get().isShowing()) {
                if (callBack != null) {
                    callBack.onCancel();
                }
                safelyDismiss();
            }
            return false;
        });
    }

    public void shareParamsDetail(Activity activity, String url, String icon, String shareTitle, String shareSummary, ShareEntrance shareEntrance, String id) {
        shareParamsDetail(activity, url, icon, shareTitle, shareSummary, shareEntrance, id, null);
    }

    public void shareParamsDetail(Activity activity, String url, String icon, String shareTitle, String shareSummary, ShareEntrance shareEntrance, String id, AdditionalParamsEntity params) {
        if (activity.isFinishing()) return;
        this.mActivity = new WeakReference<>(activity);
        this.shareIcon = getHttpsUrl(icon);
        this.shareUrl = url;
        this.mSummary = shareSummary;
        this.mTitle = shareTitle;
        this.mShareEntrance = shareEntrance;
        ShareUtils.additionalParams = params;
        ShareUtils.shareEntrance = mShareEntrance;
        ShareUtils.resourceId = id;
        ShareUtils.shareEntity = new ShareEntity(shareUrl, mTitle, mSummary);
        LogUtils.uploadShareEnter(mShareEntrance.getName(), shareUrl, mTitle, mSummary, id);
    }


    public void showShareWindows(Activity activity, View view, String url, String icon, String shareTitle, String shareSummary, ShareEntrance shareEntrance, String id) {
        showShareWindowsCallback(activity, view, url, icon, shareTitle, shareSummary, shareEntrance, id, null);
    }

    //QQ分享
    public void qqShare() {
        Utils.toast(mContext, R.string.share_skip);

        mShareType = ShareType.qq;
        shareType = "qq_friend";
        LogUtils.uploadShareType(shareType, shareEntrance.getName(), shareUrl, mTitle, mSummary, resourceId);

        Bundle params = new Bundle();

        switch (mShareEntrance) {
            case plugin:
            case game:
                mTitle += "_要好玩上光环";
                break;
            case askNormal:
            case answerNormal:
            case video:
            case communityArticle:
                mTitle += " - 光环助手";
                break;
        }

        params.putString(QQShare.SHARE_TO_QQ_TITLE, mTitle);
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, mSummary);
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, shareUrl);
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, shareIcon);
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, mContext.getString(R.string.app_name));

        Activity activity = mActivity.get();
        if (activity != null) {
            mTencent.shareToQQ(activity, params, QqShareListener);
        }

        if (mShareEntrance != ShareEntrance.shareGh) {
            safelyDismiss();
        }
    }

    //微信好友分享
    public void wechatShare() {
        Utils.toast(mContext, R.string.share_skip);

        shareType = "wechat_friend";
        mShareType = ShareType.wechat;
        LogUtils.uploadShareType(shareType, shareEntrance.getName(), shareUrl, mTitle, mSummary, resourceId);
        if (!mIWXAPI.isWXAppInstalled() && !PermissionHelper.isGetInstalledListPermissionDisabled(mContext)) {
            Utils.toast(mContext, mContext.getString(R.string.share_no_wechat_hint));
            return;
        }

        WXWebpageObject webpage = new WXWebpageObject();
        WXMediaMessage msg = new WXMediaMessage(webpage);
        webpage.webpageUrl = shareUrl;

        switch (mShareEntrance) {
            case plugin:
            case game:
                mTitle += "_要好玩上光环";
                break;
            case askNormal:
            case answerNormal:
            case video:
            case communityArticle:
                mTitle += " - 光环助手";
                break;

        }

        msg.title = mTitle;
        msg.description = !TextUtils.isEmpty(mSummary) && mSummary.length() > 1024 ? mSummary.substring(0, 1024) : mSummary;

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;

        loadBitmapAndShare(shareIcon, msg, req);
        if (mShareEntrance != ShareEntrance.shareGh) {
            safelyDismiss();
        }
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    private void loadBitmapAndShare(final String iconUrl, final WXMediaMessage msg, final SendMessageToWX.Req req) {
        ImageUtils.getBitmap(iconUrl, new BiCallback<Bitmap, Boolean>() {
            @Override
            public void onFirst(Bitmap bitmap) {
                if (mShareEntrance == ShareEntrance.video) {
                    // 分享类型为视频时裁为正方形
                    int dimension = Math.min(bitmap.getWidth(), bitmap.getHeight());
                    bitmap = ThumbnailUtils.extractThumbnail(bitmap, dimension, dimension);
                }

//                Bitmap compressBp = compressBitmap(bitmap);
                Bitmap compressBp = BitmapUtils.compressBitmap(bitmap, 32);
                if (mShareEntrance == ShareEntrance.askNormal || mShareEntrance == ShareEntrance.askInvite) {
                    msg.thumbData = ImageUtils.bmpToByteArray(compressBp, true);
                } else {
                    Bitmap resultBp = addBackGround(compressBp);
                    msg.thumbData = ImageUtils.bmpToByteArray(resultBp, true);
                }
                mIWXAPI.sendReq(req);
            }

            @Override
            public void onSecond(Boolean aBoolean) {
            }
        });
    }

    //压缩图片
    public static Bitmap compressBitmap(Bitmap bitmap) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        float zoom = (float) Math.sqrt(9 * 1024 / (float) bos.toByteArray().length);

        Matrix matrix = new Matrix();
        matrix.setScale(zoom, zoom);

        Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        bos.reset();

        result.compress(Bitmap.CompressFormat.JPEG, 100, bos);

        while (bos.toByteArray().length > 9 * 1024) {
            System.out.println(bos.toByteArray().length);
            matrix.setScale(0.9f, 0.9f);
            result = Bitmap.createBitmap(result, 0, 0, result.getWidth(), result.getHeight(), matrix, true);
            bos.reset();
            result.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        }

        return result;
    }

    //添加背景，防止图片格式为PNG的图片分享出现黑框问题
    public Bitmap addBackGround(Bitmap result) {
        Bitmap bgBitmap;
        int[] colors = new int[result.getWidth() * result.getHeight()];
        for (int i = 0; i < colors.length; i++) {
            colors[i] = Color.WHITE;
        }
        bgBitmap = Bitmap.createBitmap(colors, result.getWidth(), result.getHeight(), Bitmap.Config.ARGB_8888);

        Bitmap newmap = Bitmap
                .createBitmap(result.getWidth(), result.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newmap);
        canvas.drawBitmap(bgBitmap, 0, 0, null);
//        canvas.drawBitmap(result, (result.getHeight() - result.getWidth()) / 2,
//                (result.getHeight() - result.getWidth()) / 2, null);
        canvas.drawBitmap(result, 0, 0, null);
        canvas.save();
        canvas.restore();

        return newmap;
    }

    //QQ空间分享
    public void qZoneShare() {
        Utils.toast(mContext, R.string.share_skip);

        mShareType = ShareType.qqZone;
        shareType = "qq_zone";
        MtaHelper.onEvent("内容分享", "QQ空间", mTitle);
        LogUtils.uploadShareType(shareType, shareEntrance.getName(), shareUrl, mTitle, mSummary, resourceId);

        Bundle params = new Bundle();

        switch (mShareEntrance) {
            case game:
                mTitle += "_光环助手";
                break;
            case askNormal:
            case answerNormal:
            case video:
            case communityArticle:
                mTitle += " - 光环助手";
                break;
        }

        ArrayList<String> imageUrls = new ArrayList<>();
        imageUrls.add(shareIcon);

        if (!TextUtils.isEmpty(mSummary)) {
            params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, mSummary);
        }
        params.putString(QzoneShare.SHARE_TO_QQ_TITLE, mTitle);
        params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_NO_TYPE);
        params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, shareUrl);
        params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imageUrls);
        params.putString(QzoneShare.SHARE_TO_QQ_APP_NAME, mContext.getString(R.string.app_name));

        Activity activity = mActivity.get();
        if (activity != null) {
            mTencent.shareToQzone(activity, params, QqShareListener);
        }

        if (mShareEntrance != ShareEntrance.shareGh) {
            safelyDismiss();
        }
    }

    //微信朋友圈分享
    public void wechatMomentsShare() {
        Utils.toast(mContext, R.string.share_skip);

        mShareType = ShareType.wechatMoments;
        shareType = "wechat_moment";
        LogUtils.uploadShareType(shareType, shareEntrance.getName(), shareUrl, mTitle, mSummary, resourceId);
        if (!mIWXAPI.isWXAppInstalled() && !PermissionHelper.isGetInstalledListPermissionDisabled(mContext)) {
            Utils.toast(mContext, mContext.getString(R.string.share_no_wechat_hint));
            return;
        }

        WXWebpageObject webpage = new WXWebpageObject();
        WXMediaMessage msg = new WXMediaMessage(webpage);

        webpage.webpageUrl = shareUrl;

        switch (mShareEntrance) {
            case plugin:
            case game:
                msg.title = mTitle + "_要好玩上光环";
                break;
            case askNormal:
            case answerNormal:
            case video:
            case communityArticle:
                msg.title = mTitle + " - 光环助手";
                break;
            default:
                msg.title = mTitle;
                break;
        }


        SendMessageToWX.Req req = new SendMessageToWX.Req();

        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneTimeline;

        loadBitmapAndShare(shareIcon, msg, req);
        if (mShareEntrance != ShareEntrance.shareGh) {
            safelyDismiss();
        }
    }

    //新浪微博分享
    public void sinaWeiboShare() {
        mShareType = ShareType.weibo;
        shareType = "sina_weibo";
        LogUtils.uploadShareType(shareType, shareEntrance.getName(), shareUrl, mTitle, mSummary, resourceId);

        if (mShareEntrance == ShareEntrance.qaDetail) {
            mTitle = "向你推荐：" + mTitle + " @光环助手 " + shareUrl;
            mSummary = "";
        }
        Activity activity = mActivity.get();
        if (activity != null) {
            ARouter.getInstance().build(RouteConsts.activity.weiBoShareActivity)
                    .withString(EntranceConsts.KET_SHARE_STYLE, "NORMAL")
                    .withString(EntranceConsts.KET_TITLE, mTitle)
                    .withString(EntranceConsts.KET_SHAREICON, shareIcon)
                    .withString(EntranceConsts.KET_SUMMARY, mSummary)
                    .withString(EntranceConsts.KET_SHAREURL, shareUrl)
                    .withString(EntranceConsts.KET_TYPE, mShareEntrance.toString())
                    .withFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    .navigation();
        }


        if (mShareEntrance != ShareEntrance.shareGh) {
            safelyDismiss();
        }
    }

    //短信分享
    public void shortMessageShare() {
        mShareType = ShareType.weibo;
        shareType = "sms";
        LogUtils.uploadShareType(shareType, shareEntrance.getName(), shareUrl, mTitle, mSummary, resourceId);

        String smsBody;
        switch (mShareEntrance) {
            case news:
            case tools:
            case web:
                smsBody = mTitle + shareUrl;
                break;
            case plugin:
            case game:
                smsBody = "向你推荐：" + mTitle + "_光环助手：" + shareUrl;
                break;
            case shareGh:
                smsBody = "这个App可以下载各种热门卡牌手游的加速版，绿色安全，超级省心，做日常效率提高3-5倍！光环助手官网地址：" + shareUrl;
                break;
            case askInvite:
            case askNormal:
            case answerNormal:
            case video:
            case communityArticle:
                smsBody = mTitle + " - 光环助手" + shareUrl;
                break;
            case qaDetail:
                smsBody = "向你推荐：" + mTitle + " @光环助手 " + shareUrl;
                break;
            default:
                smsBody = mTitle;
                break;
        }

        try {
            Intent sendIntent = IntentUtils.getSMSIntent(smsBody);
            mContext.startActivity(sendIntent);
        } catch (Exception e) {
            Utils.toast(mContext, "设备短信服务异常，分享失败");
            e.printStackTrace();
        }

        if (mShareEntrance != ShareEntrance.shareGh) {
            safelyDismiss();
        }
    }

    //复制文字链接
    public void copyLink(String copyContent) {
        shareType = "copy_link";
        LogUtils.uploadShareType(shareType, shareEntrance.getName(), shareUrl, mTitle, mSummary, resourceId);
        LogUtils.uploadShareResult(shareType, shareEntrance.getName(), "success", shareUrl, mTitle, mSummary, resourceId);
        if (mShareEntrance != ShareEntrance.shareGh) {
            ExtensionsKt.copyTextAndToast(copyContent, "复制成功");
            safelyDismiss();
        } else {
            ExtensionsKt.copyTextAndToast(copyContent, "复制成功，请到微信/QQ粘贴分享");
        }
    }

    public String getTitle() {
        return mTitle;
    }

    public String getShareUrl() {
        return shareUrl;
    }

    private class ShareRecyclerViewAdapter extends RecyclerView.Adapter<ShareRecyclerViewAdapter.ViewHolder> {

        private OnItemClickListener listener;

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.share_popup_item, parent, false);
            return new ViewHolder(view);
        }

        public void setOnItemClickListener(OnItemClickListener listener) {
            this.listener = listener;
        }

        @Override
        public void onBindViewHolder(final ViewHolder holder, int position) {
            holder.shareLogo.setImageResource(arrLogo[position]);
            holder.shareLabel.setText(arrLabel[position]);
            holder.itemView.setOnClickListener(v -> {
                if (listener != null) {
                    listener.onItemClick(holder.getAdapterPosition());
                }

                switch (holder.getPosition()) {
                    case 0:
                        wechatShare();
                        break;
                    case 1:
                        wechatMomentsShare();
                        break;
                    case 2:
                        qqShare();
                        break;
                    case 3:
                        qZoneShare();
                        break;
                    case 4:
                        sinaWeiboShare();
                        break;
                    case 5:
                        shortMessageShare();
                        break;
                    case 6:
                        shareType = "copy_link";
                        LogUtils.uploadShareType(shareType, shareEntrance.getName(), shareUrl, mTitle, mSummary, resourceId);
                        LogUtils.uploadShareResult(shareType, shareEntrance.getName(), "success", shareUrl, mTitle, mSummary, resourceId);

                        if (mShareEntrance == ShareEntrance.askInvite) {
                            copyLink(mTitle + " - 光环助手" + shareUrl);
                        } else if (mShareEntrance == ShareEntrance.askNormal || mShareEntrance == ShareEntrance.answerNormal) {
                            copyLink(shareUrl);
                        } else if (mShareEntrance != ShareEntrance.shareGh) {
                            copyLink(shareUrl);
                        } else {
                            try {
                                Intent data = IntentUtils.getEmailToGHIntent();
                                mContext.startActivity(data);
                            } catch (Exception e) {
                                e.printStackTrace();
                                Utils.toast(mContext, "设备邮件服务异常，分享失败");
                            }
                        }
                        break;
                    case 7:
                        if (mShareEntrance != ShareEntrance.shareGh) {
                            safelyDismiss();
                        } else {
                            copyLink(shareUrl);
                        }
                        break;
                }
            });
        }

        @Override
        public int getItemCount() {
            return 8;
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            LinearLayout linearLayout;
            TextView shareLabel;
            ImageView shareLogo;

            public ViewHolder(View itemView) {
                super(itemView);
                linearLayout = (LinearLayout) itemView;
                shareLogo = (ImageView) linearLayout.getChildAt(0);
                shareLabel = (TextView) linearLayout.getChildAt(1);
            }
        }
    }

    private void safelyDismiss() {
        if (popupWindow != null && popupWindow.get() != null) {
            popupWindow.get().dismiss();
        }
    }

    private String getHttpsUrl(String url) {
        if (url.startsWith("http://")) {
            return url.replace("http://", "https://");
        }
        return url;
    }

    interface OnItemClickListener {
        void onItemClick(int position);
    }

    public interface ShareCallBack {
        void onSuccess(String label);

        void onCancel();
    }

    private static class SharePopupWindow extends PopupWindow {
        SharePopupWindow(View contentView, int width, int height, boolean focusable) {
            super(contentView, width, height, focusable);
        }

        @Override
        public void dismiss() {
            View backgroundView = getContentView().findViewById(R.id.share_container);
            if (backgroundView != null) {
                backgroundView.setBackgroundColor(Color.TRANSPARENT);
            }
            getContentView().postDelayed(super::dismiss, 0);
        }
    }

}