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.mob.MobSDK
import com.umeng.socialize.UMAuthListener
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import com.zxhl.cms.AppContext
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 {
                        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(),
                        "登录出错，请稍后重试" + 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)
                }

            })

    }

    private val shareListener: UMShareListener =
        object : UMShareListener {
            /**
             * @descrption 分享开始的回调
             * @param platform 平台类型
             */
            override fun onStart(platform: SHARE_MEDIA) {}

            /**
             * @descrption 分享成功的回调
             * @param platform 平台类型
             */
            override fun onResult(platform: SHARE_MEDIA) {
                //toast吐司
                Toast.makeText(AppContext.get(), "分享成功", Toast.LENGTH_SHORT).show()
            }

            /**
             * @descrption 分享失败的回调
             * @param platform 平台类型
             * @param t 错误原因
             */
            override fun onError(
                platform: SHARE_MEDIA,
                t: Throwable
            ) {
                Toast.makeText(AppContext.get(), "分享失败", Toast.LENGTH_SHORT).show()
            }

            /**
             * @descrption 分享取消的回调
             * @param platform 平台类型
             */
            override fun onCancel(platform: SHARE_MEDIA) {
                Utils.showToast(AppContext.get(), "分享取消")
            }
        }

    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", "FaceBook:onComplete")
            }

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

            override fun onCancel(arg0: Platform, arg1: Int) {
                //取消分享的回调
                Log.e("MXL", "FaceBook:onCancel")
            }
        }
        plat.showUser(null)
    }

    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"))
                    bindGoogle(p0?.db?.userId, p0?.db?.userName, obj.get("picture").toString())
                }

            }

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

            }

            override fun onCancel(arg0: Platform, arg1: Int) {
                //取消分享的回调
                Log.e("MXL", "onCancel")
            }
        }
        // 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)
                    Log.e("MXL", "谷歌登录成功")
                    //  getShareCon tent(mContext)
                    //   callBack.loginSuccess(lottery)
                    callBack.loginSuccess("")
                }

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

            })

    }
}