package com.yidianling.user.safePrivate

import android.text.TextUtils
import android.widget.TextView
import com.ydl.ydl_image.module.GlideApp
import com.ydl.ydlcommon.base.BaseActivity
import com.ydl.ydlcommon.bean.StatusBarOptions
import com.ydl.ydlcommon.utils.ActivityManager
import com.ydl.ydlcommon.view.CircleImageView
import com.ydl.ydlcommon.view.dialog.CommonDialog
import com.ydl.ydlcommon.view.shoushi.Lock9View
import com.yidianling.common.tools.ToastUtil
import com.yidianling.user.LoginUtils
import com.yidianling.user.R
import com.yidianling.user.UserHelper
import com.yidianling.user.route.UserIn
import com.yidianling.user.ui.login.RegisterAndLoginActivity

/**
 * 手势解锁验证界面(也可验证指纹)
 */
class HandUnlockCheckActivity : BaseActivity(), android.view.View.OnClickListener {
    override fun layoutResId(): Int {
        return R.layout.user_activity_hand_unlock
    }

    override fun getStatusViewOptions(): StatusBarOptions {
        return StatusBarOptions(true,true)
    }

    override fun initDataAndEvent() {
        isFromBackground = intent.getBooleanExtra("isFromBackground", false)

        tipTxt = findViewById<TextView>(R.id.text_tip)

        if (checkoutFingerPrint()) {

        } else {
            if (!isFromBackground) {
                UserIn.splashIntent(this)
            }
            finish()
            return
        }

        //初始化手势解锁
        init()
    }

    //是否来自于后台启动验证
    var isFromBackground = false

    //最多错误次数5次
    var error_num = 5

    var tipTxt: android.widget.TextView? = null

    var lock9: Lock9View? = null

    var isFinger: Boolean = false
    //头像
    var imgHead: CircleImageView? = null
    //忘记手势密码
    var textForget: android.widget.TextView? = null
    //切换登录
    var textLogin: android.widget.TextView? = null


