package com.zxhl.cms.utils

import android.app.Activity
import android.content.Context
import android.util.Log
import android.widget.Toast
import cn.sharesdk.facebook.Facebook
import cn.sharesdk.framework.Platform
import cn.sharesdk.framework.PlatformActionListener
import cn.sharesdk.framework.ShareSDK
import cn.sharesdk.google.GooglePlus
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.zxhl.cms.AppContext
import com.zxhl.cms.common.Constant
import com.zxhl.cms.net.ApiClient
import com.zxhl.cms.net.RxSchedulers
import com.zxhl.cms.net.SettingPreference
import com.zxhl.cms.net.callback.BaseObserver
import com.zxhl.cms.net.model.other.IsWeChatLoginEntity
import com.zxhl.cms.net.model.other.WxBindEntity
import com.zxhl.cms.widget.IsLoginCallBack
import java.util.*


class WeChatUtils {
    private var callBack: WeChatLoginSuccessCallBall

    private var isLogin: Boolean? = false
    private var mContext: Context? = null
    private var lottery: String? = ""

    constructor(context: Context, mCallBack: WeChatLoginSuccessCallBall) : super() {
        mContext = context
        this.callBack = mCallBack

    }

    fun isWechatLogin(callback: IsLoginCallBack<IsWeChatLoginEntity>?) {
        ApiClient.homeApi.isWxLogin().compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<IsWeChatLoginEntity>() {
                override fun onSuccess(result: IsWeChatLoginEntity?) {
                    result?.let {
                      Constant.Switch.isLogin = result.status!="0"
                        callback?.onResult(it)
                    }
//                    isLogin = result?.status.equals("1")
//
//                    Log.e("MXL","isLogin"+isLogin+"status:"+result?.status)
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    callback?.onError(code, errorMsg)
                }

            })

    }


    fun wechatLogin(activity: Activity, str: String) {
        Log.e("MXL", "微信登录")
        lottery = str

//        UMShareAPI.get(activity)
//            .getPlatformInfo(activity, SHARE_MEDIA.WEIXIN, object :
//                UMAuthListener {
//                override fun onStart(share_media: SHARE_MEDIA) {}
//
//                override fun onComplete(
//                    share_media: SHARE_MEDIA,
//                    i: Int,
//                    map: Map<String, String>
//                ) {
//                    val uid = map["uid"]
//                    val access_token = map["access_token"]
//                    val openid = map["openid"] //微博没有
//                    bindWx(access_token.toString(), openid.toString(), str)
//                }
//
//                override fun onError(share_media: SHARE_MEDIA, i: Int, throwable: Throwable) {
//                    Log.e("MXL", "i" + i + throwable.message)
//                    callBack.loginSuccess(lottery)
//                    Toast.makeText(
//                        AppContext.get(),
//                        "登录出错，loading重试" + i + throwable.message,
//                        Toast.LENGTH_SHORT
//                    ).show()
//                }
//
//                override fun onCancel(share_media: SHARE_MEDIA, i: Int) {
//                    callBack.loginSuccess(lottery)
//                    Toast.makeText(AppContext.get(), "登录已取消", Toast.LENGTH_SHORT).show()
//                }
//            })
    }

    fun getShareContent(context: Context?) {
//        ApiClient.userInfoAPi.getWxShare().compose(RxSchedulers.observableIO2Main())
//            .subscribe(object : BaseObserver<ShareEntity>() {
//                override fun onSuccess(result: ShareEntity) {
//                    share(mContext as Activity, result)
//                }
//
//                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
//
//                }
//
//            })
    }

