package com.mints.goodmoney.ui.activitys

import android.Manifest
import android.os.Bundle
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import cn.sharesdk.framework.ShareSDK
import cn.sharesdk.wechat.friends.Wechat
import com.mints.goodmoney.MintsApplication
import com.mints.goodmoney.R
import com.mints.goodmoney.common.Constant
import com.mints.goodmoney.login.LoginApi
import com.mints.goodmoney.login.OnLoginListener
import com.mints.goodmoney.manager.UserManager
import com.mints.goodmoney.mvp.model.WXInfo
import com.mints.goodmoney.mvp.presenters.LoginPresenter
import com.mints.goodmoney.mvp.views.LoginView
import com.mints.goodmoney.ui.activitys.base.BaseActivity
import com.mints.goodmoney.utils.BackInputUtil
import com.mints.goodmoney.utils.LogUtil
import com.mints.library.utils.CommonUtils
import com.mints.library.utils.json.JsonUtil
import com.mints.library.utils.nodoubleclick.AntiShake
import com.tbruyelle.rxpermissions.RxPermissions
import kotlinx.android.synthetic.main.activity_login.*
import net.grandcentrix.tray.AppPreferences
import java.util.*

/**
 * 描述：登录
 * 作者：孟崔广
 * 时间：2020/9/22 13:55
 */
