package com.yidianling.user.ui.login

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import androidx.core.content.ContextCompat
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import android.view.animation.AnimationUtils
import com.ydl.ydlcommon.base.BaseMvpActivity
import com.ydl.ydlcommon.utils.ActivityManager
import com.ydl.ydlcommon.utils.StatusBarUtils
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import com.ydl.ydlcommon.view.dialog.CommonDialog
import com.yidianling.common.tools.RxKeyboardTool
import com.yidianling.common.tools.ToastUtil
import com.yidianling.user.LoginUtils
import com.yidianling.user.R
import com.yidianling.user.constants.UserBIConstants
import com.yidianling.user.ui.login.contract.IInputPassWordContract
import com.yidianling.user.ui.login.presenter.InputPassWordPresenterImpl
import kotlinx.android.synthetic.main.user_activity_input_password_new.*

/**
 * @author jiucheng
 * @描述:密码输入页面（设置新密码）
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2018/11/29
 */
class InputPassWordActivity : BaseMvpActivity<IInputPassWordContract.View,IInputPassWordContract.Presenter>(), IInputPassWordContract.View {
    private var userPhoneNumber: String? = null//手机号
    private var countryCode: String? = null//手机号地区区号
    private var msgCode: String? = null//
    private var codeStatus = STATUS_INPUT_PWD//页面状态： STATUS_INPUT_PWD--输入密码  STATUS_SET_PWD--设置密码  默认：输入密码

    companion object {
        var STATUS_INPUT_PWD = 1//输入密码
        var STATUS_SET_PWD = 2//设置密码
        var INTENT_PHONE = "intent_phone"
        var INTENT_CODE_STATUS = "intent_code_status"
        var INTENT_MSG_CODE = "intent_msg_code"
        var INTENT_PHONE_COUNTRY_CODE = "intent_phone_country_code"


        /**
         * 密码登录
         * @param phone 手机号
         * @param countryCode  手机号地区区号
         */
        fun start(activity: Activity, phone: String, countryCode: String, codeStatus: Int) {
            start(activity, phone, countryCode, codeStatus, "")
        }

        /**
         * 重重新设置密码（调用这个方法需要传验证码）
         */
        fun start(
            activity: Activity,
            phone: String,
            countryCode: String,
            codeStatus: Int,
            msgCode: String
        ) {
            if (TextUtils.isEmpty(phone)) {
                ToastUtil.toastShort("手机号不能为空")
                return
            }
            var intent = Intent(activity, InputPassWordActivity::class.java)
            intent.putExtra(INTENT_PHONE, phone)
            intent.putExtra(INTENT_CODE_STATUS, codeStatus)
            intent.putExtra(INTENT_PHONE_COUNTRY_CODE, countryCode)
            intent.putExtra(INTENT_MSG_CODE, msgCode)
            activity.startActivity(intent)
        }

    }

    override fun createPresenter(): IInputPassWordContract.Presenter {
        return InputPassWordPresenterImpl()
    }

    override fun layoutResId(): Int {
        return R.layout.user_activity_input_password_new
    }

    override fun initDataAndEvent() {
        setWindowStatusBarColor()

        userPhoneNumber = intent.getStringExtra(INTENT_PHONE)
        countryCode = intent.getStringExtra(INTENT_PHONE_COUNTRY_CODE)
        msgCode = intent.getStringExtra(INTENT_MSG_CODE)
        codeStatus = intent.getIntExtra(INTENT_CODE_STATUS, STATUS_INPUT_PWD)

        initView()

        setClickEvent()

        showSoftKeyBord()
    }

    private fun setWindowStatusBarColor() {
        StatusBarUtils.Companion.setWindowStatusBarColor(this, R.color.white)
        StatusBarUtils.Companion.setStatusBarLightMode(this, true)
    }

    private fun initView() {
        //初始化：密码显示不可见
        iv_visibility.isSelected = false
        switchPwdShowType()

        when (codeStatus) {
            STATUS_INPUT_PWD -> {//输入密码
                if (!TextUtils.isEmpty(userPhoneNumber) && userPhoneNumber!!.length == 11) {
                    val sb = StringBuffer(userPhoneNumber)
                    sb.insert(3, " ")
                    sb.insert(8, " ")
//                    tv_user_phone.text = sb.toString()
                } else {
//                    tv_user_phone.text = userPhoneNumber
                }
            }
            STATUS_SET_PWD -> {//设置密码
                //设置新密码
                tv_forget.visibility = View.GONE
                tv_msm_login.visibility = View.GONE
//                tv_setPass2.visibility = View.VISIBLE
                tv_password_orSet_title.text = "设置新密码"
                et_input_password.hint = "输入新密码"
                forget_password_hint.visibility = View.VISIBLE
                //设置密码时默认密码明文显示
                iv_visibility.isSelected = true
                login_password.text = "完成"
                switchPwdShowType()
            }
        }

    }

    /**
     * 注册流程成功之后，进行百度埋点
     */
    override fun baiduActionBury() {
        ActionCountUtils.baiduCount(
            UserBIConstants.APP_REGISTER_PAGE,
            UserBIConstants.POSITION_PHONE_REGISTER_CLICK,
            25
        )
    }


