package com.yidianling.user.ui.login

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Handler
import android.support.v4.content.ContextCompat
import android.text.TextUtils
import android.view.View
import com.ydl.ydlcommon.base.BaseMvpActivity
import com.ydl.ydlcommon.bean.StatusBarOptions
import com.ydl.ydlcommon.utils.ActivityManager
import com.ydl.ydlcommon.utils.StatusBarUtils
import com.ydl.ydlcommon.utils.YDLCacheUtils
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
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.UserHelper
import com.yidianling.user.constants.UserBIConstants
import com.yidianling.user.http.request.BindPhoneJavaParam
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.IVerificationCodeContract
import com.yidianling.user.ui.login.presenter.VerificationCodePresenterImpl
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.user_activity_verification_code.*
import java.util.concurrent.TimeUnit

/**
 * @author jiucheng
 * @描述:验证码页面/忘记密码身份认证页面
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2018/11/29
 */
class VerificationCodeActivity : BaseMvpActivity<IVerificationCodeContract.View,IVerificationCodeContract.Presenter>(), IVerificationCodeContract.View {

    private var codeType = STATUS_LOGIN_BY_CODE//页面状态： 1 忘记密码界面   2验证码登录界面
    private var userPhoneNumber: String? = null
    private var isBindPhone = false
    private var hasPassword = false
    private var countryCode: String? = null
    private var msgCodeDispoable: Disposable? = null

    companion object {
        var STATUS_FORGET_PWD = 1//忘记密码界面
        var STATUS_LOGIN_BY_CODE = 2//验证码登录界面
        private var INTENT_PHONE = "intent_phone"
        private var INTENT_COUNTRY_CODE = "intent_country_code"
        private var INTENT_TYPE = "intent_type"
        private var INTENT_IS_BIND_PHONE = "intent_is_bind_phone"
        private var INTENT_IS_HAS_PWD = "intent_is_has_pwd"


        fun start(activity: Activity, phone: String, countryCode: String, type: Int) {
            start(activity, phone, countryCode, type, false)
        }

        /**
         * @param isBindPhone 是否是绑定手机号
         */
        fun start(activity: Activity, phone: String, countryCode: String, type: Int, isBindPhone: Boolean) {
            if (TextUtils.isEmpty(phone)) {
                ToastUtil.toastShort("手机号不能为空")
                return
            }
            var intent = Intent(activity, VerificationCodeActivity::class.java)
            intent.putExtra(INTENT_PHONE, phone)
            intent.putExtra(INTENT_COUNTRY_CODE, countryCode)
            intent.putExtra(INTENT_TYPE, type)
            intent.putExtra(INTENT_IS_BIND_PHONE, isBindPhone)
            activity.startActivity(intent)
        }

        /**
         * @param isBindPhone 是否是绑定手机号
         * @param hasPassword 是否有密码
         */
        fun start(activity: Activity, phone: String, countryCode: String, type: Int, isBindPhone: Boolean, hasPassword: Boolean) {
            if (TextUtils.isEmpty(phone)) {
                ToastUtil.toastShort("手机号不能为空")
                return
            }
            var intent = Intent(activity, VerificationCodeActivity::class.java)
            intent.putExtra(INTENT_PHONE, phone)
            intent.putExtra(INTENT_COUNTRY_CODE, countryCode)
            intent.putExtra(INTENT_TYPE, type)
            intent.putExtra(INTENT_IS_BIND_PHONE, isBindPhone)
            intent.putExtra(INTENT_IS_HAS_PWD, hasPassword)
            activity.startActivity(intent)
        }
    }

    override fun createPresenter(): IVerificationCodeContract.Presenter {
        return VerificationCodePresenterImpl(this)
    }

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

    override fun initDataAndEvent() {
        setWindowStatusBarColor()
        getIntentData()
        initView()
        setClickEvent()
        sendMsgCode()
        showSoftKeyBord()
    }

    private fun setWindowStatusBarColor() {
        StatusBarUtils.setWindowStatusBarColor(this, R.color.platform_color_075b66)
    }

    private fun getIntentData() {
        codeType = intent.getIntExtra(INTENT_TYPE, 0)
        userPhoneNumber = intent.getStringExtra(INTENT_PHONE)
        countryCode = intent.getStringExtra(INTENT_COUNTRY_CODE)
        isBindPhone = intent.getBooleanExtra(INTENT_IS_BIND_PHONE, false)
        hasPassword = intent.getBooleanExtra(INTENT_IS_HAS_PWD, false)
    }

    private fun initView() {
        when (codeType) {
            STATUS_FORGET_PWD -> {//忘记密码界面
                tv_title.text = "身份认证"
                tv_first.visibility = View.VISIBLE
                tv_passWord.visibility = View.GONE
            }
            STATUS_LOGIN_BY_CODE -> {//验证码登录界面
                if (hasPassword) {
                    tv_passWord.visibility = View.VISIBLE
                } else {
                    tv_passWord.visibility = View.GONE
                }
            }
        }


        if (!TextUtils.isEmpty(userPhoneNumber) && userPhoneNumber!!.length == 11) {
            val sb = StringBuffer(userPhoneNumber)
            sb.insert(3, " ")
            sb.insert(8, " ")
            tv_phone.text = sb.toString()
        } else {
            tv_phone.text = userPhoneNumber
        }

        if (codeType == STATUS_FORGET_PWD) {//忘记密码界面
            tv_title.text = "身份认证"
            tv_first.visibility = View.VISIBLE
            tv_passWord.visibility = View.GONE
        }
    }

