package com.yidianling.user.ui.login

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.text.TextUtils
import android.view.View
import android.view.animation.AnimationUtils
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.core.content.ContextCompat
import com.ydl.ydlcommon.base.BaseMvpActivity
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.ui.login.contract.IVerificationCodeContract
import com.yidianling.user.ui.login.presenter.VerificationCodePresenterImpl
import com.yidianling.user.widget.PinField.HighlightType
import com.yidianling.user.widget.PinField.PinField
import com.yidianling.user.widget.ZDialog
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_new.*
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, View.OnClickListener {

    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
    private var mKeFuDialog: ZDialog? = 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_new
    }

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

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

    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() {
        /*
        * 注册登录改版优化，忘记密码界面和验证码登录界面没有UI区分
        *
        * */
        when (codeType) {
            STATUS_FORGET_PWD -> {//忘记密码界面
//                tv_title.text = "身份认证"
//                tv_first.visibility = View.VISIBLE
//                tv_passWord.visibility = View.GONE
            }
            STATUS_LOGIN_BY_CODE -> {//验证码登录界面
                if (hasPassword) {
                    login_password.visibility = View.VISIBLE
                } else {
                    login_password.visibility = View.GONE
                }
            }
        }
        val splitCountryCode=countryCode?.substring(2)

        if (!TextUtils.isEmpty(userPhoneNumber) && userPhoneNumber!!.length == 11) {
            val sb = StringBuffer(userPhoneNumber)
            sb.insert(3, " ")
            sb.insert(8, " ")
            tv_phone.text = "已发送至 +${splitCountryCode}  $sb"
        } else {
//            tv_phone.text = userPhoneNumber
            tv_phone.text = "已发送至 +${splitCountryCode}  "+userPhoneNumber
        }

        if (codeType == STATUS_FORGET_PWD) {//忘记密码界面
//            tv_title.text = "身份认证"
//            tv_first.visibility = View.VISIBLE
//            tv_passWord.visibility = View.GONE
        }
    }
    fun showSoftKeyboardNew(editText: EditText?) {
        editText?.let {
            it.requestFocus()
            val inputManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            inputManager.showSoftInput(editText, 0)
        }
    }
    private fun setClickEvent() {
        verify_code.onTextCompleteListener=object :PinField.OnTextCompleteListener{
            override fun onTextComplete(enteredText: String): Boolean {
                login()
                return true
            }
        }

        not_get_code.setOnClickListener(this)
        img_reg_back.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()
        }

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



    /**
     * 登录
     */
    fun login() {
        val msgCode = verify_code.text.toString()
        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
        )
    }

    override fun verificationErrorCode() {
        //验证码异常回调
        verify_code.highlightSingleFieldType= HighlightType.ALL_FIELDS
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            verify_code.highlightPaintColor=getColor(R.color.user_bgcolorred)
            verify_code.setText("")
        }
        verify_code.invalidate()
        dismissProgressDialog()
        val shake = AnimationUtils.loadAnimation(this, R.anim.user_shake_input)//加载动画资源文件 
        verify_code.startAnimation(shake)
    }

    /**
     *发送验证码
     */
    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) {
        verify_code.postDelayed({
            showSoftKeyboardNew(verify_code)
        },300)
        tv_countdown_time.isEnabled = false
        tv_countdown_time.setTextColor(ContextCompat.getColor(this, R.color.platform_color_999999))

        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
        }*/
        if (state){
            showProgressDialog()
        }else{
            dismissProgressDialog()
        }
    }

    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)
        //设置红色边框
//        verify_code.setErrorColor()
    }

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

    override fun onClick(v: View?) {
        when(v?.id){
            R.id.not_get_code->{
                showKeFuDialog()
            }
        }
    }

    private fun showKeFuDialog() {
        if (mKeFuDialog == null) {
            mKeFuDialog = ZDialog.Builder(this)
                .setContentView(R.layout.user_kefu_tipdialog)
                .setOnClickListener(R.id.cancel_dialog) {
                    mKeFuDialog?.dismiss()
                    mKeFuDialog=null
                }
                .setAnimation(0)//取消动画
                .setOnClickListener(R.id.dial_right_now) {
                    mKeFuDialog?.dismiss()
                    mKeFuDialog=null
                    val dialIntent =
                        Intent(
                            Intent.ACTION_DIAL,
                            Uri.parse(String.format("tel:" + "400-765-1010"))
                        )
                    startActivity(dialIntent)

                }
                .show()
        }
    }

}
