package com.zxhl.main.page.activity

import android.text.Editable
import android.text.InputType
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import com.badoo.mobile.util.WeakHandler
import com.zxhl.cms.common.NetConfig
import com.zxhl.cms.common.base.WxImpl
import com.zxhl.cms.router.RounterApi
import com.zxhl.cms.router.RounterBus
import com.zxhl.cms.utils.JumpUtils
import com.zxhl.cms.utils.Utils
import com.zxhl.main.R
import com.zxhl.main.R.id.*
import com.zxhl.main.page.contract.LoginContract
import com.zxhl.main.page.presenter.LoginPresenter
import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.activity_login.*
import java.util.concurrent.TimeUnit

/**
 * Created by gaoleichao on 2018/12/28
 */

class LoginActivity : WxImpl(), LoginContract.View {

    private var TYPE: Int = 0
    private val CODE = 1001
    private val PASSWORD = 1002

    private var mPresenter: LoginContract.Presenter? = null
    private var mHandler: WeakHandler? = null

    private var isWx = false

    private var isStartTimer: Boolean = false
    private var SECONDS: Long = 0

    private var isShowPsw: Boolean = false

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

    override fun init() {
        super.init()
        id_tv_yonghu?.setOnClickListener {
            JumpUtils.webJump("用户协议", NetConfig.H5.WEB_URL_USER)
        }
        id_tv_yinsi?.setOnClickListener {
            JumpUtils.webJump("隐私政策", NetConfig.H5.WEB_URL_PRIVACY)
        }
        TYPE = CODE
        mHandler = WeakHandler()
        mPresenter = LoginPresenter(this)
        id_activity_login_wx?.setOnClickListener(this)
        id_activity_login_switch_type?.setOnClickListener(this)
        id_activity_login_edit_phone_getcode?.setOnClickListener(this)
        id_activity_login_btn?.setOnClickListener(this)
        id_activity_login_edit_password_show?.setOnClickListener(this)
        id_activity_login_forget?.setOnClickListener(this)
        id_activity_login_close?.setOnClickListener(this)
        id_activity_login_edit_phone.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                if (!TextUtils.isEmpty(id_activity_login_edit_phone.text) && !TextUtils.isEmpty(
                        id_activity_login_edit_code.text
                    )
                ) {
                    id_activity_login_btn.setBackgroundResource(R.drawable.shape_3a95fd_r23)
                } else {
                    id_activity_login_btn.setBackgroundResource(R.drawable.shape_login_nomal_bg)
                }
                if (p0?.length == 11) {
                    id_activity_login_edit_phone_getcode?.setTextColor(getResources().getColor(R.color.color_3A95FD))
                }else{
                    id_activity_login_edit_phone_getcode?.setTextColor(getResources().getColor(R.color.color_bbbbbb))
                }
            }

            override fun afterTextChanged(p0: Editable?) {

            }

        })
        id_activity_login_edit_code.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                if (!TextUtils.isEmpty(id_activity_login_edit_phone.text) && !TextUtils.isEmpty(
                        id_activity_login_edit_code.text
                    )
                ) {
                    id_activity_login_btn.setBackgroundResource(R.drawable.shape_3a95fd_r23)
                } else {
                    id_activity_login_btn.setBackgroundResource(R.drawable.shape_login_nomal_bg)
                }
            }

            override fun afterTextChanged(p0: Editable?) {

            }

        })
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.id_activity_login_close -> finish()
            R.id.id_activity_login_wx -> {
                isWx = true
                onWxLogin()
            }
            R.id.id_activity_login_switch_type -> swtichLayout()
            R.id.id_activity_login_edit_phone_getcode -> checkPhone()
            R.id.id_activity_login_btn -> checkNullAndLogin()
            R.id.id_activity_login_edit_password_show -> {
                isShowPsw = !isShowPsw
                switchPsw()
            }