    private fun setClickEvent() {
        et_input_password.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                //设置新密码的时候做校验，输入密码不做校验
                if (codeStatus == STATUS_SET_PWD) {
                    if (checkPassWordNoAnim()) {
                        login_password.isEnabled = true
                        login_password.background = ContextCompat.getDrawable(
                            this@InputPassWordActivity,
                            R.drawable.bg_one_click_login
                        )
                    }
                } else {
                    if (s.toString().length >= 6) {
                        login_password.isEnabled = true
                        login_password.background = ContextCompat.getDrawable(
                            this@InputPassWordActivity,
                            R.drawable.bg_one_click_login
                        )
                    } else {
                        login_password.isEnabled = false
                        login_password.background = ContextCompat.getDrawable(
                            this@InputPassWordActivity,
                            R.drawable.login_password_unable_bg_24dp
                        )
                    }

                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

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

        })
        img_reg_back.setOnClickListener {
            if (ActivityManager.getInstance().getSecondTaskActivity() == null) {
                closeAnim(true)
            } else {
                if (ActivityManager.getInstance().getSecondTaskActivity() is VerificationCodeActivity) {
                    closeAnim(false)
                } else {
                    closeAnim(true)
                }
            }
        }
        login_password.setOnClickListener {
            RxKeyboardTool.hideKeyboard(this@InputPassWordActivity,login_password)
            //下一步
            if (STATUS_INPUT_PWD == codeStatus) {

                //密码登录
                userLoginByPassword()
            } else {

                //设置新密码
                if (checkPassWord()) {
                    mPresenter.resetPwd(
                        et_input_password.text.toString(),
                        userPhoneNumber!!,
                        msgCode!!,
                        countryCode!!
                    )
                }
            }
        }

        iv_visibility.setOnClickListener {

            iv_visibility.isSelected = !iv_visibility.isSelected
            //切换密码显示、不显示
            switchPwdShowType()
        }
        tv_msm_login.setOnClickListener {

            //短信登录
            VerificationCodeActivity.start(
                this,
                userPhoneNumber!!,
                countryCode!!,
                VerificationCodeActivity.STATUS_LOGIN_BY_CODE,
                false,
                true
            )
            overridePendingTransition(0, 0)
        }
        tv_forget.setOnClickListener {

            //忘记密码
            VerificationCodeActivity.start(
                this,
                userPhoneNumber!!,
                countryCode!!,
                VerificationCodeActivity.STATUS_FORGET_PWD
            )
            overridePendingTransition(0, 0)
        }
    }


    private fun showSoftKeyBord() {
        RxKeyboardTool.toggleSoftInput(this, et_input_password)

    }

    /**
     * 密码登录
     */
    private fun userLoginByPassword() {
        var pwd = et_input_password.text.toString()
        if (TextUtils.isEmpty(pwd)) {
            ToastUtil.toastShort("请输入密码")
            return
        }
        mPresenter.userLoginByPassword(pwd, userPhoneNumber!!, countryCode!!)
    }

    /**
     * 切换密码显示、不显示
     */
    private fun switchPwdShowType() {
        if (iv_visibility.isSelected) {
            iv_visibility.setImageResource(R.drawable.user_ic_visibility_new)
            et_input_password.transformationMethod = HideReturnsTransformationMethod.getInstance()
            et_input_password.hint = "当前密码可见"
        } else {
            iv_visibility.setImageResource(R.drawable.user_ic_invisibility_new)
            et_input_password.transformationMethod = PasswordTransformationMethod.getInstance()
            et_input_password.hint = "当前密码不可见"
        }

        if (!TextUtils.isEmpty(et_input_password.text.toString())) {
            et_input_password.setSelection(et_input_password.text.toString().length)
        }
    }

    /**
     *菊花框
     */
    override fun showLoading(state: Boolean) {
        /*if (state) {
            input_iv_next.visibility = View.GONE
            input_progressBarNormal.visibility = View.VISIBLE
        } else {
            input_iv_next.visibility = View.VISIBLE
            input_progressBarNormal.visibility = View.GONE
        }*/
        if (state) {
            showProgressDialog()
        } else {
            dismissProgressDialog()
        }
    }

    /**
     * 校验密码
     */
    private fun checkPassWord(): Boolean {
        val regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$"
        val pwd = et_input_password.text.toString()
        if (TextUtils.isEmpty(pwd)) {
            ToastUtil.toastShort("密码不能为空")
            startAnim()
            return false
        }
        if (!pwd.matches(regex.toRegex())) {
            ToastUtil.toastShort("请输入6-16位数字和字母组合密码")
            startAnim()
            return false
        }
        return true
    }

    /**
     * 校验密码
     */
    private fun checkPassWordNoAnim(): Boolean {
        val regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$"
        val pwd = et_input_password.text.toString()
        if (TextUtils.isEmpty(pwd)) {
            return false
        }
        if (!pwd.matches(regex.toRegex())) {
            return false
        }
        return true
    }

    override fun startAnim() {
        val shake = AnimationUtils.loadAnimation(this, R.anim.user_shake_input)//加载动画资源文件 
        et_input_password.startAnimation(shake)
        view_lin.startAnimation(shake)
        view_lin.setBackgroundColor(Color.parseColor("#FB6761"))
        login_password.isEnabled = false
        login_password.background = ContextCompat.getDrawable(
            this@InputPassWordActivity,
            R.drawable.login_password_unable_bg_24dp
        )
    }

    override fun showNormalDialog() {
        CommonDialog.create(this)
            .setMessage("专家账号，请下载壹点灵专家版app喔")
            .setRightClick("确定") {
            }
            .show()
    }

    override fun closeActivity() {

        RxKeyboardTool.hideSoftInput(this)

        LoginUtils.loginSuccessOperate(this)
    }

    private fun closeAnim(hasAnim: Boolean) {
        if (hasAnim) {
            finish()
        } else {
            finish()
            overridePendingTransition(0, 0)
        }
    }
}