    override fun onResume() {
        super.onResume()
        if (error_num < 1) {
            //错误次数太多 验证账号
            CommonDialog(mContext)
                    .setMessage(FingerPrintUtil.errorLogin)
                    .setRightClick("确定") {
                        //跳转登录
                        RegisterAndLoginActivity.start(this@HandUnlockCheckActivity)
                    }
                    .setCancelAble(false)
                    .show()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    //检查是否开启指纹或手势密码
    private fun checkoutFingerPrint(): Boolean {
        //判断是否有设置指纹或手势解锁
        val finger = FingerPrintUtil.Companion.instance().fingerPrintIsOpen()
        var hand: Boolean = !FingerPrintUtil.Companion.instance().getHandPass().equals("")

        //判断本地是否有uid和acessToken
        if (!UserHelper.isLogin()) {
            return false
        }
        if (finger && hand) {
            //验证指纹与手势同时进行
            //跳转手势解锁界面并监听指纹
            isFinger = true
            return true
        } else if (finger && !hand) {
            //进入指纹解锁界面
            val intent = android.content.Intent(mContext, FingerPrintCheckActivity::class.java)
            intent.putExtra("isFromBackground", isFromBackground)
            startActivity(intent)
            finish()
            return true
        } else return !finger && hand
    }

    fun init() {
        lock9 = findViewById<Lock9View>(R.id.lock9View)
        //头像
        imgHead = findViewById<CircleImageView>(R.id.head_img)
        var head = UserHelper.getUserInfo()?.userInfo?.head
        if (!TextUtils.isEmpty(head)) {
            GlideApp.with(mContext).load(head).into(imgHead)
        }
        //忘记手势密码
        textForget = findViewById<TextView>(R.id.text_forget)
        //切换登录
        textLogin = findViewById<TextView>(R.id.text_login)
        textForget?.setOnClickListener(this)
        textLogin?.setOnClickListener(this)

        //设置正确密码
        lock9?.setSuccessPass(FingerPrintUtil.instance().getHandPass())
        lock9?.setCallBack(object : Lock9View.CallBack {
            override fun onStart() {

            }

            override fun onFinish(password: String) {

                if (password.length < 4) {
                    ToastUtil.toastShort("连接点不能少于4个")
                    return
                }

                var pass: String = FingerPrintUtil.Companion.instance().getHandPass()
                if (pass.equals(password)) {
                    //解锁成功
                    FingerPrintUtil.instance().setCurrentUnLockTime(System.currentTimeMillis())
                    if (!isFromBackground) {
                        UserIn.splashIntent(this@HandUnlockCheckActivity)
                    }
                    finish()
                } else {
                    error_num--
                    if (error_num < 0) {
                        error_num = 0
                    }
                    tipTxt?.setText("手势错误，剩余尝试机会" + error_num + "次")
                    if (error_num < 1) {
                        //错误次数太多 验证账号
                        LoginUtils.logout()
                        FingerPrintUtil.instance().setFingerStatus(false)
                        FingerPrintUtil.instance().setHandPassword("")
                        CommonDialog(mContext)
                                .setMessage(FingerPrintUtil.errorLogin)
                                .setRightClick("确定") {
                                    //跳转登录
                                    ActivityManager.finishAll()
                                    RegisterAndLoginActivity.start(this@HandUnlockCheckActivity)
                                }
                                .setCancelAble(false)
                                .show()
                    }
                }
            }
        })

        if (isFinger) {

            //如果系统指纹功能被关闭（关闭状态下指纹会被清除的），则提示
            if (FingerPrintUtil.instance().isHaveFingerPrint() ?: false == false) {
                //锁屏密码已关闭
                CommonDialog(mContext)
                        .setMessage("\n您的指纹信息发生变更,请在手机中重新添加指纹后返回解锁,或切换登录方式")
                        .setRightClick("确定") {
                        }
                        .setCancelAble(false)
                        .show()
                return
            }

            var dia = CommonDialog(mContext)
                    .setImageCenter(R.drawable.user_lock_ico_zhiwen)
                    .setMessage("验证手机已有指纹")
                    .setLeftOnclick("取消") {
                        //停止指纹监听
                        FingerPrintUtil.instance().cancelFingerListener()
                    }
                    .setCancelAble(false)
            dia?.show()
            //判断系统指纹是否被禁用
            if (!FingerPrintUtil.getFingerPrintIsAviable()) {
                if (dia != null) {
                    dia.setMessage(FingerPrintUtil.errorMoreMessage).setMessageColor(R.color.platform_price_color)
                }
                return
            }

            FingerPrintUtil.Companion.instance().startFingerPrint(object : FingerPrintUtil.FingerCallback {
                override fun onAuthenticationError() {
                    tipTxt?.text = "请使用手势解锁"
                    //关闭指纹监听
                    FingerPrintUtil.instance().cancelFingerListener()//关闭指纹监听
                    if (dia != null) {
                        if (!mContext.isFinishing) {
                            dia.dismiss()
                        }
                    }
                }

                override fun onAuthenticationSucceeded() {
                    //解锁成功
                    FingerPrintUtil.instance().setCurrentUnLockTime(System.currentTimeMillis())
                    if (!isFromBackground) {
                        UserIn.splashIntent(this@HandUnlockCheckActivity)
                    }
                    //关闭手势解锁页面与指纹解锁页面
//                    EventBus.getDefault().post(FinishActivityEvent(FingerPrintCheckActivity::class.simpleName))
//                    EventBus.getDefault().post(FinishActivityEvent(HandUnlockCheckActivity::class.simpleName))
                    if (dia != null) {
                        if (!mContext.isFinishing) {
                            dia.dismiss()
                        }
                        dia = null
                    }
                    finish()
                }

                override fun onAuthenticationFailed() {
                    if (dia != null) {
                        dia.setMessage(FingerPrintUtil.errorMessage).setMessageColor(R.color.platform_price_color)
                        //设置抖动动画
                        dia.setMessageShake(true)
                    }
                }

            })
        }
    }

    override fun onClick(v: android.view.View) {
        when (v.id) {
            R.id.text_forget -> {
                //忘记手势
                CheckPasswordActivity.startActivity(mContext)
//                finish()
            }
            R.id.text_login -> {
                //切换登录
                RegisterAndLoginActivity.start(this)
//                finish()
            }
        }
    }

    override fun onBackPressed() {

    }

}
