package com.gh.gamecenter;

import static com.gh.gamecenter.common.constant.EntranceConsts.KET_SHAREICON;
import static com.gh.gamecenter.common.constant.EntranceConsts.KET_SHAREURL;
import static com.gh.gamecenter.common.constant.EntranceConsts.KET_SHARE_STYLE;
import static com.gh.gamecenter.common.constant.EntranceConsts.KET_SUMMARY;
import static com.gh.gamecenter.common.constant.EntranceConsts.KET_TITLE;
import static com.gh.gamecenter.common.constant.EntranceConsts.KET_TYPE;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.util.Base64;

import androidx.annotation.NonNull;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.gh.common.constant.Config;
import com.gh.gamecenter.energy.EnergyBridge;
import com.gh.common.util.IntegralLogHelper;
import com.gh.gamecenter.common.callback.BiCallback;
import com.gh.gamecenter.common.constant.RouteConsts;
import com.gh.gamecenter.common.eventbus.EBShare;
import com.gh.gamecenter.common.utils.BitmapUtils;
import com.gh.gamecenter.common.utils.ImageUtils;
import com.gh.gamecenter.common.utils.ShareUtils;
import com.lightgame.utils.Utils;
import com.sina.weibo.sdk.api.ImageObject;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.common.UiError;
import com.sina.weibo.sdk.openapi.IWBAPI;
import com.sina.weibo.sdk.openapi.WBAPIFactory;
import com.sina.weibo.sdk.share.WbShareCallback;

import org.greenrobot.eventbus.EventBus;

import java.io.ByteArrayOutputStream;

/**
 * Created by khy on 2016/11/23.
 * <p>
 * 微博分享
 */
@Route(path = RouteConsts.activity.weiBoShareActivity)
public class WeiBoShareActivity extends Activity implements WbShareCallback {

    private static final String WEIBO_SCOPE = (
            "email,direct_messages_read,direct_messages_write,"
                    + "friendships_groups_read,friendships_groups_write,statuses_to_me_read,"
                    + "follow_app_official_microblog," + "invitation_write");

    private String shareUrl;

    private String mShareStyle;
    private String mTitle;
    private String mSummary;
    private String mShareType;

    private IWBAPI mWBAPI;

