package com.zj365.dc.activity

import android.content.Intent
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.TextView
import androidx.core.content.ContextCompat
import androidx.lifecycle.MutableLiveData
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.gson.Gson
import com.tamsiree.rxkit.RxActivityTool
import com.tamsiree.rxkit.RxKeyboardTool
import com.xty.base.act.BaseVmAct
import com.xty.common.Const
import com.xty.common.LogUtils
import com.xty.common.MyLinkedMovementMethod
import com.xty.common.TimeSelect
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.util.CommonToastUtils
import com.xty.common.xqr_code.XQRCodeAct

import com.xuexiang.xqrcode.XQRCode
import com.zj365.dc.R
import com.zj365.dc.databinding.ActRegisterBinding
import com.zj365.dc.model.SimpleInfoBean
import com.zj365.dc.vm.RegisterVm
import org.greenrobot.eventbus.EventBus
import java.util.*

/**
 * 注册
 */
@Route(path = ARouterUrl.REGIST_ACT)
class RegisterAct : BaseVmAct<RegisterVm>() {

    val binding by lazy { ActRegisterBinding.inflate(layoutInflater) }
    override fun setLayout() = binding.root

    val timeLive by lazy { MutableLiveData<String>() }
    private var timeNow = Const.timeBack
    private var timer: Timer? = null
    private val USER_AGREEMENT = 10000
    private val PRIVACY = 10001
    private var isAgreement = false
    private var isPrivacy = false
    private var birthdayType = 1
    private val timeSelect by lazy { TimeSelect(this) {} }
    var bean: SimpleInfoBean? = null

    override fun initData() {
        super.initData()
        isDarkBar = true
//        bean=intent.extras!!.getSerializable("bean") as SimpleInfoBean
    }

    override fun initView() {
        super.initView()
        timeSelect.startDate.set(1922, 0, 1)
        getTextWatch(binding.mAccount)
        getTextWatch(binding.mCode)
        getTextWatch(binding.mPsw)
        binding.mRegister.isSelected = false
        binding.mRegister.isEnabled = false
        binding.mTvCode.apply {
            isSelected = true
            setOnClickListener {
                val trim = binding.mAccount.text.toString().trim()
                if (trim.length == 11) {
                    mViewModel.sendCode(trim)
                } else {
                    CommonToastUtils.showToast(R.string.please_input_ok_phone)
                }
            }
        }

        binding.tvReturn.setOnClickListener {
            finish()
        }

        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.mRegister.setOnClickListener {
            RxKeyboardTool.hideSoftInput(this)
            if (!binding.mPrivate.isSelected) {
                CommonToastUtils.showToast(R.string.please_agree_all)
                return@setOnClickListener
            }

            val phone = binding.mAccount.text.toString().trim()
            val code = binding.mCode.text.toString().trim()
            val pwd = binding.mPsw.text.toString().trim()
            mViewModel.register(
                phone,
                code,
                pwd
            )
        }
        binding.mPrivate.setOnClickListener {
            it.isSelected = !it.isSelected
        }
        setPrv()
    }

    /**
     * 隐私条款
     */
    private fun setPrv() {
        var txtCol = ContextCompat.getColor(this, R.color.col_313)
        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@RegisterAct,
                    USER_AGREEMENT,
                    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://auprty.com/app/static/app/privacy.html")
                RouteManager.goActRequest(
                    ARouterUrl.AGREEMNT_READ_WEB_ACT,
                    this@RegisterAct,
                    PRIVACY,
                    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
    }

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

    override fun liveObserver() {
        mViewModel.registerVm.observe(this) {
            CommonToastUtils.showSucceedToast("注册成功")
            if (timer != null) {
                timer!!.cancel()
                timer = null
            }
            mViewModel.login(binding.mAccount.text.toString().trim(),binding.mPsw.text.toString().trim())
            EventBus.getDefault().post(RegisterSuccessEvent())
          //  RxActivityTool.finishActivity(LoginAct::class.java)
        }
        mViewModel.codeLive.observe(this) {
            timeStart()
            binding.mTvCode.apply {
                isEnabled = false
                isSelected = false
            }
        }

        mViewModel.mLogin.observe(this){
4
            RouteManager.goAct(ARouterUrl.BASE_INFO_CHANGE)
            EventBus.getDefault().post(LoginOrRegisterEvent())
            this@RegisterAct.finish()

        }

        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)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            when (requestCode) {
                USER_AGREEMENT -> {
                    isAgreement = true
                    if (!isPrivacy) {
                        bundle.clear()
                        bundle.putString("title", "隐私政策")
                        bundle.putInt("type", Const.AGREEMENT_3)
                        RouteManager.goActRequest(
                            ARouterUrl.RICH_TEXT,
                            this@RegisterAct,
                            PRIVACY,
                            bundle
                        )
                    }
                }

                PRIVACY -> {
                    isPrivacy = true
                    if (!isAgreement) {
                        bundle.clear()
                        bundle.putString("title", "用户协议")
                        bundle.putInt("type", Const.AGREEMENT_1)
                        RouteManager.goActRequest(
                            ARouterUrl.RICH_TEXT,
                            this@RegisterAct,
                            USER_AGREEMENT,
                            bundle
                        )
                    }
                }

                XQRCodeAct.QRCODE_AGREEMENT -> {
                }
            }
        }
    }

    private fun getTextWatch(view: TextView) {
        var watcher = 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?) {
                changeStatus()
            }
        }
        view.setTag(watcher)
        view.addTextChangedListener(watcher)
    }

    fun changeStatus() {
        var phone = binding.mAccount.text.toString().trim()

        var code = binding.mCode.text.toString().trim()

        var pwd = binding.mPsw.text.toString().trim()

        if (phone.isNotEmpty() && code.isNotEmpty() && pwd.isNotEmpty()) {
            binding.mRegister.isSelected = true
            binding.mRegister.isEnabled = true
        } else {
            binding.mRegister.isSelected = false
            binding.mRegister.isEnabled = false
        }
    }

    override fun onStop() {
        super.onStop()
        LogUtils.e("RegisterAct","onStop ${timer}")
        if (timer != null) {
            timer!!.cancel()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        LogUtils.e("RegisterAct","onDestroy  ${timer}")

        if (timer != null) {
            timer!!.cancel()
            timer = null
        }
    }
}