package com.zj365.dc.activity

import android.graphics.Color
import android.text.*
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.text.style.ClickableSpan
import android.view.View
import android.widget.EditText
import androidx.core.content.ContextCompat
import androidx.lifecycle.MutableLiveData
import com.alibaba.android.arouter.facade.annotation.Route
import com.androidkun.xtablayout.XTabLayout
import com.tamsiree.rxkit.RxKeyboardTool
import com.tamsiree.rxkit.RxRegTool
import com.xty.base.act.BaseVmAct
import com.xty.base.dialog.AppUpdateDialog
import com.xty.common.*
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.event.LoginOrRegisterEvent
import com.xty.common.event.RegisterSuccessEvent
import com.xty.common.event.WxLoginEvent
import com.xty.common.util.CommonToastUtils
import com.xty.network.model.WxInfoBean
import com.zj365.dc.databinding.ActLoginBinding
import com.zj365.dc.vm.LoginVm
import com.zj365.health.weight.DialogTip
import com.zj365.health.weight.DialogTipNew
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*

/**
 * 登录页
 */
@Route(path = ARouterUrl.LOGIN_ACT)
class LoginAct : BaseVmAct<LoginVm>() {
    var timer: Timer? = null
    var timeNow = Const.timeBack
    val binding by lazy { ActLoginBinding.inflate(layoutInflater) }
    val timeLive by lazy { MutableLiveData<String>() }
    var wxBean: WxInfoBean? = null

    var tabName = arrayOf("账号密码","验证码")


    val dialogBind by lazy {

        DialogTipNew(this,"温馨提示", "恭喜您成为中健三六五大家庭的一员，为了提供更好的信息服务，请完善您的基本信息。", "前往","取消",false,{
            RouteManager.goAct(ARouterUrl.BASE_INFO_CHANGE)
            EventBus.getDefault().post(LoginOrRegisterEvent())
            finish()
        }){
            EventBus.getDefault().post(LoginOrRegisterEvent())
            finish()
        }
    }
    val dialog by lazy {
        AppUpdateDialog(this){
            if (it){
                finish()
            }
        }
    }

    var isSelectTab = 0 //0 账号密码 1 验证码
    private val USER_AGREEMENT = 10000

    override fun setLayout(): View = binding.root

    override fun initData() {
        super.initData()
        isDarkBar = true
    }

    override fun initView() {
        super.initView()
        binding.mRegister.setOnClickListener {
            RouteManager.goAct(ARouterUrl.REGIST_ACT)
        }
        binding.tvReturn.setOnClickListener {
            finish()
        }

        binding.mLogin.isSelected = true
        binding.mLogin.setOnClickListener {
            RxKeyboardTool.hideSoftInput(this)
            if (!binding.seleck.isSelected) {
                CommonToastUtils.showToast(getString(R.string.please_agree_all))
                return@setOnClickListener
            }
            var phone = binding.mAccount.text.toString()
            if (isSelectTab == 0) {  //密码登陆
                var pwd = binding.mPsw.text.toString()

                mViewModel.login(phone, pwd)
            } else {  //验证码登陆
                var code = binding.mCode.text.toString()

                mViewModel.loginCode(phone, code)
            }

        }
        binding.mTvCode.apply {
            isSelected = true
            setOnClickListener {
                val trim = binding.mAccount.text.toString().trim()
                if (RxRegTool.isMobileSimple(trim)) {
                    mViewModel.sendCode(trim)
                    setErrorMsg("")
                } else {
                    setErrorMsg(getString(R.string.please_input_ok_phone))
                }

            }
        }
        binding.mShow.setOnClickListener {
            if (it.isSelected) {
                binding.mPsw.transformationMethod = PasswordTransformationMethod.getInstance()
            } else {
                binding.mPsw.transformationMethod = HideReturnsTransformationMethod.getInstance();
            }
            it.isSelected = !it.isSelected
            var txtLength = binding.mPsw.text.toString().trim().length

            binding.mPsw.setSelection(txtLength)
        }

        binding.mForget.setOnClickListener {
            bundle.clear()
            bundle.putString("title", "忘记密码")
            RouteManager.goAct(ARouterUrl.CHANGE_PWD)
        }


        initTab()
        setPrv()
        setTextWatcher(binding.mAccount)
        setTextWatcher(binding.mPsw)
        setTextWatcher(binding.mCode)

        mViewModel.getVersionNew()
    }

    /**
     * 隐私条款
     */
    fun setPrv() {
        var txtCol = ContextCompat.getColor(this, R.color.col_313)
        binding.seleck.setOnClickListener {
            it.isSelected = !it.isSelected
        }
        binding.mPrivate.movementMethod = MyLinkedMovementMethod().getInstance()
        var span = SpannableString(getString(R.string.private_info))
        span.setSpan(object : ClickableSpan() {
            override fun onClick(widget: View) {
               /* bundle.clear()
                bundle.putString("title", "用户协议")
                bundle.putInt("type", Const.AGREEMENT_1)
                RouteManager.goActRequest(
                    ARouterUrl.RICH_TEXT,
                    this@LoginAct,
                    USER_AGREEMENT,
                    bundle
                )*/

                bundle.clear()
                bundle.putString("title", "用户协议")
                bundle.putString("url", "https://dc.zhongjian365.com/agreement.html")
                RouteManager.goAct(ARouterUrl.AGREEMNT_READ_WEB_ACT, bundle)
            }

            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.color = txtCol
                ds.isUnderlineText = false
            }
        }, 2, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
        span.setSpan(object : ClickableSpan() {
            override fun onClick(widget: View) {
                bundle.clear()
                bundle.putString("title", "隐私政策")
                bundle.putString("url", "https://dc.zhongjian365.com/privacy.html")
                RouteManager.goAct(ARouterUrl.AGREEMNT_READ_WEB_ACT, bundle)
            }

            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.color = txtCol
                ds.isUnderlineText = false
                ds.clearShadowLayer()

            }
        }, 9, 15, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

        binding.mPrivate.text = span
        binding.mPrivate.highlightColor = Color.TRANSPARENT
    }