class LoginActivity : BaseActivity()
        , LoginView, View.OnClickListener, OnLoginListener {

    private val loginPresenter by lazy { LoginPresenter() }
    private val loginApi by lazy { LoginApi() }

    private var mobile: String? = null
    private var wxInfo: WXInfo? = null
    private var loginFlag: Boolean = false// false-登录  true-绑定手机号

    override fun getBundleExtras(extras: Bundle?) {
        super.getBundleExtras(extras)
        extras?.let {
            loginFlag = it.getBoolean(Constant.LOGIN_FLAG, false)
        }
    }

    override fun initViewsAndEvents() {
        loginPresenter.attachView(this)

        initView()
        initListener()
    }

    override fun getContentViewLayoutID() = R.layout.activity_login

    override fun toggleOverridePendingTransition() = true

    override fun getOverridePendingTransitionMode() = TransitionMode.BOTTOM

    override fun isApplyKitKatTranslucency() = false

    override fun onDestroy() {
        super.onDestroy()
        loginApi.setOnLoginListener(null)
        loginPresenter.detachView()
    }

    override fun finish() {
        super.finish()
        //关闭窗体动画显示
        overridePendingTransition(0, R.anim.push_bottom_out)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK) {
            val channel = CommonUtils.getAppMetaData(MintsApplication.getContext(), "CHANNEL_NAME")
            if (!TextUtils.equals(channel, Constant.CHANNEL_SHARE)) {
                finish()
            }
            true
        } else super.onKeyDown(keyCode, event)
    }

    override fun onClick(v: View?) {
        if (AntiShake.check(v?.id)) return

        when (v?.id) {
            R.id.ivLoginBack -> {
                val channel = CommonUtils.getAppMetaData(MintsApplication.getContext(), "CHANNEL_NAME")
                if (!TextUtils.equals(channel, Constant.CHANNEL_SHARE)) {
                    finish()
                }
            }
            R.id.tvLoginSendcode -> {
                var mobile = etLoginMobile.getText().toString().trim()
                if (mobile.length < 13) {
                    showToast("请输入手机号")
                    return
                }
                sendCodeThread()

                mobile = mobile.replace(" ".toRegex(), "")
                loginPresenter.sendMobileCode(mobile)
            }
            R.id.tvLoginNext -> {
                var mobile = etLoginMobile.getText().toString().trim()
                if (mobile.length < 13) {
                    showToast("请输入手机号")
                    return
                }

                var code = etLoginCode.getText().toString().trim()
                if (code.length < 4) {
                    showToast("请输入验证码")
                    return
                }


                RxPermissions(this@LoginActivity)
                        .request(Manifest.permission.READ_PHONE_STATE)
                        .subscribe { granted: Boolean ->
                            if (granted) {

                                mobile = mobile.replace(" ".toRegex(), "")
                                if (loginFlag) {
                                    loginPresenter.bindingMobile(mobile, code)
                                } else {
                                    // 登录
                                    loginPresenter.login(mobile, code)
                                }
                            } else {
                                showMissingPermissionDialog("设备")
                            }
                        }
            }
            R.id.tvLoginWx -> {
                val wechat = ShareSDK.getPlatform(Wechat.NAME)
                if (!wechat.isClientValid) {
                    showToast("请先安装微信")
                    return
                }

                RxPermissions(this)
                        .request(Manifest.permission.READ_PHONE_STATE)
                        .subscribe { granted: Boolean ->
                            if (granted) {
                                loginApi.setOnLoginListener(this@LoginActivity)
                                loginApi.setPlatform(Wechat.NAME)
                                loginApi.login(this@LoginActivity)
                            } else {
                                showMissingPermissionDialog("设备")
                            }
                        }
            }
            R.id.tvLoginAgreement -> {
                val bundle = Bundle()
                bundle.putString(WebActivity.WEB_TITLE, getString(R.string.register_name))
                bundle.putString(WebActivity.WEB_URL, Constant.REGISTER_URL)
                readyGo(WebActivity::class.java, bundle)
            }
            R.id.tvLoginPolicy -> {
                val bundle = Bundle()
                bundle.putString(WebActivity.WEB_TITLE, getString(R.string.privacy_name))
                bundle.putString(WebActivity.WEB_URL, Constant.PRIVACY_URL)
                readyGo(WebActivity::class.java, bundle)
            }
        }
    }

    override fun loginSuc() {
        try {
            // 登录成功初始化鱼玩盒子userid
            baseApplication.initYwSdk()
        } catch (e: Exception) {
        }

        // false-登录  true-绑定手机号
        if (loginFlag) {
            showToast("绑定成功")
        } else {
            showToast("登录成功")
        }


        if (progressDialog != null) {
            progressDialog.dismiss()
        }

        val channel = CommonUtils.getAppMetaData(MintsApplication.getContext(), "CHANNEL_NAME")
        if (TextUtils.equals(channel, Constant.CHANNEL_SHARE)) {
            readyGo(MainActivity::class.java)
        }

        finish()
    }

    override fun onLogin(platform: String?, res: HashMap<String, Any>): Boolean {
        try {
            wxInfo = WXInfo()
            wxInfo?.let {
                it.setUnionid(res["unionid"].toString() + "")
                it.setOpenid(res["openid"].toString() + "")
                it.setProvince(res["province"].toString() + "")
                it.setCity(res["city"].toString() + "")
                it.setCountry(res["country"].toString() + "")
                it.setHeadimgurl(res["headimgurl"].toString() + "")
                it.setNickname(res["nickname"].toString() + "")
                it.setSex((res["sex"].toString() + "").toInt())
            }

            if (!isFinishing) {
                loginPresenter.login(JsonUtil.toJson(wxInfo))
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return false
    }

    private fun initView() {
        // false-登录  true-绑定手机号
        if (loginFlag) {
            tvLoginWx.visibility = View.GONE
            tvLoginNext.text = "绑定手机号"
        }

        BackInputUtil.phoneNumAddSpace(etLoginMobile)
        mobile = UserManager.getInstance().mobile
        if (!TextUtils.isEmpty(mobile)) {
            etLoginMobile.setText(mobile)
            etLoginMobile.setSelection(mobile!!.length + 2)
        }
    }

    private fun initListener() {
        ivLoginBack.setOnClickListener(this)
        tvLoginSendcode.setOnClickListener(this)
        tvLoginNext.setOnClickListener(this)
        tvLoginAgreement.setOnClickListener(this)
        tvLoginPolicy.setOnClickListener(this)
        tvLoginWx.setOnClickListener(this)
    }

    var num = 0
    var run: Runnable? = null

    fun sendCodeThread() {
        num = 60
        tvLoginSendcode?.let {
            it.setEnabled(false)
            it.setText("（$num）重新获取")

            run = object : Runnable {
                override fun run() {
                    num--
                    LogUtil.d("login", "login num:" + num)
                    if (num == 0) {
                        it.setText("重新获取")
                        it.setEnabled(true)
                    } else {
                        it.setText("（$num）重新获取")
                        it.postDelayed(this, 1000)
                    }
                }
            }
            it.postDelayed(run, 1000)
        }
    }
}