//            R.id.id_activity_login_forget -> openActivity(ForgetPassWordActivity::class.java)
        }
    }

    private fun checkPhone() {
        mLoading.setLoadText(getString(R.string.wait_ing))
        mLoading.show()
        val phone = id_activity_login_edit_phone?.text.toString().trim { it <= ' ' }
        if (phone.length == 11) {
            //            if (PhoneNumUtils.isChinaPhoneLegal(phone) && PhoneNumUtils.isMobile(phone)) {
            mPresenter?.requestCode(phone)
            //            } else {
            //                mLoading.setResult(false, "手机号码错误", 1000);
            //            }

        } else {
            mLoading.setResult(false, "手机号码错误", 1000)
        }
    }

    override fun smsCodeFaild(msg: String) {
        mLoading.setResult(false, msg, 1000)
    }

    override fun loginSuc() {
        mLoading.setResult(true, "登录成功", 1000)
        JumpUtils.activityJump(
            RounterBus.getRounter(RounterApi::class.java).getIntentActivityMain()
        )
        finish()
    }

    override fun smsCodeSuccess() {
        startTimer(60)
        mLoading.setResult(true, getString(R.string.get_sms_code_success), 1000)
    }

    override fun onWxSuccess(token: String, openid: String) {
        isWx = false
        // mPresenter?.wxLogin(token, openid)
    }

    private fun swtichLayout() {
        if (TYPE == CODE) {
            id_activity_login_edit_phone_line?.visibility = View.GONE
            id_activity_login_edit_phone_getcode?.visibility = View.GONE
            id_activity_login_code_layout?.visibility = View.GONE
            id_activity_login_code_line?.visibility = View.GONE
            id_activity_login_password_layout?.visibility = View.VISIBLE
            id_activity_login_password_line?.visibility = View.VISIBLE
            id_activity_login_forget?.visibility = View.VISIBLE
            id_activity_login_switch_type?.text = "免密码登录"
            TYPE = PASSWORD
            switchPsw()
        } else {
            id_activity_login_edit_phone_line?.visibility = View.VISIBLE
            id_activity_login_edit_phone_getcode?.visibility = View.VISIBLE
            id_activity_login_code_layout?.visibility = View.VISIBLE
            id_activity_login_code_line?.visibility = View.VISIBLE
            id_activity_login_password_layout?.visibility = View.GONE
            id_activity_login_password_line?.visibility = View.GONE
            id_activity_login_forget?.visibility = View.GONE
            id_activity_login_switch_type?.text = "密码登录"
            TYPE = CODE
        }
    }

    private fun startTimer(count: Long) {
        isStartTimer = false
        id_activity_login_edit_phone_getcode?.setTextColor(-0x39393a)
        id_activity_login_edit_phone_getcode?.isEnabled = false
        Flowable.intervalRange(0, count, 0, 1, TimeUnit.SECONDS).compose(bindToLifecycle())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnNext { aLong ->
                SECONDS = count - (aLong + 1)
                id_activity_login_edit_phone_getcode?.text = "重新发送(" + SECONDS + "s)"
                if (!isStartTimer) {
                    isStartTimer = true
                }
            }.doOnComplete {
                if (SECONDS == 0L) {
                    isStartTimer = false
                    id_activity_login_edit_phone_getcode?.isEnabled = true
                    id_activity_login_edit_phone_getcode?.setTextColor(-0xe0e0e1)
                    id_activity_login_edit_phone_getcode?.text = "获取验证码"
                }
            }.subscribe()
    }

    override fun onResume() {
        super.onResume()
        if (isStartTimer) {
            startTimer(SECONDS)
        }
        if (isWx) {
            mHandler?.postDelayed({
                if (isWx && mLoading.isShowing) {
                    isWx = false
                    mLoading.setResult(false, "取消登录", 1000)
                }
            }, 2000)
        }
    }

    override fun loginFaild(msg: String) {
        mLoading.setResult(false, msg, 1000)
        //  JumpUtils.homeJump()
    }


    fun oneKeyLogin() {
        mLoading.setLoading(getString(R.string.login_ing))
        mLoading.show()

        //   mPresenter?.oneKeyLogin()
    }

    fun checkNullAndLogin() {
        val phone = id_activity_login_edit_phone?.text.toString().trim { it <= ' ' }
        mLoading.setLoading(getString(R.string.login_ing))
        mLoading.show()
        if (TextUtils.isEmpty(phone)) {
            mLoading.setResult(false, "手机号不能为空", 1000)
            return
        }
        if (TYPE == CODE) {
            val code = id_activity_login_edit_code?.text.toString().trim { it <= ' ' }
            if (TextUtils.isEmpty(code)) {
                mLoading.setResult(false, "验证码不能为空", 1000)
                return
            }
            mPresenter?.codeLogin(phone, code)
        } else {
            val password = id_activity_login_edit_password?.text.toString().trim { it <= ' ' }
            if (TextUtils.isEmpty(password)) {
                mLoading.setResult(false, "密码不能为空", 1000)
                return
            } else if (password.length < 6) {
                mLoading.setResult(false, "密码少于6位", 1000)
                return
            }
//            mPresenter?.passwordLogin(phone, password)
        }
    }

    private fun switchPsw() {
        if (isShowPsw) {
            id_activity_login_edit_password_show?.setBackgroundResource(R.drawable.icon_login_pass_hide)
            id_activity_login_edit_password?.inputType =
                InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD// 输入为密码且可见
        } else {
            id_activity_login_edit_password_show?.setBackgroundResource(R.drawable.icon_login_pass_show)
            id_activity_login_edit_password?.inputType =
                InputType.TYPE_TEXT_VARIATION_PASSWORD or InputType.TYPE_CLASS_TEXT// 设置文本类密码（默认不可见），这两个属性必须同时设置
        }
    }
    private var mPrepareExit = false
    override fun onBackPressed() {
//        super.onBackPressed();
        exitBy2Click()
    }
    private fun exitBy2Click() {
        if (!mPrepareExit) {
            mPrepareExit = true // 准备退出
            Utils.showToast(this, resources.getString(R.string.nav_back_again_finish))
            id_activity_login_btn.postDelayed(Runnable {
                mPrepareExit = false // 取消退出
            }, 1500)
        } else {
            Utils.onExit(this)
        }
    }

}