package com.yidianling.user.ui.login

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.text.TextUtils
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.R
import com.yidianling.user.constants.UserBIConstants
import com.yidianling.user.route.UserIn
import com.yidianling.user.safePrivate.FingerPrintCheckActivity
import com.yidianling.user.safePrivate.FingerPrintUtil
import com.yidianling.user.safePrivate.HandUnlockCheckActivity
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.*

/**
 * @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
    }

    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.setWindowStatusBarColor(this, R.color.platform_color_075b66)
    }

    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
                input_password.text = "设置新密码"
                tv_phone_num.text = "密码为6-16个字符，数字或英文字母组合"

                //设置密码时默认密码明文显示
                iv_visibility.isSelected = true
                switchPwdShowType()
            }
        }

    }

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


    private fun setClickEvent() {
        input_img_back.setOnClickListener {
            if (ActivityManager.getInstance().getSecondTaskActivity() == null) {
                closeAnim(true)
            } else {
                if (ActivityManager.getInstance().getSecondTaskActivity() is VerificationCodeActivity) {
                    closeAnim(false)
                } else {
                    closeAnim(true)
                }
            }
        }
        input_iv_next.setOnClickListener {
            //下一步
            if (STATUS_INPUT_PWD == codeStatus) {

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

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

        input_iv_del.setOnClickListener {
            et_input_password.setText("")
        }
        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.showKeyboard(this, true)
    }

    /**
     * 密码登录
     */
    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)
            et_input_password.transformationMethod = HideReturnsTransformationMethod.getInstance()
            et_input_password.hint = "当前密码可见"
        } else {
            iv_visibility.setImageResource(R.drawable.user_ic_invisibility)
            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
        }
    }

    /**
     * 校验密码
     */
    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
    }

    override fun startAnim() {
        val shake = AnimationUtils.loadAnimation(this, R.anim.user_shake_input)//加载动画资源文件 
        et_input_password.startAnimation(shake)
        view_input_lin.startAnimation(shake)
        view_input_lin.setBackgroundColor(Color.parseColor("#FB6761"))
    }

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

    override fun closeActivity() {
        RxKeyboardTool.hideSoftInput(this)
        val size = ActivityManager.getActivitySize()
        if (size <= 2) {//当前stack只有两个页面，必然没有MainActivity
            ActivityManager.finishAll()
            startActivity(UserIn.mainIntent(this))
        } else {//需要判断stack中是否有MainActivity
            //这里不能引用到MainActivity 想别的办法
            var flag = 0
            //判断stack中activity是否属于登录相关的三个页面
            for (activity in ActivityManager.getInstance().getActivitys()) {
                if (activity is RegisterAndLoginActivity
                    || activity is VerificationCodeActivity
                    || activity is InputPassWordActivity
                    || activity is FingerPrintCheckActivity
                    || activity is HandUnlockCheckActivity
                ) {
                    flag++
                }
            }
            //flag小于size：则stack中必然有其他的activity
            if (flag < size) {
                ActivityManager.getInstance().finishActivity(VerificationCodeActivity::class.java)
                ActivityManager.getInstance().finishActivity(InputPassWordActivity::class.java)
                ActivityManager.getInstance().finishActivity(RegisterAndLoginActivity::class.java)
                ActivityManager.getInstance().finishActivity(FingerPrintCheckActivity::class.java)
                ActivityManager.getInstance().finishActivity(HandUnlockCheckActivity::class.java)
                FingerPrintUtil.instance().setCurrentUnLockTime(System.currentTimeMillis())
            } else {
                ActivityManager.finishAll()
                startActivity(UserIn.mainIntent(this))
            }
        }
    }

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