package com.reactlibrary.uMeng;

import android.Manifest;
import android.content.Intent;
import android.os.Build;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.umeng.socialize.Config;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMMin;
import com.umeng.socialize.media.UMVideo;
import com.umeng.socialize.media.UMWeb;
import com.umeng.socialize.media.UMusic;

import java.util.ArrayList;
import java.util.Map;

import javax.annotation.Nonnull;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

public class UmShare extends ReactContextBaseJavaModule {


    private static ReactApplicationContext reactContext;
    public static UmShare instance;

    @NonNull
    @Override
    public String getName() {
        return "UmShare";
    }


    static public void onActivityResult(int requestCode, int resultCode, Intent data){
        UMShareAPI.get(UmCommon.activity).onActivityResult(requestCode,resultCode,data);
    }

    public UmShare(@Nonnull ReactApplicationContext context) {
        super(context);
        reactContext = context;
        instance = this;


        if (Build.VERSION.SDK_INT >= 23) {
            String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CALL_PHONE, Manifest.permission.READ_LOGS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.SET_DEBUG_APP, Manifest.permission.SYSTEM_ALERT_WINDOW, Manifest.permission.GET_ACCOUNTS, Manifest.permission.WRITE_APN_SETTINGS};
            ActivityCompat.requestPermissions(UmCommon.activity, mPermissionList, 123);
        }
    }


    /*
     * 获取对应的类型，依据的是iOS的类型枚举
     * */
    private SHARE_MEDIA getMediaType(Integer platformType) {
        SHARE_MEDIA type = SHARE_MEDIA.WEIXIN;

        if (platformType == 1) {
            type = SHARE_MEDIA.WEIXIN;
        } else if (platformType == 4) {
            type = SHARE_MEDIA.QQ;
        } else if (platformType == 7) {
            type = SHARE_MEDIA.ALIPAY;
        } else if (platformType == 0) {
            type = SHARE_MEDIA.SINA;
        }
        return type;
    }

    /// 判断 平台是否安装
    /// @param platformType 平台类型
    @ReactMethod
    public void isInstall(int platformType, Promise callback) {
        SHARE_MEDIA type = getMediaType(platformType);

        boolean install = UMShareAPI.get(reactContext).isInstall(UmCommon.activity, type);
        callback.resolve(install);
    }

    /// 初始化分享平台 微信/QQ/新浪
    /// @param data 初始化数据 包含 type:类型  appkey：app的key  appSecret：秘钥  redirectURL：重定向url
    @ReactMethod
    public void initPlaform(ReadableMap data) {
        int type = data.getInt("type");
        String appkey = data.getString("appkey");
        String appSecret = data.getString("appSecret");
        String redirectURL = data.getString("redirectURL");

        if (type == 1) {
            PlatformConfig.setWeixin(appkey, appSecret);
        } else if (type == 4) {
            PlatformConfig.setQQZone(appkey, appSecret);
        } else if (type == 7) {
            PlatformConfig.setAlipay(appkey);
        } else if (type == 0) {
            PlatformConfig.setSinaWeibo(appkey, appSecret, redirectURL);
        }
    }

    /// 第三方平台登录
    /// @param platformType 平台类型
    @ReactMethod
    public void getUserInfoForPlatform(Integer platformType,final Promise callback) {


                SHARE_MEDIA type = getMediaType(platformType);

                UMShareAPI.get(reactContext).getPlatformInfo(UmCommon.activity, type, new UMAuthListener() {
                    @Override
                    public void onStart(SHARE_MEDIA share_media) {
                    }

                    @Override
                    public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                        WritableMap writableMap = Arguments.createMap();
                        for (String key : map.keySet()) {
                            String value = map.get(key);
                            writableMap.putString(key, value);
                        }
                        callback.resolve(writableMap);
                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                        callback.reject("错误", "错误");
                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media, int i) {
                        callback.reject("用户取消", "用户取消");

                    }
                });


    }

    /// 第三方平台 取消授权
    /// @param platformType 平台类型
    @ReactMethod
    public void cancelAuthWithPlatform(Integer platformType,final Promise callback) {
        SHARE_MEDIA type = getMediaType(platformType);

        UMShareAPI.get(reactContext).deleteOauth(UmCommon.activity, type, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {
            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                callback.resolve("成功");
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                callback.reject("错误", "错误");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                callback.reject("用户取消", "用户取消");
            }
        });

    }

    /// 分享文本
    /// @param data 数据
    @ReactMethod
    public void shareText(ReadableMap data,final Promise callback) {
        Integer platformType = data.getInt("platformType");
        String text = data.getString("text");

        new ShareAction(UmCommon.activity).setPlatform(getMediaType(platformType)).withText(text).setCallback(new UMShareListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {
            }

            @Override
            public void onResult(SHARE_MEDIA share_media) {
                callback.resolve("成功");
            }

            @Override
            public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                callback.reject("错误", "错误");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media) {
                callback.reject("用户取消", "用户取消");
            }
        }).share();
    }

    /// 分享图片
    /// @param data 数据
    @ReactMethod
    public void shareImage(ReadableMap data,final Promise callback) {
        Integer platformType = data.getInt("platformType");
        String image = data.getString("image");
        UMImage umImage = new UMImage(reactContext, image);
        UMImage thumb = new UMImage(reactContext, image);
        umImage.setThumb(thumb);

        new ShareAction(UmCommon.activity).setPlatform(getMediaType(platformType)).withMedia(umImage).setCallback(new UMShareListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {
            }

            @Override
            public void onResult(SHARE_MEDIA share_media) {
                callback.resolve("成功");
            }

            @Override
            public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                callback.reject("错误", "错误");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media) {
                callback.reject("用户取消", "用户取消");
            }
        }).share();
    }

    /// 分享网页
    /// @param data 数据
    @ReactMethod
    public void shareWebPage(ReadableMap data,final Promise callback) {
        Integer platformType = data.getInt("platformType");
        String title = data.getString("title");
        String desc = data.getString("desc");
        String icon = data.getString("icon");
        String webpageUrl = data.getString("webpageUrl");

        UMWeb web = new UMWeb(webpageUrl);
        web.setTitle(title);
        web.setThumb(new UMImage(reactContext,icon));
        web.setDescription(desc);

        new ShareAction(UmCommon.activity).setPlatform(getMediaType(platformType)).withMedia(web).setCallback(new UMShareListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) { }

            @Override
            public void onResult(SHARE_MEDIA share_media) {
                callback.resolve("成功");
            }

            @Override
            public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                callback.reject("错误", "错误");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media) {
                callback.reject("用户取消", "用户取消");
            }
        }).share();

    }

    /// 分享音乐
    /// @param data 数据
    @ReactMethod
    public void shareMusic(ReadableMap data,final Promise callback) {
        Integer platformType = data.getInt("platformType");
        String title = data.getString("title");
        String desc = data.getString("desc");
        String icon = data.getString("icon");
        String musicUrl = data.getString("musicUrl");
        String musicDataUrl = data.getString("musicDataUrl");

        UMusic music = new UMusic(musicDataUrl);
        music.setTitle(title);
        music.setThumb(new UMImage(reactContext,icon));
        music.setDescription(desc);
        music.setmTargetUrl(musicUrl);

        new ShareAction(UmCommon.activity).setPlatform(getMediaType(platformType)).withMedia(music).setCallback(new UMShareListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) { }

            @Override
            public void onResult(SHARE_MEDIA share_media) {
                callback.resolve("成功");
            }

            @Override
            public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                callback.reject("错误", "错误");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media) {
                callback.reject("用户取消", "用户取消");
            }
        }).share();
    }


    /// 分享视频
    /// @param data 数据
    @ReactMethod
    public void shareVideo(ReadableMap data,final Promise callback) {
        Integer platformType = data.getInt("platformType");
        String title = data.getString("title");
        String desc = data.getString("desc");
        String icon = data.getString("icon");
        String videoUrl = data.getString("videoUrl");
        String videoStreamUrl = data.getString("videoStreamUrl");

        UMVideo video = new UMVideo(videoUrl);
        video.setTitle(title);
        video.setThumb(new UMImage(reactContext,icon));
        video.setDescription(desc);
        new ShareAction(UmCommon.activity).setPlatform(getMediaType(platformType)).withMedia(video).setCallback(new UMShareListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) { }

            @Override
            public void onResult(SHARE_MEDIA share_media) {
                callback.resolve("成功");
            }

            @Override
            public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                callback.reject("错误", "错误");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media) {
                callback.reject("用户取消", "用户取消");
            }
        }).share();
    }

    /// 分享小程序
    /// @param data 数据
    @ReactMethod
    public void shareMiniProgram(ReadableMap data,final Promise callback) {
        Integer platformType = data.getInt("platformType");
        String title = data.getString("title");
        String desc = data.getString("desc");
        String icon = data.getString("icon");
        String userName = data.getString("userName");
        String path = data.getString("path");
        String hdImage = data.getString("hdImage");
        Integer programType = data.getInt("programType");

        UMMin umMin = new UMMin("");
        umMin.setThumb(new UMImage(reactContext,hdImage));
        umMin.setPath(path);
        umMin.setUserName(userName);
        umMin.setTitle(title);
        umMin.setDescription(desc);
        switch (programType){
            case 0: // 正式版
                break;
            case 1: //  测试版
                Config.setMiniTest();
                break;
            case 2: // 体验版
                Config.setMiniPreView();
                break;
        }

        new ShareAction(UmCommon.activity).setPlatform(getMediaType(platformType)).withMedia(umMin).setCallback(new UMShareListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) { }

            @Override
            public void onResult(SHARE_MEDIA share_media) {
                callback.resolve("成功");
            }

            @Override
            public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                callback.reject("错误", "错误");

            }

            @Override
            public void onCancel(SHARE_MEDIA share_media) {
                callback.reject("用户取消", "用户取消");

            }
        }).share();
    }

}