    private fun setClickEvent() {
        pc_1.setOnMsgCodeInputCompleteListener {
            login()
        }

        img_goback.setOnClickListener {
            if (ActivityManager.getInstance().getSecondTaskActivity() == null) {
                closeAnim(true)
            } else {
                if (ActivityManager.getInstance().getSecondTaskActivity() is InputPassWordActivity) {
                    closeAnim(false)
                } else {
                    closeAnim(true)
                }
            }
        }
        //下一步
        ver_iv_next.setOnClickListener {

            if (TextUtils.isEmpty(pc_1.phoneCode) || pc_1.phoneCode.length != 4) {
                startAnim()
                return@setOnClickListener
            }
            login()
        }

        //重新发送验证码
        tv_countdown_time.setOnClickListener {
            sendMsgCode()
        }

        tv_passWord.setOnClickListener {


            if (ActivityManager.getInstance().getSecondTaskActivity() == null) {
                closeAnim(true)
            } else {
                if (ActivityManager.getInstance().getSecondTaskActivity() is InputPassWordActivity) {
                    closeAnim(false)
                } else {
                    closeAnim(true)
                }
            }
        }
    }

    private fun showSoftKeyBord() {
        Handler().postDelayed({
            RxKeyboardTool.showKeyboard(this, true)
        }, 300)

    }

    /**
     * 登录
     */
    fun login() {
        val msgCode = pc_1.phoneCode
        if (codeType == STATUS_LOGIN_BY_CODE) {//验证码登录界面
            if (isBindPhone) {
                var param = BindPhoneJavaParam("", countryCode!!, userPhoneNumber!!, msgCode, UserHelper.getUserInfo()!!.uid!!)
                mPresenter.bindPhone(param)
            } else {
                mPresenter.loginByMsgCode(userPhoneNumber!!, countryCode!!, msgCode)
            }
        } else {//忘记密码界面
            mPresenter.checkResetCode(userPhoneNumber!!, countryCode!!, msgCode)
        }
    }


    override fun baiduActionBury() {
        ActionCountUtils.baiduCount(UserBIConstants.APP_REGISTER_PAGE, UserBIConstants.POSITION_CODE_REGISTER_CLICK, 25)
    }

    /**
     *发送验证码
     */
    private fun sendMsgCode() {
        if (codeType == STATUS_LOGIN_BY_CODE) {//验证码登录界面
            //获取上次发送验证码时间
            var lastTimeStr = YDLCacheUtils.getCodeTime(userPhoneNumber!!)
            var duration = (System.currentTimeMillis() - lastTimeStr.toLong()) / 1000
            if (duration > 60) {
                mPresenter.sendLoginCode(userPhoneNumber!!, countryCode!!)
            } else {
                startCountdown(60 - duration.toInt())
            }
        } else {//忘记密码界面
            //获取上次发送验证码时间
            var lastTimeStr = YDLCacheUtils.getResetCodeTime(userPhoneNumber!!)
            var duration = (System.currentTimeMillis() - lastTimeStr.toLong()) / 1000
            if (duration > 60) {
                mPresenter.sendResetCode(userPhoneNumber!!, countryCode!!)
            } else {
                startCountdown(60 - duration.toInt())
            }
        }
    }


    /**
     * 手机号绑定成功
     */
    override fun bindSuccess() {
        UserHelper.getUserInfo()!!.userInfo!!.bind_phone = 1
        UserHelper.getUserInfo()!!.userInfo!!.phone = userPhoneNumber

        closeActivity()
    }

    override fun closeActivity() {
        RxKeyboardTool.hideSoftInput(this)

        LoginUtils.LoginSuccessOperate(this)
    }

    /**
     * 开始倒计时
     */
    @SuppressLint("SetTextI18n")
    override fun startCountdown(remainTime: Int) {
        tv_countdown_time.isEnabled = false
        tv_countdown_time.setTextColor(ContextCompat.getColor(this, R.color.platform_white))

        msgCodeDispoable = Observable.interval(0, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.computation())
                .take(remainTime.toLong())
                .map {
                    (remainTime - it).toString()
                }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    tv_countdown_time.text = it + "s"
                }, {

                }, {
                    tv_countdown_time.isEnabled = true
                    tv_countdown_time.text = "重新发送"
                    tv_countdown_time.setTextColor(ContextCompat.getColor(this, R.color.platform_color_2EB0FF))
                })
    }

    /**
     * 重置密码的验证码校验成功
     */
    override fun checkResetCodeSuccess(code: String) {
        InputPassWordActivity.start(this, userPhoneNumber!!, countryCode!!, InputPassWordActivity.STATUS_SET_PWD, code)
        overridePendingTransition(0, 0)
    }

    /**
     *菊花框
     */
    override fun showLoading(state: Boolean) {
        if (state) {
            ver_iv_next.visibility = View.GONE
            pb_load.visibility = View.VISIBLE
        } else {
            ver_iv_next.visibility = View.VISIBLE
            pb_load.visibility = View.GONE
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (msgCodeDispoable != null) {
            msgCodeDispoable!!.dispose()
        }
    }

    /**
     * 动画
     */
    override fun startAnim() {
//        val shake = AnimationUtils.loadAnimation(this, R.anim.user_shake_input)//加载动画资源文件 
//        pc_1.startAnimation(shake)
        //设置红色边框
        pc_1.setErrorColor()
    }

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