package com.gh.common.util;

import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.KeyEvent;
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 com.gh.gamecenter.R;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXWebpageObject;
import com.tencent.mm.sdk.platformtools.Util;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.system.text.ShortMessage;

/**
 * Created by khy on 2016/9/4.
 */
public class ShareUtils {
    private static ShareUtils instance;

    private String shareUrl;
    private String shareGameName;
    private String shareIcon;
    private String shareNewsTitle; // shareNewsTitle不为空就是新闻分享，否则是游戏分享

    private boolean isPlugin = false;

    private static IWXAPI api;
    private static Tencent mTencent;

    private Handler handler;

    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};
    private String[] arrLabel = {"微信好友", "朋友圈", "QQ好友", "QQ空间", "新浪微博", "短信", "复制链接", "取消"};

    private PopupWindow popupWindow;

    private Context context;

    public static ShareUtils getInstance(Context context) {
        if (instance == null) {
            instance = new ShareUtils();
            mTencent = Tencent.createInstance("1104659243", context); //初始化QQ分享
            api = WXAPIFactory.createWXAPI(context, "wx3ffd0785fad18396"); //初始化微信分享
        }
        instance.context = context;
        return instance;
    }

    public void showShareWindows(View view, String url, String gameName, String icon ,String newsTitle, boolean isPlugin){
        this.shareIcon = icon;
        this.shareGameName = gameName;
        this.shareUrl = url;
        this.shareNewsTitle = newsTitle;
        this.isPlugin = isPlugin;

        RelativeLayout contentView = new RelativeLayout(context);
        contentView.setBackgroundColor(0x8c000000);
        contentView.setFocusable(true);
        contentView.setFocusableInTouchMode(true);

        RecyclerView shareRecyclerView = new RecyclerView(context);
        shareRecyclerView.setPadding(DisplayUtils.dip2px(context, 20), DisplayUtils.dip2px(context, 10), DisplayUtils.dip2px(context, 20), 0);
        shareRecyclerView.setBackgroundColor(Color.WHITE);

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

        shareRecyclerView.setLayoutManager(gridLayoutManager);
        shareRecyclerView.setAdapter(new ShareRecyclerViewAdapter());

        RelativeLayout.LayoutParams rlParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT
                , DisplayUtils.dip2px(context, 200));
        rlParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        contentView.addView(shareRecyclerView,rlParams);

        popupWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT
                , LinearLayout.LayoutParams.MATCH_PARENT, true);
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);

        contentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        contentView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {

                if (keyCode == KeyEvent.KEYCODE_BACK
                        && event.getRepeatCount() == 0 && popupWindow != null
                        && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
                return false;
            }
        });
    }

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

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LinearLayout linearLayout = new LinearLayout(context);
            linearLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, DisplayUtils.dip2px(context, 90)));
            linearLayout.setOrientation(LinearLayout.VERTICAL);
            linearLayout.setGravity(Gravity.CENTER_HORIZONTAL);
            linearLayout.setBackgroundResource(R.drawable.cardview_item_style);

            ImageView shareLogo = new ImageView(context);
            LinearLayout.LayoutParams logoParams = new LinearLayout.LayoutParams(DisplayUtils.dip2px(context, 45), DisplayUtils.dip2px(context, 45));
            logoParams.setMargins(0, DisplayUtils.dip2px(context, 10), 0, 0);
            shareLogo.setLayoutParams(logoParams);

            TextView shareLabel = new TextView(context);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins(0, DisplayUtils.dip2px(context,10), 0, 0);
            shareLabel.setLayoutParams(layoutParams);
            shareLabel.setGravity(Gravity.CENTER);
            shareLabel.setTextColor(Color.parseColor("#3a3a3a"));
            shareLabel.setTextSize(13);

            linearLayout.addView(shareLogo);
            linearLayout.addView(shareLabel);

            return new ViewHolder(linearLayout);
        }

        @Override
        public void onBindViewHolder(final ViewHolder holder, int position) {
            holder.shareLogo.setImageResource(arrLogo[position]);
            holder.shareLabel.setText(arrLabel[position]);
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    switch (holder.getPosition()){
                        case 0:
                            wechatSahre();
                            break;
                        case 1:
                            wechatMomentsSahre();
                            break;
                        case 2:
                            qqSahre();
                            break;
                        case 3:
                            qZoneSahre();
                            break;
                        case 4:
                            sinaWeiboSahre();
                            break;
                        case 5:
                            shortMessageSahre();
                            break;
                        case 6:
                            copyLink(shareUrl);
                            break;
                        case 7:
                            popupWindow.dismiss();
                            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);
            }
        }
    }

    //QQ分享
    private void qqSahre(){
        Utils.toast(context,"分享跳转中...");
        Bundle params = new Bundle();

        if (shareNewsTitle != null){
            params.putString(QQShare.SHARE_TO_QQ_TITLE, shareNewsTitle);
            params.putString(QQShare.SHARE_TO_QQ_SUMMARY, "来自光环助手（最强卡牌神器）");
        }else {
            params.putString(QQShare.SHARE_TO_QQ_TITLE, "向你推荐：");
            if (isPlugin){
                params.putString(QQShare.SHARE_TO_QQ_SUMMARY, shareGameName + "（光环加速版）");
            }else {
                params.putString(QQShare.SHARE_TO_QQ_SUMMARY, shareGameName);
            }
        }

        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,  "光环助手");

        mTencent.shareToQQ(
                (Activity) context, params,QqShareListener);
        popupWindow.dismiss();
    }

    //微信好友分享
    private void wechatSahre(){
        Utils.toast(context,"分享跳转中...");
        WXWebpageObject webpage = new WXWebpageObject();
        WXMediaMessage msg = new WXMediaMessage(webpage);
        webpage.webpageUrl = shareUrl;

        if (shareNewsTitle != null){
            msg.title = shareNewsTitle;
            msg.description = "来自光环助手（最强卡牌神器）";
        }else {
            if (isPlugin){
                msg.title = "向你推荐";
                msg.description = shareGameName + "（光环加速版）";
            }else {
                msg.title = "向你推荐";
                msg.description = shareGameName;
            }
        }

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

        loadBitMap(shareIcon, msg, req);
        popupWindow.dismiss();
    }

    //QQ空间分享
    private void qZoneSahre(){
        Utils.toast(context,"分享跳转中...");
        Bundle params = new Bundle();

        if (shareNewsTitle != null){
            params.putString(QzoneShare.SHARE_TO_QQ_TITLE, shareNewsTitle);
        }else {
            params.putString(QzoneShare.SHARE_TO_QQ_TITLE, "向你推荐：");
            if (isPlugin){
                params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, shareGameName + "（光环加速版）");
            }else {
                params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, shareGameName);
            }
        }

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

        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,  "光环助手");

        mTencent.shareToQzone(
                (Activity) context, params,QqShareListener);
        popupWindow.dismiss();
    }

    //微信朋友圈分享
    private void wechatMomentsSahre(){
        Utils.toast(context,"分享跳转中...");
        WXWebpageObject webpage = new WXWebpageObject();
        WXMediaMessage msg = new WXMediaMessage(webpage);

        webpage.webpageUrl = shareUrl;
        if (shareNewsTitle != null){
            msg.title = shareNewsTitle;
        }else {
            if (isPlugin){
                msg.title = "向你推荐：" + shareGameName + "（光环加速版）";
            }else {
                msg.title = "向你推荐：" + shareGameName;
            }
        }

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

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

        loadBitMap(shareIcon, msg, req);
        popupWindow.dismiss();
    }


    //新浪微博分享
    private void sinaWeiboSahre(){
        SinaWeibo.ShareParams sinaWeiboParams =  new SinaWeibo.ShareParams();
        handler = new Handler();

        if (shareNewsTitle != null){
            sinaWeiboParams.setText(shareNewsTitle + " " + shareUrl);
        }else {
            if (isPlugin){
                sinaWeiboParams.setText("向你推荐：" + shareGameName + "（光环加速版） " + shareUrl);
            }else {
                sinaWeiboParams.setText("向你推荐：" + shareGameName + " " + shareUrl);
            }
        }
        sinaWeiboParams.setImageUrl(shareIcon);
        sharePlatform(sinaWeiboParams, SinaWeibo.NAME);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Utils.toast(context, "分享成功");
            }
        }, 3000);
    }

    //短信分享
    private void shortMessageSahre(){
        ShortMessage.ShareParams shortMessageParams =  new ShortMessage.ShareParams();

        if (shareNewsTitle != null){
            shortMessageParams.setText(shareNewsTitle + shareUrl);
        }else {
            if (isPlugin){
                shortMessageParams.setText("向你推荐：" + shareGameName + "（光环加速版）" + shareUrl);
            }else {
                shortMessageParams.setText("向你推荐：" + shareGameName + shareUrl);
            }
        }
        shortMessageParams.setUrl(shareUrl);
        shortMessageParams.setTitleUrl(shareUrl);

        sharePlatform(shortMessageParams, ShortMessage.NAME);
    }

    //分享平台回调
    private void sharePlatform(Platform.ShareParams params, String name) {
        Utils.toast(context,"分享跳转中...");
        Platform platform = ShareSDK.getPlatform(name);
        if (platform.getName().equals(SinaWeibo.NAME)){
            platform.SSOSetting(true);
        }
        platform.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                Utils.log("分享成功");
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                Utils.log("分享失败");
            }

            @Override
            public void onCancel(Platform platform, int i) {
                Utils.log("取消分享");
            }
        });
        platform.share(params);
        popupWindow.dismiss();
    }

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

    //复制文字链接
    private void copyLink(String copyContent) {
        ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        cmb.setText(copyContent);
        popupWindow.dismiss();

        Utils.toast(context,"复制成功");
    }

    private void loadBitMap(final String iconUrl, final WXMediaMessage msg, final SendMessageToWX.Req req){
        ImageUtils.getInstance(context).loadBitmap(iconUrl, new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String s, View view) {

            }

            @Override
            public void onLoadingFailed(String s, View view, FailReason failReason) {

            }

            @Override
            public void onLoadingComplete(String s, View view, Bitmap bitmap) {

                Bitmap compressBp = compressBitmap(bitmap);
                Bitmap resultBp = addBackGround(compressBp);
                msg.thumbData = Util.bmpToByteArray(resultBp, true);
                api.sendReq(req);
            }

            @Override
            public void onLoadingCancelled(String s, View view) {

            }
        });
    }

    //添加背景，防止图片格式为PNG的图片分享出现黑框问题
    private 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.save(Canvas.ALL_SAVE_FLAG);
        canvas.restore();

        return newmap;
    }

    //压缩图片
    private Bitmap compressBitmap(Bitmap bitmap) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 85, bos);
        float zoom = (float) Math.sqrt(10 * 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, 85, bos);

        while(bos.toByteArray().length > 10 * 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, 85, bos);

        }

        return result;
    }

    //QQ或者QQ空间分享回调处理
    public IUiListener QqShareListener = new IUiListener() {
        @Override
        public void onComplete(Object o) {
            Utils.toast(context, "分享成功");
        }

        @Override
        public void onError(UiError uiError) {
            Utils.toast(context, "分享失败");
        }

        @Override
        public void onCancel() {
            Utils.toast(context, "分享已取消");
        }
    };


}
