package com.zxhl.main.page.activity

import android.content.Intent
import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.View
import com.zxhl.cms.AppContext
import com.zxhl.cms.common.Constant
import com.zxhl.cms.common.NetConfig
import com.zxhl.cms.common.base.BaseActivity
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.uc.UserInfo
import com.zxhl.cms.router.RounterApi
import com.zxhl.cms.router.RounterBus
import com.zxhl.cms.utils.*
import com.zxhl.cms.widget.LoadingDialog
import com.zxhl.main.R
import kotlinx.android.synthetic.main.activity_layout_login_before.*


class LoginBeforeActivity : BaseActivity() {

    private var googleLogin: GoogleLoginUtil? = null;
    private var faceBookLogin: FaceBookLoginUtil? = null;
    private var mLoading: LoadingDialog? = null

    override fun init() {
        mLoading = LoadingDialog.getLoadingDialog(
            this,
            getString(R.string.wait_ing),
            false,
            false
        )
        //googleLogin init
        googleLogin = GoogleLoginUtil(this)
        googleLogin?.init()
        //FaceBook
        faceBookLogin = FaceBookLoginUtil(this)
        faceBookLogin?.init()



        id_tv_google_login?.setOnClickListener {
            EventUtils.onEvent("googleLoginClick")
            mLoading?.setLoading(getString(R.string.wait_ing))
            mLoading?.show()
            googleLogin?.googleLogin(object : GoogleLoginUtil.LoginCallBack {
                override fun onLoginSuccess() {
                    runOnUiThread {
                        mLoading?.setResult(true, "login success", 0)
                        imLogin()
                    }
                }

                override fun onLoginError(errorMsg: String) {
//                    Log.d("LogonLoginError", errorMsg)
                    EventUtils.onEvent("GoogleLoginError", errorMsg)
                    runOnUiThread {
                        mLoading?.setResult(false, "login error", 1000)
                    }
                }
            })
        }

        id_tv_facebook_login?.setOnClickListener {
            EventUtils.onEvent("facebookLoginClick")
            mLoading?.setLoading(getString(R.string.wait_ing))
            mLoading?.show()
            faceBookLogin?.faceBookLogin(object : FaceBookLoginUtil.LoginCallBack {
                override fun onLoginSuccess() {
                    runOnUiThread {
                        mLoading?.setResult(true, "login success", 0)
                        imLogin()
                    }
                }

                override fun onLoginError(errorMsg: String) {
                    if (errorMsg == "Success_未获取到登录信息") {
                        runOnUiThread {
                            mLoading?.setResult(false, "try again", 1000)
                        }
                    } else {
                        runOnUiThread {
                            mLoading?.setResult(false, "login error", 1000)
                        }
                    }
                    EventUtils.onEvent("facebookLoginError", errorMsg)
//                        Log.e("FaceBookLoginUtil", "error $errorMsg")
                }
            })
        }
        initBottomDesc()
    }

    private fun initBottomDesc() {

        val spannableString =
            SpannableString("By signing up, you confirm that you agree to our Terms of service and have read and understand our Privacy policy. ")
        val userAgreement =
            object : ClickableSpan() {
                override fun onClick(widget: View) {
                    JumpUtils.webJump("Terms Of Service", NetConfig.H5.WEB_URL_USER)
                }

                override fun updateDrawState(ds: TextPaint) {
                    ds.isUnderlineText = false;
                    ds.color = Color.parseColor("#FF772E")
                }
            }
        val privacyPolicy =
            object : ClickableSpan() {
                override fun onClick(widget: View) {
                    JumpUtils.webJump("PrivacyPolicy", NetConfig.H5.WEB_URL_PRIVACY)
                }

                override fun updateDrawState(ds: TextPaint) {
                    ds.isUnderlineText = false;
                    ds.color = Color.parseColor("#FF772E")
                }
            }
//        spannableString.setSpan(tvColor1, 49, 65, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
//        spannableString.setSpan(tvColor2, 99, 114, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        spannableString.setSpan(userAgreement, 49, 65, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        spannableString.setSpan(privacyPolicy, 99, 114, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        id_tv_login_desc.movementMethod = LinkMovementMethod.getInstance()
        // 点击时的背景色
        id_tv_login_desc.highlightColor = Color.parseColor("#00000000");
        id_tv_login_desc.text = spannableString
    }

    override fun before() {
        super.before()
        setStatusBarBackground(AppContext.get().resources.getColor(R.color.transparent))
    }

    override fun onClick(v: View?) {

    }

    override fun layoutID(): Int {
        return R.layout.activity_layout_login_before
    }

    override fun onBackPressed() {
//        super.onBackPressed();
        exitBy2Click()
    }

    private var mPrepareExit = false
    private fun exitBy2Click() {
        if (!mPrepareExit) {
            mPrepareExit = true // 准备退出
            Utils.showToast(this, resources.getString(R.string.nav_back_again_finish))
            id_tv_login_desc.postDelayed(Runnable {
                mPrepareExit = false // 取消退出
            }, 1500)
        } else {
            Utils.onExit(this)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        faceBookLogin?.onActivityResult(requestCode, resultCode, data)
        googleLogin?.onActivityResult(requestCode, resultCode, data)
    }

    private fun imLogin() {
        UserDataUtils.updateUserInfo(AdCallback { _, _ ->
            JumpUtils.activityJump(
                RounterBus.getRounter(RounterApi::class.java).getIntentActivityMain()
            )
            finish()
        })

//        ApiClient.userInfoAPi.deviceLogin().compose(RxSchedulers.observableIO2Main())
//            .subscribe(object : BaseObserver<UserInfo>() {
//                override fun onSuccess(result: UserInfo) {
//                    val token = result.token
//                    SettingPreference.saveToken(token)
//                    UserDataUtils.updateUserInfo(AdCallback { _, _ ->
//                        JumpUtils.activityJump(
//                            RounterBus.getRounter(RounterApi::class.java).getIntentActivityMain()
//                        )
//                        finish()
//                    })
//                }
//
//                override fun onFailure(e: Throwable, code: String, errorMsg: String) {
//                    SettingPreference.saveToken("")
//                    SettingPreference.saveUserInfo(null)
//
//                }
//            })
    }
}