package com.zxhl.main.page.activity

import android.text.Editable
import android.text.InputType
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import com.badoo.mobile.util.WeakHandler
import com.tencent.imsdk.v2.*
import com.ym.chat.utils.TUIUtils
import com.zxhl.cms.common.NetConfig
import com.zxhl.cms.common.base.BaseActivity
import com.zxhl.cms.net.SettingPreference
import com.zxhl.cms.router.RounterApi
import com.zxhl.cms.router.RounterBus
import com.zxhl.cms.utils.AdCallback
import com.zxhl.cms.utils.Im.GenerateTestUserSig
import com.zxhl.cms.utils.JumpUtils
import com.zxhl.cms.utils.UserDataUtils
import com.zxhl.cms.utils.Utils
import com.zxhl.main.R
import com.zxhl.main.page.contract.LoginContract
import com.zxhl.main.page.presenter.LoginPresenter
import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.activity_login.*
import java.util.concurrent.TimeUnit

/**
 * Created by gaoleichao on 2018/12/28
 */

class LoginActivity : BaseActivity(), LoginContract.View, AdCallback<String> {

    private var TYPE: Int = 0
    private val CODE = 1001
    private val PASSWORD = 1002

    private var mPresenter: LoginContract.Presenter? = null
    private var mHandler: WeakHandler? = null

    private var isWx = false

    private var isStartTimer: Boolean = false
    private var SECONDS: Long = 0

    private var isShowPsw: Boolean = false

    override fun layoutID(): Int {
        return R.layout.activity_login
    }
        var ifchoose:Boolean=false
    override fun init() {
        id_tv_yonghu?.setOnClickListener {
            JumpUtils.webJump(R.string.UserAgreement.toString(), NetConfig.H5.WEB_URL_USER)
        }
        id_tv_yinsi?.setOnClickListener {
            JumpUtils.webJump("隐私政策", NetConfig.H5.WEB_URL_PRIVACY)
        }
        id_img_xuanzhong?.setOnClickListener {
            if(!ifchoose){
                ifchoose=true
                id_img_xuanzhong?.setImageResource(R.drawable.icon_xuanzhong_zise)
            }else{
                ifchoose=false
                id_img_xuanzhong?.setImageResource(R.drawable.icon_weixuan_zise)
            }
        }
        TYPE = CODE
        mHandler = WeakHandler()
        mPresenter = LoginPresenter(this)
        id_activity_login_wx?.setOnClickListener(this)
        id_activity_login_switch_type?.setOnClickListener(this)
        id_activity_login_edit_phone_getcode?.setOnClickListener(this)
        id_activity_login_btn?.setOnClickListener(this)
        id_activity_login_edit_password_show?.setOnClickListener(this)
        id_activity_login_forget?.setOnClickListener(this)
        id_activity_login_close?.setOnClickListener(this)
        id_activity_login_edit_phone.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                if (!TextUtils.isEmpty(id_activity_login_edit_phone.text) && !TextUtils.isEmpty(
                        id_activity_login_edit_code.text
                    )
                ) {
                    id_activity_login_btn.setBackgroundResource(R.drawable.shape_7a9cff_ae71dd_r25)
                } else {
                    id_activity_login_btn.setBackgroundResource(R.drawable.shape_login_nomal_bg)
                }
                if (p0?.length == 11) {
                    id_activity_login_edit_phone_getcode?.setTextColor(getResources().getColor(R.color.color_3A95FD))
                } else {
                    id_activity_login_edit_phone_getcode?.setTextColor(getResources().getColor(R.color.color_bbbbbb))
                }
            }

