package com.zxhl.cms.utils

import android.app.Activity
import android.content.Context
import android.util.Log
import android.widget.Toast
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.UMWeb
import com.zxhl.cms.AppContext
import com.zxhl.cms.R
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


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(): Boolean? {
        ApiClient.homeApi.isWxLogin().compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<IsWeChatLoginEntity>() {
                override fun onSuccess(result: IsWeChatLoginEntity?) {

                    isLogin = result?.status.equals("1")
                    Constant.Switch.isBindLogin = result?.status.equals("1")
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {

                }

            })
        if(Constant.Switch.isBindLogin){
            return true
        }
        return isLogin
    }


    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)
                    Constant.Switch.isBindLogin = true
                    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(), "分享取消")
            }
        }
}