package com.yidianling.user.ui.login

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.support.v4.content.ContextCompat
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import com.ydl.ydlcommon.base.BaseActivity
import com.ydl.ydlcommon.router.YdlCommonOut
import com.ydl.ydlcommon.utils.StatusBarUtils
import com.ydl.ydlcommon.utils.YDLCacheUtils
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.http.LoginApiRequestUtil
import com.yidianling.user.http.request.BindPhoneJavaParam
import com.yidianling.user.ui.CountryListActivity
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.activity_bind_phone.*
import kotlinx.android.synthetic.main.user_activity_verification_code_new.*
import java.util.concurrent.TimeUnit

class BindPhoneActivity : BaseActivity() {
    private val REQUEST_CODE_COUNTRY = 1001
    private var countryCode: String = "0086"//国家或地区手机区号
    private var msgCodeDispoable: Disposable? = null
    private var mKeFuDialog: ZDialog? = null

    companion object {
        /**
         * 启动BindPhoneActivity
         */
        fun startActivity(context: Context) {
            val intent = Intent(context, BindPhoneActivity::class.java)
            context.startActivity(intent)
        }
    }

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


    override fun initDataAndEvent() {
        setWindowStatusBarColor()

        iv_back.setOnClickListener {
            LoginUtils.logout()
            finish()
        }
        tv_country_code.setOnClickListener {
            val intent = Intent(this, CountryListActivity::class.java)
            intent.putExtra("userCountryCode", countryCode)
            startActivityForResult(intent, REQUEST_CODE_COUNTRY)
            overridePendingTransition(R.anim.platform_slide_in_from_bottom, R.anim.user_slide_null)
        }
        // 删除按钮
        iv_del.setOnClickListener {
            et_phone_number.setText("")
        }
        // 获取验证码按钮
        tv_get_code.setOnClickListener {
            checkPhoneStatus()
        }
        // 收不到验证码
        tv_no_get_code.setOnClickListener {
            showKeFuDialog()
        }
        // 绑定手机号
        tv_bind.setOnClickListener {
            bindPhone()
        }
        et_phone_number.setListener {
            if (TextUtils.isEmpty(it)) {
                iv_del.visibility = View.INVISIBLE
                iv_del.isEnabled = false
            } else {
                iv_del.visibility = View.VISIBLE
                iv_del.isEnabled = true
            }

            // 判断绑定按钮状态
            if ((tv_country_code.text == "+86") && it.toString().length == 13) {
                setTvGetCodeStatus(true, 1f)
                if (et_code.text.isNotEmpty()) {
                    setTvBindPhoneStatus(true, R.drawable.bg_one_click_login)
                }
            } else {
                if ((tv_country_code.text == "+86")) {
                    setTvGetCodeStatus()
                    setTvBindPhoneStatus()
                    return@setListener
                }
                if (!tv_country_code.text?.equals("+86")!! && it.toString().isNotEmpty()) {
                    setTvGetCodeStatus(true, 1f)
                    if (et_code.text.isNotEmpty()) {
                        setTvBindPhoneStatus(true, R.drawable.bg_one_click_login)
                    }
                } else {
                    setTvGetCodeStatus()
                    setTvBindPhoneStatus()
                }
            }
        }
        // 验证码输入监听
        et_code.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                if (s?.length ?: 0 > 0 && et_phone_number.text.isNotEmpty()) {
                    setTvBindPhoneStatus(true, R.drawable.bg_one_click_login)
                } else {
                    setTvBindPhoneStatus()
                }
            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }
        })
        setTvGetCodeStatus()
    }

    /**
     * 检查手机号是否是用户版号码、是否有设置密码、是否被绑定
     */
    @SuppressLint("CheckResult")
    private fun checkPhoneStatus() {
        val phone = et_phone_number.text.toString().replace(" ", "")
        LoginApiRequestUtil.checkPhoneStatus(phone, countryCode)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                if (it.data == null || it.code != 200) {
                    ToastUtil.toastShort(it.msg)
                    return@subscribe
                }
                // 获取验证码
                getBindPhoneCode(phone)
            }, {
                if (null != it && !TextUtils.isEmpty(it.message)) {
                    YdlCommonOut.showToast(it.message!!)
                }
            })
    }

    /**
     * 获取绑定手机验证码
     * @param phone
     */
    @SuppressLint("CheckResult")
    private fun getBindPhoneCode(phone:String){
        LoginApiRequestUtil.sendLoginMsgCode(phone,countryCode)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSubscribe { showProgressDialog()}
            .doAfterTerminate { dismissProgressDialog() }
            .subscribe({
                if (it.code == 200) {
                    startCountdown(60)
                } else {
                    ToastUtil.toastShort(it.msg)
                }
            }, {
                ToastUtil.toastShort(it.message)
            })
    }

    /**
     * 绑定手机号
     * @param phone
     * @param code
     */
    @SuppressLint("CheckResult")
    private fun bindPhone() {
        val phone = et_phone_number.text.toString().replace(" ", "")
        val code = et_code.text.toString()
        val bindPhoneParams = BindPhoneJavaParam("", countryCode, phone, code, UserHelper.getUserInfo()!!.uid!!)
        LoginApiRequestUtil.bindPhone(bindPhoneParams)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSubscribe { showProgressDialog() }
            .doAfterTerminate { dismissProgressDialog() }
            .subscribe({
                if (it.data != null && it.code == 200) {
                    ToastUtil.toastShort("手机号绑定成功")
                    UserHelper.getUserInfo()!!.userInfo!!.bind_phone = 1
                    UserHelper.getUserInfo()!!.userInfo!!.phone = phone
                    RxKeyboardTool.hideSoftInput(this)
                    LoginUtils.loginSuccessOperate(this)
                } else {
                    ToastUtil.toastShort(it.msg)//服务端返回{验证码错误&异常}信息
                }
            }, {
                ToastUtil.toastShort(it.message)
            })
    }


    /**
     * 开始倒计时
     */
    @SuppressLint("SetTextI18n")
    private fun startCountdown(remainTime: Int) {
        et_code.postDelayed({RxKeyboardTool.showSoftInput(this,et_code)},300)
        tv_get_code.isEnabled = false
        msgCodeDispoable = Observable.interval(0, 1, TimeUnit.SECONDS)
            .subscribeOn(Schedulers.computation())
            .take(remainTime.toLong())
            .map {
                (remainTime - it).toString()
            }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                tv_get_code.text = it + "s"
            }, {

            }, {
                tv_get_code.isEnabled = true
                tv_get_code.text = "重新发送"
            })
    }

    public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == 45 && requestCode == REQUEST_CODE_COUNTRY) {
            countryCode = data?.getStringExtra("code") ?: "0086"

            tv_country_code.text = "+${countryCode.replace("00", "")}"
        }
    }

    /**
     * 设置获取验证码按钮状态
     * @param isEnabled 按钮是否可点击
     * @param alpha 获取验证码透明度
     */
    private fun setTvGetCodeStatus(isEnabled: Boolean = false, alpha: Float = 0.6f) {
        tv_get_code.isEnabled = isEnabled
        tv_get_code.alpha = alpha
    }

    /**
     * 设置绑定按钮状态
     * @param isEnabled 按钮是否可点击
     * @param bg 绑定按钮背景图片
     */
    private fun setTvBindPhoneStatus(
        isEnabled: Boolean = false,
        bg: Int = R.drawable.login_password_unable_bg_24dp
    ) {
        tv_bind.isEnabled = isEnabled
        tv_bind.background = ContextCompat.getDrawable(this, bg)
    }


    /**
     * 设置状态栏
     */
    private fun setWindowStatusBarColor() {
        StatusBarUtils.Companion.setWindowStatusBarColor(this, R.color.white)
        StatusBarUtils.Companion.setStatusBarLightMode(this, true)
    }

    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()
        }
    }

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