//    fun share(context: Context, result: ShareEntity) {
//        //执行分享操作
//        if (result.type.equals("0")) {
//            val webUrl: UMWeb = UMWeb(result.url)
//            webUrl.description = result.desc
//            webUrl.title = result.title
//            ShareAction(context as Activity)
//                .setPlatform(SHARE_MEDIA.WEIXIN)//传入平台
//                .withText(result.title)
//                .withSubject(result.desc)//分享内容
//                .withMedia(webUrl)
//                // .withMedia(UMImage(activity, bp))
//                .setCallback(shareListener)//回调监听器
//                .share()
//        } else {
//            ShareAction(context as Activity)
//                .setPlatform(SHARE_MEDIA.WEIXIN)//传入平台
//                .withText(result.title + "\n" + result.desc + "\n" + result.url)
//                // .withMedia(UMImage(activity, bp))
//                .setCallback(shareListener)//回调监听器
//                .share()
//        }
//
//    }

    fun bindWx(accesstoken: String, opid: String, str: String) {
        //执行微信绑定
        //成功后调
        ApiClient.homeApi.bindWx(opid, accesstoken)
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<WxBindEntity>() {
                override fun onSuccess(result: WxBindEntity?) {
                    SettingPreference.saveToken(result?.token)
                    Log.e("MXL", "微信登录成功")
                    //  getShareCon tent(mContext)
                    callBack.loginSuccess(lottery)
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    callBack.loginSuccess(lottery)
                }

            })

    }


    fun FackBooklogin() {
        val plat = ShareSDK.getPlatform(Facebook.NAME)
//授权回调监听，监听oncomplete，onerror，oncancel三种状态
        plat.platformActionListener = object : PlatformActionListener {
            override fun onComplete(p0: Platform?, p1: Int, p2: HashMap<String, Any>?) {
                Log.e("MXL", "Data:" + p0?.db?.exportData() + "Image:" + p0?.db?.userIcon)
                bindFaceBookLogin(p0?.db?.userId, p0?.db?.userName, p0?.db?.userIcon)
                EventUtils.onEvent("FackBookloginSuccess")
            }

            override fun onError(arg0: Platform, arg1: Int, arg2: Throwable) {
                //失败的回调，arg:平台对象，arg1:表示当前的动作(8:有用户信息登录, 1:无用户信息登录)，arg2:异常信息
                Log.e("MXL", "FaceBook:onError" + arg2.printStackTrace())
                EventUtils.onEvent("FackBookloginError", "arg1" + arg1 + " arg2" + arg2.message+" arg2:"+arg2.printStackTrace())
            }

            override fun onCancel(arg0: Platform, arg1: Int) {
                //取消分享的回调
                Log.e("MXL", "FaceBook:onCancel")
                EventUtils.onEvent("FackBookloginCancel")

            }
        }
        plat.showUser(null)
    }

    fun bindFaceBookLogin(userId: String?, userName: String?, picture: String?) {
        ApiClient.homeApi.authFaceBookLogin(userId, userName, picture)
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<WxBindEntity>() {
                override fun onSuccess(result: WxBindEntity?) {
                    SettingPreference.saveToken(result?.token)
                    UserDataUtils.updateUserInfo(null)
                    Constant.Switch.isLogin = true
                    Log.e("MXL", "FaceBook登录成功")
                    //  getShareCon tent(mContext)
                    //   callBack.loginSuccess(lottery)
                    callBack.loginSuccess("")
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    //   callBack.loginSuccess(lottery)
                }

            })
    }

    fun GoogleLogin() {
        // MobSDK.submitPolicyGrantResult(true, null)
        val plat = ShareSDK.getPlatform(GooglePlus.NAME)
        ShareSDK.setActivity(mContext as Activity)
//授权回调监听，监听oncomplete，onerror，oncancel三种状态
        plat.platformActionListener = object : PlatformActionListener {
            override fun onComplete(p0: Platform?, p1: Int, p2: HashMap<String, Any>?) {
                Log.e("MXL", "onComplete" + p0?.db?.userIcon + p0?.db?.userId)
                Log.e("MXL", "Data:" + p0?.db?.exportData())
                if (p2 != null) {
                    val g = Gson()
                    val obj: JsonObject = g.fromJson(p0?.db?.exportData(), JsonObject::class.java)
                    Log.e("MXL", "PIC:" + obj.get("picture"))
                    val pic = obj.get("picture").toString().replace("\"", "")
                    Log.e("MXL", "image:" + pic)
                    bindGoogle(p0?.db?.userId, p0?.db?.userName, pic)
                    EventUtils.onEvent("GoogleLoginSuccess")
                }

            }

            override fun onError(arg0: Platform, arg1: Int, arg2: Throwable) {
                //失败的回调，arg:平台对象，arg1:表示当前的动作(8:有用户信息登录, 1:无用户信息登录)，arg2:异常信息
                Log.e("MXL", "onError" + arg2.printStackTrace())
                Log.e("MXL", "onError" + arg2.message)
                EventUtils.onEvent("GoogleLoginError", "arg1" + arg1 + " arg2" + arg2.message+" arg2:"+arg2.printStackTrace())
            }

            override fun onCancel(arg0: Platform, arg1: Int) {
                //取消分享的回调
                Log.e("MXL", "onCancel")
                EventUtils.onEvent("GoogleLoginCancel")

            }
        }
        // plat.authorize()
        plat.showUser(null)

    }

    fun bindGoogle(userId: String?, userName: String?, picture: String?) {
        ApiClient.homeApi.authGoogleLogin(userId, userName, picture)
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<WxBindEntity>() {
                override fun onSuccess(result: WxBindEntity?) {
                    SettingPreference.saveToken(result?.token)
                    UserDataUtils.updateUserInfo(null)
                    Constant.Switch.isLogin = true
                    Log.e("MXL", "谷歌登录成功")
                    //  getShareCon tent(mContext)
                    //   callBack.loginSuccess(lottery)
                    callBack.loginSuccess("")
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    //   callBack.loginSuccess(lottery)
                }

            })

    }
}