    /**
     * 定时器
     */
    fun timeStart() {
        timer = Timer()
        var task = object : TimerTask() {
            override fun run() {
                timeLive.postValue("")
            }
        }
        timer!!.schedule(task, 0, 1000)
    }

    /**
     * 初始化tab
     */
    fun initTab() {

        binding.tabTitle.removeAllTabs()
        tabName.forEach {
            var tab = binding.tabTitle.newTab()
            tab.text = it
            binding.tabTitle.addTab(tab)
        }

        binding.tabTitle.setOnTabSelectedListener(object : XTabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: XTabLayout.Tab?) {
                var filed = tab!!.javaClass.getDeclaredField("mView")
                filed.isAccessible = true
                var tabView = filed.get(tab) as View
                if (tabView.isPressed) {
                    isSelectTab = tab.position
                    if(tab.position == 1){
                        binding.mRelPwd.visibility = View.GONE
                        binding.mRelCode.visibility = View.VISIBLE
                        getNowLoginStatus()
                    }else{
                        binding.mRelPwd.visibility = View.VISIBLE
                        binding.mRelCode.visibility = View.GONE
                        getNowLoginStatus()
                    }
                }
            }

            override fun onTabUnselected(tab: XTabLayout.Tab?) {
            }

            override fun onTabReselected(tab: XTabLayout.Tab?) {
            }

        })
    }

    //添加监听
    fun setTextWatcher(view: EditText) {
        view.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                getNowLoginStatus()
            }
        })
    }

    //判断登陆按钮状态
    fun getNowLoginStatus() {
        var ac = binding.mAccount.text.toString()
        if (isSelectTab == 0) { //密码登陆
            var pwd = binding.mPsw.text.toString()
            binding.mLogin.isSelected = ac.isNotEmpty() && pwd.isNotEmpty()
        } else { //验证码登陆
            var code = binding.mCode.text.toString()
            binding.mLogin.isSelected = ac.isNotEmpty() && code.isNotEmpty()
        }
    }


    override fun liveObserver() {
        mViewModel.mLogin.observe(this) {
            loadingView.dismiss()
            if (it.data.isPerfect == 0){
                dialogBind.setContentNew("恭喜您成为中健三六五大家庭的医院，为了提供更好的信息服务，请完善您的基本信息。")
                dialogBind.show()
            }else{
                EventBus.getDefault().post(LoginOrRegisterEvent())
                finish()
            }
       //     initTab()
//            mViewModel.getImUserSig("user_${it.data.id}")
    //        RouteManager.goAct(ARouterUrl.MAIN_ACT)

        }
//        mViewModel.loginWx.observe(this) {
//            loadingView.dismiss()
//            initTab()
//            mViewModel.getImUserSig("user_${it.data}")
//        }
      /*  mViewModel.setLoginWxId.observe(this) {
            loadingView.dismiss()
            initTab()
            mViewModel.getImUserSig("user_${it}")
        }*/
       /* mViewModel.getImUserSig.observe(this) {
            Log.e("simon", "login"+it.data)
            TUILogin.login(
                applicationContext,
                1400807230,
                it.paramsData,
                it.data,
                object : TUICallback() {
                    override fun onSuccess() {
                        Log.e("simon","onSuccess")
                        RouteManager.goAct(ARouterUrl.MAIN_ACT)
                        finish()
                    }

                    override fun onError(errorCode: Int, errorMessage: String?) {
                        Log.e("simon","onError")
                    }

                })
        }*/

        mViewModel.codeLive.observe(this) {
            timeStart()
            binding.mTvCode.apply {
                isEnabled = false
                isSelected = false
            }
        }
        timeLive.observe(this) {
            --timeNow
            if (timeNow > 0) {
                binding.mTvCode.text = "${timeNow}秒"
            } else {
                timer!!.cancel()
                binding.mTvCode.isSelected = true
                binding.mTvCode.isEnabled = true
                timeNow = Const.timeBack
                binding.mTvCode.text = getString(R.string.get_code)
            }
        }
        mViewModel.wxLoginInfo.observe(this) {
            wxBean = it
            mViewModel.loginWx(it)
        }

        mViewModel.loginWxRegister.observe(this) {
            bundle.clear()
            bundle.putSerializable("bean", wxBean)
            RouteManager.goAct(ARouterUrl.BIND_WX_PHONE, bundle)
        }

        mViewModel.updateLive.observe(this) {
            if (!it.data.url.isNullOrEmpty()) {
                dialog.showUploadDialog(it.data.url!!, it.data.log, it.data.versionName,it.data.isupdate){}
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        timer?.cancel()
    }

    fun setErrorMsg(error: String) {
        if (error.isEmpty()) {
            binding.mError.visibility = View.GONE
        } else {
            binding.mError.visibility = View.VISIBLE
        }
        binding.mError.text = error
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun getWxLoginToken(event: WxLoginEvent) {
        //微信登陆
        mViewModel.getWxLoginInfo(event.code)

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun registerSuccess(event: RegisterSuccessEvent){
        finish()
    }
}