package com.sheep.gamegroup.util.share;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.support.annotation.IntDef;
import android.support.annotation.StringDef;
import android.text.TextUtils;
import android.view.View;

import com.kfzs.duanduan.utils.ApkUtils;
import com.sheep.gamegroup.model.entity.DialogConfig;
import com.sheep.gamegroup.model.entity.FriendAndAwardEntity;
import com.sheep.gamegroup.model.entity.UserEntity;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.StringUtils;
import com.sheep.gamegroup.util.TestUtil;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.util.ZipChannelUtil;
import com.sheep.gamegroup.util.viewHelper.CacheImageUtil;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.FileUtil;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.io.File;
import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Locale;

import rx.functions.Action1;

import static com.sheep.gamegroup.util.UMConfigUtils.Event.LINK_SHARE;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.QR_COPY;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.SHARE_SYS_SEND;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.SHARE_TO_QQ;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.SHARE_TO_QZONE;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.SHARE_TO_WEIXIN_CIRCLE;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.SHARE_TO_WX;
import static com.sheep.jiuyan.samllsheep.utils.ClassFileHelper.DIR;

/**
 * Created by realicing on 2018/11/23.
 * realicing@sina.com
 * 分享配置
 */
public class ShareLinkConfig {
    private String link;
    private String title;
    private String des;
    private String iconUrl;
    private int iconResId;
    private File file;
    private int type = WEB;//分享类型：对应TYPE
    private Action1<View> action1;
    private String shareType = ALL;//分享方式：对应 SHARE_TYPE

    public String getLink() {
        return link;
    }

    public ShareLinkConfig setLink(String link) {
        this.link = link;
        return this;
    }

    public String getTitle() {
        return title;
    }

    public ShareLinkConfig setTitle(String title) {
        this.title = title;
        return this;
    }

    public String getDes() {
        return des;
    }

    public ShareLinkConfig setDes(String des) {
        this.des = des;
        return this;
    }

    public String getIconUrl() {
        return iconUrl;
    }

    public ShareLinkConfig setIconUrl(String iconUrl) {
        this.iconUrl = iconUrl;
        return this;
    }

    public int getIconResId() {
        return iconResId;
    }

    public ShareLinkConfig setIconResId(int iconResId) {
        this.iconResId = iconResId;
        return this;
    }

    public String getShareType() {
        return shareType;
    }

    public ShareLinkConfig setShareType(@ShareLinkConfig.SHARE_TYPE String shareType) {
        this.shareType = shareType;
        return this;
    }

    public File getFile() {
        return file;
    }

    public ShareLinkConfig setFile(File file) {
        this.file = file;
        return this;
    }

    public Action1<View> getAction1() {
        return action1;
    }

    public ShareLinkConfig setAction1(Action1<View> action1) {
        this.action1 = action1;
        return this;
    }

    public int getType() {
        return type;
    }

    public ShareLinkConfig setType(int type) {
        this.type = type;
        return this;
    }

    public void toShare(Activity activity) {
        if(activity instanceof UMShareListener){
            toShare(activity, (UMShareListener) activity);
        } else {
            toShare(activity, null);
        }
    }