            override fun afterTextChanged(p0: Editable?) {

            }

        })
        id_activity_login_edit_code.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                if (!TextUtils.isEmpty(id_activity_login_edit_phone.text) && !TextUtils.isEmpty(
                        id_activity_login_edit_code.text
                    )
                ) {
                    id_activity_login_btn.setBackgroundResource(R.drawable.shape_7a9cff_ae71dd_r25)
                } else {
                    id_activity_login_btn.setBackgroundResource(R.drawable.shape_login_nomal_bg)
                }
            }

            override fun afterTextChanged(p0: Editable?) {

            }

        })
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.id_activity_login_close -> finish()
            R.id.id_activity_login_wx -> {
                isWx = true
            }
            R.id.id_activity_login_switch_type -> swtichLayout()
            R.id.id_activity_login_edit_phone_getcode -> checkPhone()
            R.id.id_activity_login_btn -> checkNullAndLogin()
            R.id.id_activity_login_edit_password_show -> {
                isShowPsw = !isShowPsw
                switchPsw()
            }
//            R.id.id_activity_login_forget -> openActivity(ForgetPassWordActivity::class.java)
        }
    }

    private fun checkPhone() {
        val phone = id_activity_login_edit_phone?.text.toString().trim { it <= ' ' }
        if (phone.length == 11) {
            //            if (PhoneNumUtils.isChinaPhoneLegal(phone) && PhoneNumUtils.isMobile(phone)) {
            mPresenter?.requestCode(phone)
            //            } else {
            //                mLoading.setResult(false, "手机号码错误", 1000);
            //            }

        } else {
        }
    }

    override fun smsCodeFaild(msg: String) {
    }

    override fun loginSuc() {
        //  mLoading.setResult(true, "登录成功", 1000)
        UserDataUtils.updateUserInfo(this)
    }

    override fun smsCodeSuccess() {
        startTimer(60)
    }

    override fun getSignSuc(sign: String) {
        SettingPreference.setImSignInfo(sign)
//        TUIUtils.login(SettingPreference.getUid(), sign, object : V2TIMCallback {
//            override fun onError(code: Int, desc: String) {
//                runOnUiThread {
//                    loginFaild("失败")
//                    Log.e("MXL", "链接失败" + SettingPreference.getUid() + sign)
//                    //  ToastUtil.toastLongMessage(getString(R.string.failed_login_tip) + ", errCode = " + code + ", errInfo = " + desc)
//                }
//
//            }
//
//            override fun onSuccess() {
//                mLoading.setResult(true, "登录成功", 1000)
//                if (TextUtils.equals(SettingPreference.getUserHasData(), "1")) {
//                    JumpUtils.activityJump(
//                        RounterBus.getRounter(RounterApi::class.java).getIntentActivityMain()
//                    )
//
//                } else {
//                    JumpUtils.SettingInfoJump()
//                }
//                finish()
//            }
//        })
    }

    override fun getSignFail() {
        TUIUtils.login(
            SettingPreference.getUid(),
            GenerateTestUserSig.genTestUserSig(SettingPreference.getUid()),
            object : V2TIMCallback {
                override fun onError(code: Int, desc: String) {
                    runOnUiThread {
                        loginFaild("失败")
                        //  ToastUtil.toastLongMessage(getString(R.string.failed_login_tip) + ", errCode = " + code + ", errInfo = " + desc)
                    }

                }

                override fun onSuccess() {
                    if (TextUtils.equals(SettingPreference.getUserHasData(), "1")) {
                        JumpUtils.activityJump(
                            RounterBus.getRounter(RounterApi::class.java).getIntentActivityMain()
                        )

                    } else {
                        JumpUtils.SettingInfoJump()
                    }
                    finish()
                }
            })
    }



    private fun swtichLayout() {
        if (TYPE == CODE) {
            id_activity_login_edit_phone_line?.visibility = View.GONE
            id_activity_login_edit_phone_getcode?.visibility = View.GONE
            id_activity_login_code_layout?.visibility = View.GONE
            id_activity_login_code_line?.visibility = View.GONE
            id_activity_login_password_layout?.visibility = View.VISIBLE
            id_activity_login_password_line?.visibility = View.VISIBLE
            id_activity_login_forget?.visibility = View.VISIBLE
            id_activity_login_switch_type?.text = "免密码登录"
            TYPE = PASSWORD
            switchPsw()
        } else {
            id_activity_login_edit_phone_line?.visibility = View.VISIBLE
            id_activity_login_edit_phone_getcode?.visibility = View.VISIBLE
            id_activity_login_code_layout?.visibility = View.VISIBLE
            id_activity_login_code_line?.visibility = View.VISIBLE
            id_activity_login_password_layout?.visibility = View.GONE
            id_activity_login_password_line?.visibility = View.GONE
            id_activity_login_forget?.visibility = View.GONE
            id_activity_login_switch_type?.text = "密码登录"
            TYPE = CODE
        }
    }

    private fun startTimer(count: Long) {
        isStartTimer = false
        id_activity_login_edit_phone_getcode?.setTextColor(-0x39393a)
        id_activity_login_edit_phone_getcode?.isEnabled = false
        Flowable.intervalRange(0, count, 0, 1, TimeUnit.SECONDS).compose(bindToLifecycle())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnNext { aLong ->
                SECONDS = count - (aLong + 1)
                id_activity_login_edit_phone_getcode?.text = "重新发送(" + SECONDS + "s)"
                if (!isStartTimer) {
                    isStartTimer = true
                }
            }.doOnComplete {
                if (SECONDS == 0L) {
                    isStartTimer = false
                    id_activity_login_edit_phone_getcode?.isEnabled = true
                    id_activity_login_edit_phone_getcode?.setTextColor(-0xe0e0e1)
                    id_activity_login_edit_phone_getcode?.text = "获取验证码"
                }
            }.subscribe()
    }

    override fun onResume() {
        super.onResume()
        if (isStartTimer) {
            startTimer(SECONDS)
        }

    }

    override fun loginFaild(msg: String) {
        // mLoading.setResult(false, msg, 1000)
        //  JumpUtils.homeJump()
    }


    fun oneKeyLogin() {

        //   mPresenter?.oneKeyLogin()
    }

    fun checkNullAndLogin() {
        if(!ifchoose){
            Utils.showToast(this, "请勾选同意后再进行登录")
            return
        }
        val phone = id_activity_login_edit_phone?.text.toString().trim { it <= ' ' }
        if (TextUtils.isEmpty(phone)) {
            return
        }
        if (TYPE == CODE) {
            val code = id_activity_login_edit_code?.text.toString().trim { it <= ' ' }
            if (TextUtils.isEmpty(code)) {
                return
            }
            mPresenter?.codeLogin(phone, code)
        } else {
            val password = id_activity_login_edit_password?.text.toString().trim { it <= ' ' }
            if (TextUtils.isEmpty(password)) {
                return
            } else if (password.length < 6) {
                return
            }
//            mPresenter?.passwordLogin(phone, password)
        }
    }

    private fun switchPsw() {
        if (isShowPsw) {
            id_activity_login_edit_password_show?.setBackgroundResource(R.drawable.icon_login_pass_hide)
            id_activity_login_edit_password?.inputType =
                InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD// 输入为密码且可见
        } else {
            id_activity_login_edit_password_show?.setBackgroundResource(R.drawable.icon_login_pass_show)
            id_activity_login_edit_password?.inputType =
                InputType.TYPE_TEXT_VARIATION_PASSWORD or InputType.TYPE_CLASS_TEXT// 设置文本类密码（默认不可见），这两个属性必须同时设置
        }
    }

    private var mPrepareExit = false
    override fun onBackPressed() {
//        super.onBackPressed();
        exitBy2Click()
    }

    private fun exitBy2Click() {
        if (!mPrepareExit) {
            mPrepareExit = true // 准备退出
            Utils.showToast(this, resources.getString(R.string.nav_back_again_finish))
            id_activity_login_btn.postDelayed(Runnable {
                mPrepareExit = false // 取消退出
            }, 1500)
        } else {
            Utils.onExit(this)
        }
    }

    override fun onResult(code: Int, result: String?) {
        mPresenter?.getSign()
    }

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

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }
}