    @NonNull
    public static Intent getWeiboShareIntent(Context context, String shareUrl, String shareIcon,
                                             String shareTitle, String shareSummary, String shareType) {
        Intent intent = new Intent(context, WeiBoShareActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(KET_SHARE_STYLE, "NORMAL");
        bundle.putString(KET_TITLE, shareTitle);
        bundle.putString(KET_SHAREICON, shareIcon);
        bundle.putString(KET_SUMMARY, shareSummary);
        bundle.putString(KET_SHAREURL, shareUrl);
        bundle.putString(KET_TYPE, shareType);
        intent.putExtras(bundle);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        return intent;
    }

    // 分享图片专用
    @NonNull
    public static Intent getWeiboImageShareIntent(Context context) {
        Intent intent = new Intent(context, WeiBoShareActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(KET_SHARE_STYLE, "IMAGE");
        intent.putExtras(bundle);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle extras = getIntent().getExtras();

        if (extras == null) return;

        String shareIcon = null;
        mShareStyle = extras.getString(KET_SHARE_STYLE);
        if ("NORMAL".equals(mShareStyle)) {
            mTitle = extras.getString(KET_TITLE);
            shareIcon = extras.getString(KET_SHAREICON);
            mSummary = extras.getString(KET_SUMMARY);
            shareUrl = extras.getString(KET_SHAREURL);
            mShareType = extras.getString(KET_TYPE);
        }

        Utils.toast(this, R.string.share_skip);

        mWBAPI = WBAPIFactory.createWBAPI(this);
        mWBAPI.registerApp(this, new AuthInfo(this, Config.WEIBO_APPKEY, "http://www.sina.com", WEIBO_SCOPE));

        if ("NORMAL".equals(mShareStyle)) {
            if (shareIcon != null) {
                loadIconAndShare(shareIcon);
            } else {
                onError(new UiError(0, "", ""));
            }
        } else if ("IMAGE".equals(mShareStyle)) {
            shareImage();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mWBAPI != null) {
            mWBAPI.doResultIntent(data, this);
        }
    }

    private void loadIconAndShare(String iconUrl) {
        ImageUtils.getBitmap(iconUrl, new BiCallback<Bitmap, Boolean>() {
            @Override
            public void onFirst(Bitmap bitmap) {
                Utils.log("分享获取bitmap成功，准备分享");

                if (ShareUtils.ShareEntrance.video.name().equals(mShareType)) {
                    // 分享类型为视频时裁为正方形
                    int dimension = Math.min(bitmap.getWidth(), bitmap.getHeight());
                    bitmap = ThumbnailUtils.extractThumbnail(bitmap, dimension, dimension);
                }

                Bitmap compressBp = BitmapUtils.compressBitmap(bitmap, 200);
                Bitmap bgBitmap;

                if (ShareUtils.ShareEntrance.askInvite.name().equals(mShareType) || ShareUtils.ShareEntrance.askNormal.name().equals(mShareType)) {
                    bgBitmap = compressBp;
                } else {
                    bgBitmap = ShareUtils.getInstance(getApplicationContext()).addBackGround(compressBp);
                }

                TextObject textObject = new TextObject();

                if (ShareUtils.ShareEntrance.tools.name().equals(mShareType)) {
                    textObject.text = mTitle + "@光环的游戏日常";
                } else if (ShareUtils.ShareEntrance.shareGh.name().equals(mShareType)) {
                    textObject.text = "这个App可以下载各种热门卡牌手游的加速版，绿色安全，超级省心，做日常效率提高3-5倍！不用肝的感觉真好！ @光环的游戏日常";
                } else if (ShareUtils.ShareEntrance.plugin.name().equals(mShareType)
                        || ShareUtils.ShareEntrance.game.name().equals(mShareType)) {
                    textObject.text = "向你推荐：" + mTitle + " @光环的游戏日常 ";
                } else if (ShareUtils.ShareEntrance.video.name().equals(mShareType) ||
                        ShareUtils.ShareEntrance.communityArticle.name().equals(mShareType) ||
                        ShareUtils.ShareEntrance.askNormal.name().equals(mShareType)) {
                    textObject.text = mTitle + shareUrl + "（@光环的游戏日常）";
                } else {
                    textObject.text = mTitle + " @光环的游戏日常 ";
                }

                ImageObject imageObject = new ImageObject();
                imageObject.setImageData(bgBitmap);//设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。

                /*WebpageObject webObject = new WebpageObject();
                webObject.identify = UUID.randomUUID().toString();
                webObject.title = "";
                webObject.description = getString(R.string.app_name);
                webObject.defaultText = getString(R.string.app_name);
                webObject.actionUrl = shareUrl;
                ByteArrayOutputStream os = null;
                try {
                    os = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 85, os);
                    webObject.thumbData = os.toByteArray();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (os != null) {
                            os.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }*/

                WeiboMultiMessage weiboMessage = new WeiboMultiMessage();//初始化微博的分享消息
                weiboMessage.textObject = textObject;
                if (!ShareUtils.ShareEntrance.video.name().equals(mShareType)) {
                    weiboMessage.imageObject = imageObject;
                }
//                weiboMessage.mediaObject = webObject;

                mWBAPI.shareMessage(WeiBoShareActivity.this, weiboMessage, false);
            }

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

    private void shareImage() {
        // base64转bitmap
        byte[] decode = Base64.decode(ImageViewerActivity.base64Image, Base64.DEFAULT);
        Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length);
        // 转完后重新置位
        ImageViewerActivity.base64Image = "";

        Bitmap compressBitmap = compressBitmap(bitmap);
        ImageObject imageObject = new ImageObject();
        imageObject.setImageData(compressBitmap);

        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();//初始化微博的分享消息
        weiboMessage.imageObject = imageObject;

        mWBAPI.shareMessage(WeiBoShareActivity.this, weiboMessage, false);
    }

    public Bitmap compressBitmap(Bitmap bitmap) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        float zoom = (float) Math.sqrt(500 * 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 > 500 * 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;
    }

    @Override
    public void onComplete() {
        Utils.toast(this, R.string.share_success_hint);
        if ("NORMAL".equals(mShareStyle)) {
            com.gh.gamecenter.common.utils.LogUtils.uploadShareResult(ShareUtils.shareType, ShareUtils.shareEntrance.getName(), "success",
                    ShareUtils.shareEntity.getShareUrl(), ShareUtils.shareEntity.getShareTitle(), ShareUtils.shareEntity.getSummary(), ShareUtils.resourceId);
            EventBus.getDefault().post(new EBShare(ShareUtils.shareEntrance));
            EnergyBridge.postEnergyTaskForShare(ShareUtils.shareEntrance.getName(), ShareUtils.resourceId, ShareUtils.shareEntity.getShareUrl());
            if (ShareUtils.shareEntrance == ShareUtils.ShareEntrance.inviteFriends) {
                IntegralLogHelper.INSTANCE.logInviteResult("成功", "微博");
            }
            if (ShareUtils.shareEntrance == ShareUtils.ShareEntrance.askNormal ||
                    ShareUtils.shareEntrance == ShareUtils.ShareEntrance.communityArticle ||
                    ShareUtils.shareEntrance == ShareUtils.ShareEntrance.video) {
                com.gh.gamecenter.common.utils.NewLogUtils.logShareResult(ShareUtils.additionalParams, true);
            } else if (ShareUtils.shareEntrance == ShareUtils.ShareEntrance.gameCollection) {
                com.gh.gamecenter.common.utils.NewLogUtils.logViewOrClickGameCollectionDetail(
                        "click_game_collect_detail_favorite_success",
                        ShareUtils.shareEntity.getShareTitle(),
                        ShareUtils.resourceId,
                        "新浪微博"
                );
            }
        } else {
            IntegralLogHelper.INSTANCE.logInviteResult("成功", "微博");
        }
        finish();
    }

    @Override
    public void onError(UiError uiError) {
        Utils.toast(this, R.string.share_fail_hint);
        if ("NORMAL".equals(mShareStyle)) {
            com.gh.gamecenter.common.utils.LogUtils.uploadShareResult(ShareUtils.shareType, ShareUtils.shareEntrance.getName(), "fail",
                    ShareUtils.shareEntity.getShareUrl(), ShareUtils.shareEntity.getShareTitle(), ShareUtils.shareEntity.getSummary(), ShareUtils.resourceId);
            if (ShareUtils.shareEntrance == ShareUtils.ShareEntrance.inviteFriends) {
                IntegralLogHelper.INSTANCE.logInviteResult("失败", "微博");
            }
            if (ShareUtils.shareEntrance == ShareUtils.ShareEntrance.askNormal ||
                    ShareUtils.shareEntrance == ShareUtils.ShareEntrance.communityArticle ||
                    ShareUtils.shareEntrance == ShareUtils.ShareEntrance.video) {
                com.gh.gamecenter.common.utils.NewLogUtils.logShareResult(ShareUtils.additionalParams, false);
            }
        } else {
            IntegralLogHelper.INSTANCE.logInviteResult("失败", "微博");
        }
        finish();
    }

    @Override
    public void onCancel() {
        Utils.toast(this, R.string.share_cancel_hint);
        if ("NORMAL".equals(mShareStyle)) {
            com.gh.gamecenter.common.utils.LogUtils.uploadShareResult(ShareUtils.shareType, ShareUtils.shareEntrance.getName(), "cancel",
                    ShareUtils.shareEntity.getShareUrl(), ShareUtils.shareEntity.getShareTitle(), ShareUtils.shareEntity.getSummary(), ShareUtils.resourceId);
            if (ShareUtils.shareEntrance == ShareUtils.ShareEntrance.inviteFriends) {
                IntegralLogHelper.INSTANCE.logInviteResult("取消", "微博");
            }
            if (ShareUtils.shareEntrance == ShareUtils.ShareEntrance.askNormal ||
                    ShareUtils.shareEntrance == ShareUtils.ShareEntrance.communityArticle ||
                    ShareUtils.shareEntrance == ShareUtils.ShareEntrance.video) {
                com.gh.gamecenter.common.utils.NewLogUtils.logShareResult(ShareUtils.additionalParams, false);
            }
        } else {
            IntegralLogHelper.INSTANCE.logInviteResult("取消", "微博");
        }
        finish();
    }
}