    //可以直接分享，也可以弹出分享对话框(ALL, SYS_SEND, FACE_TO_FACE, COPY_SHARE_LINK)
    public void toShare(final Activity activity, final UMShareListener umShareListener) {
        if (activity == null) {
            return;
        }
        if(TextUtils.isEmpty(link)){
            CommonUtil.getInstance().callActionWithUserInfo(new Action1<UserEntity>() {
                @Override
                public void call(UserEntity userEntity) {
                    if (userEntity == null) {
                        G.showToast("分享功能调试中");
                        if(action1 != null)
                            action1.call(null);
                        return;
                    }
                    String url = userEntity.getShareLink();
                    setLink(url).toShare(activity, umShareListener);
                }
            });
            return;
        }
        if(TextUtils.isEmpty(des)){
            CommonUtil.getInstance().callActionWithFriendCountAndAward(new Action1<FriendAndAwardEntity>() {
                @Override
                public void call(FriendAndAwardEntity result) {
                    if (result == null) {
                        G.showToast("分享功能调试中");
                        if(action1 != null)
                            action1.call(null);
                    } else {
                        String desc = result.getShare_desc();
                        setDes(desc).toShare(activity, umShareListener);
                    }
                }
            });
            return;
        }
        if(!TextUtils.isEmpty(iconUrl)){//下载图标后分享,iconUrl只是一个要下载图片的标识，下载成功后要设置为空并且设置其对应的文件，
            String path = CacheImageUtil.getCacheImg(link);
            if(path == null) {
                CacheImageUtil.cacheImg(iconUrl, new Action1<File>() {
                    @Override
                    public void call(File file) {
                        if (file == null) {
                            setIconUrl(null).toShare(activity, umShareListener);
                        } else {
                            setIconUrl(null).setFile(file).toShare(activity, umShareListener);
                        }
                    }
                });
                return;
            } else {
                setFile(new File(path));
            }
        }
        final String realUrl = jointString(link, shareType);
        SHARE_MEDIA share_media;
        switch (shareType) {
            case ShareLinkConfig.ALL:
                ViewUtil.showShareDialog(activity, this, null);
                return;
            case ShareLinkConfig.SYS_SEND:
                SHARE_SYS_SEND.onEvent();
                shareBySysSend(activity);
                return;
            case ShareLinkConfig.FACE_TO_FACE:
                ViewUtil.showQR(activity, realUrl);
                return;
            case ShareLinkConfig.COPY_SHARE_LINK:
                LINK_SHARE.onEvent();
                ViewUtil.showMsgDialog(activity, new DialogConfig().setTitle("分享链接").setMsg(realUrl)
                        .setMsgMore("他人通过该链接加入小绵羊即可成为你的好友").setMsgMoreColor(R.color.txt_black_9e9c9c)
                        .setBtnLeftText("复制链接").setBtnLeftOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                QR_COPY.onEvent();
                                StringUtils.CopyText(realUrl);
                                G.showToast("复制链接成功");
                            }
                        }));
                return;
                //上面为弹出对话框进行分享，下面为直接分享
            case ShareLinkConfig.QQ:
                SHARE_TO_QQ.onEvent();
                share_media = SHARE_MEDIA.QQ;
                break;
            case ShareLinkConfig.QZONE:
                SHARE_TO_QZONE.onEvent();
                share_media = SHARE_MEDIA.QZONE;
                break;
            case ShareLinkConfig.WX:
                SHARE_TO_WX.onEvent();
                share_media = SHARE_MEDIA.WEIXIN;
                break;
            case ShareLinkConfig.WEIXIN_CIRCLE:
            default:
                SHARE_TO_WEIXIN_CIRCLE.onEvent();
                share_media = SHARE_MEDIA.WEIXIN_CIRCLE;
                break;
        }
        String title = activity.getResources().getString(R.string.app_name);
        UMImage umImage;
        UMWeb umWeb;
        if (type == WEB) {
            if(file != null && file.exists()){
                umImage = new UMImage(SheepApp.getInstance(), file);
            } else if(iconResId > 0){
                umImage = new UMImage(SheepApp.getInstance(), iconResId);
            } else {
                umImage = new UMImage(SheepApp.getInstance(), R.mipmap.icon);
            }
            umWeb = new UMWeb(realUrl);
            umWeb.setTitle(title);
            umWeb.setThumb(umImage);
            umWeb.setDescription(TextUtils.isEmpty(des) ? title : des);
            switch (shareType) {
                case ShareLinkConfig.WEIXIN_CIRCLE://微信朋友圈分享时只会显示标题，所以这里使用描述
                    umWeb.setTitle(TextUtils.isEmpty(des) ? title : (title + "\n" + des));
                default:
                    new ShareAction(activity)
                            .setPlatform(share_media)
                            .withMedia(umWeb)
                            .setCallback(umShareListener != null ? umShareListener : new CommonUMShareListener())
                            .share();
                    break;
            }
        } else {
            if(file != null && file.exists()){
                umImage = new UMImage(SheepApp.getInstance(), file);
            } else if(iconResId > 0){
                umImage = new UMImage(SheepApp.getInstance(), iconResId);
            } else {
                if(TestUtil.isDev()){
                    G.showToast("应该是调用方式有问题，请检查一下：分享图片时，file必须保证不为空，且存在");
                } else {
                    G.showToast(R.string.coming_soon);
                }
                return;
            }
            new ShareAction(activity)
                    .setPlatform(share_media)
                    .withMedia(umImage)
                    .setCallback(umShareListener != null ? umShareListener : new CommonUMShareListener())
                    .share();
        }
    }



    public static void shareBySysSend(Activity activity) {
        PackageInfo packageInfo = ApkUtils.getPackageInfo(SheepApp.getInstance().getPackageName());
        if (packageInfo != null && packageInfo.applicationInfo != null && !TextUtils.isEmpty(packageInfo.applicationInfo.sourceDir)) {
            String dir = DIR;
            //File dir = SheepApp.getInstance().getDir("apk", Context.MODE_PRIVATE);
            File file = new File(dir, String.format(Locale.CHINA, "sheep_release_v%s_%d-%s.apk", packageInfo.versionName, packageInfo.versionCode, DataUtil.getInstance().getInvitationCode()));
            if (!file.exists()) {
                try {
                    FileUtil.copyFile(new File(packageInfo.applicationInfo.sourceDir), file);
                    ZipChannelUtil.writeQUA(file, DataUtil.getInstance().getInvitationCode());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (file.exists())
                shareFile(activity, file);
            else
                G.showToast("暂不支持，或未打开权限");
        } else {
            G.showToast("暂不支持");
        }
    }

    // 調用系統方法分享文件
    public static void shareFile(Context context, File file) {
        if (null != file && file.exists()) {
            Intent share = new Intent(Intent.ACTION_SEND);
            share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
            share.setType(getMimeType(file.getAbsolutePath()));//此处可发送多种文件
            share.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            context.startActivity(Intent.createChooser(share, "分享文件"));
        } else {
            G.showToast("分享文件不存在");
        }
    }

    // 根据文件后缀名获得对应的MIME类型。
    private static String getMimeType(String filePath) {
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        String mime = "*/*";
        if (filePath != null) {
            try {
                mmr.setDataSource(filePath);
                mime = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE);
            } catch (IllegalStateException e) {
                return mime;
            } catch (IllegalArgumentException e) {
                return mime;
            } catch (RuntimeException e) {
                return mime;
            }
        }
        return mime;
    }
    /**
     * 分享 url type 拼接
     * 1:微信 2：QQ 3：短信 4：二维码 5:其他
     */
    public static String jointString(String url, @ShareLinkConfig.SHARE_TYPE String type) {
        if (url.contains("&type="))
            return url;
        switch (type) {
            case ShareLinkConfig.WX:
            case ShareLinkConfig.WEIXIN_CIRCLE:
                return url + "&type=1";
            case ShareLinkConfig.QQ:
            case ShareLinkConfig.QZONE:
                return url + "&type=2";
            case ShareLinkConfig.FACE_TO_FACE:
                return url + "&type=4";
            default:
                return url + "&type=5";
        }
    }
    public final static String FACE_TO_FACE = "face_to_face";
    public final static String COPY_SHARE_LINK = "copy_share_link";
    public final static String WEIXIN_CIRCLE = "weixin_circle";
    public final static String QZONE = "qzone";
    public final static String QQ = "qq";
    public final static String WX = "wx";
    public final static String ALL = "all";
    public final static String SYS_SEND = "sys_send";
    public final static String OTHER = "other";

    @StringDef({FACE_TO_FACE, COPY_SHARE_LINK, WEIXIN_CIRCLE, QZONE, QQ, WX, OTHER, SYS_SEND, ALL})
    @Retention(RetentionPolicy.SOURCE)
    public @interface SHARE_TYPE {
    }


    public final static int WEB = 1;//分享网页，
    public final static int IMG = 2;//分享图片，图片对应的是一个文件：file
    @IntDef({WEB, IMG})
    @Retention(RetentionPolicy.SOURCE)
    public @interface TYPE {
    }
}
