package com.yidianling.user.ui.login

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.core.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.base.config.GET_GATEWAY_BASE_URL
import com.ydl.ydlcommon.base.config.HttpConfig
import com.ydl.ydlcommon.router.YdlCommonOut
import com.ydl.ydlcommon.utils.StatusBarUtils
import com.yidianling.common.tools.LogUtil
import com.yidianling.common.tools.RxKeyboardTool
import com.yidianling.common.tools.ToastUtil
import com.yidianling.user.LoginUtils
import com.yidianling.user.LoginUtils.logout
import com.yidianling.user.R
import com.yidianling.user.UserHelper
import com.yidianling.user.UserHelper.setUserinfo
import com.yidianling.user.api.event.RefreshRecentContactListEvent
import com.yidianling.user.http.LoginApiRequestUtil
import com.yidianling.user.http.request.BindPhoneJavaParam
import com.yidianling.user.route.UserIn.clearImData
import com.yidianling.user.ui.CountryListActivity
import com.yidianling.user.widget.ZDialog
import de.greenrobot.event.EventBus
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.activity_bind_phone.et_phone_number
import kotlinx.android.synthetic.main.activity_bind_phone.iv_del
import java.util.concurrent.TimeUnit

class BindPhoneActivity : BaseActivity() {
    private val REQUEST_CODE_COUNTRY = 1001
    private var countryCode: String = "0086"//国家或地区手机区号
    private var countryName: String = "中国"
    private var msgCodeDispoable: Disposable? = null
    private var mKeFuDialog: ZDialog? = null
    private var mIsForceBindPhone: Boolean = false // 是否强绑手机号
    private var mIsFromGuide: Boolean = false    // 是否来自启动页

    companion object {
        /**
         * 启动BindPhoneActivity
         */
        fun startActivity(context: Context, isForceBindPhone: Boolean, isFromGuide: Boolean) {
            val intent = Intent(context, BindPhoneActivity::class.java)
            intent.putExtra("is_force_bind_phone", isForceBindPhone)
            intent.putExtra("is_from_guide", isFromGuide)
            context.startActivity(intent)
        }
    }

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


    override fun initDataAndEvent() {
        setWindowStatusBarColor()
        mIsForceBindPhone = intent.getBooleanExtra("is_force_bind_phone",false)
        mIsFromGuide = intent.getBooleanExtra("is_from_guide", false)
        iv_back.setOnClickListener {
            onBackPressed()
        }
        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 {
            if (checkPhone()) {
                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 == "中国") && 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 == "中国")) {
                    setTvGetCodeStatus()
                    setTvBindPhoneStatus()
                    return@setListener
                }
                if (!tv_country_code.text?.equals("中国")!! && 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) {
            }
        })
//        getIsNeedForceBindPhone()
        setTvGetCodeStatus()
    }

//    /**
//     * 获取用户是否需要强绑定手机号
//     */
//    @SuppressLint("CheckResult")
//    private fun getIsNeedForceBindPhone() {
//        val userInfo = UserHelper.getUserInfo()?.userInfo
//        val map = HashMap<String, String>()
//        map["login_type"] = loginType
//        map["openid"] = userInfo?.open_id_qqapp ?: ""
//        map["unionid"] = userInfo?.union_id ?: ""
//        LoginApiRequestUtil.isNeedForceBindPhone(map)
//            .subscribeOn(Schedulers.io())
//            .observeOn(AndroidSchedulers.mainThread())
//            .subscribe({
//                if (it.code == "200") {
//                    isForceBindPhone = it.data
//                }
//            }, {
//                ToastUtil.toastShort(it.message)
//            })
//    }

    /**
     * 检查手机号是否是用户版号码、是否有设置密码、是否被绑定
     */
    @SuppressLint("CheckResult")
    private fun checkPhoneStatus() {
        val phone = et_phone_number.text.toString().replace(" ", "")
        LoginApiRequestUtil.checkPhoneStatus(phone, countryCode, GET_GATEWAY_BASE_URL)
            .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, HttpConfig.Companion.GET_GATEWAY_BASE_URL)
            .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)
            })
    }

    /**
     * 绑定手机号
     */
    @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!!,transferFlag=1)
        LoginApiRequestUtil.bindPhone(bindPhoneParams)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSubscribe { showProgressDialog() }
            .doAfterTerminate { dismissProgressDialog() }
            .subscribe({
                RxKeyboardTool.hideSoftInput(this)
                if (it.code == 200) {
                    ToastUtil.toastShort("绑定成功")
                    UserHelper.getUserInfo()!!.userInfo!!.bind_phone = 1
                    UserHelper.getUserInfo()!!.userInfo!!.phone = phone
                    if (mIsFromGuide) {
                        LoginUtils.loginSuccessOperate(this)
                    } else {
                        finish()
                    }
                } else if (it.code == 1300000004) {    // 如果不是10分钟内注册，提示“绑定失败，此手机号已注册”，并标记此账号为无需强绑
                    ToastUtil.toastShort(it.msg)
                    if (mIsFromGuide) {
                        LoginUtils.loginSuccessOperate(this)
                    } else {
                        finish()
                    }
                }else if(it.code==1800010011){
                    RegisterAndLoginActivity.startFromGuide(this,false,mIsFromGuide)
                    finish()
                } else {
                    ToastUtil.toastShort(it.msg)//服务端返回{验证码错误&异常}信息
                }
            }, {
                ToastUtil.toastShort(it.message)
            })
    }

    override fun onBackPressed() {
        if (mIsForceBindPhone) {
            //清除UserInfo
            setUserinfo(null)
            clearImData()
            logout()
            EventBus.getDefault().post(RefreshRecentContactListEvent())
            finish()
        } else {
            LoginUtils.loginSuccessOperate(this)
        }
    }


    /**
     * 开始倒计时
     */
    @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"
            countryName = data?.getStringExtra("name") ?: "中国"
            tv_country_code.text = countryName
        }
    }

    /**
     * 设置获取验证码按钮状态
     * @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()
        }
    }

    /**
     * 检查手机号规范
     */
    private fun checkPhone(): Boolean {
        val editPhone = et_phone_number.textContent
        if (TextUtils.isEmpty(editPhone)) {
            ToastUtil.toastShort("请输入手机号")
            return false
        }
        LogUtil.e("本地userPhoneNumber赋值操作2：$editPhone")
        //手机号码验证 国外手机号码不做限制
        if (!TextUtils.equals("0086", countryCode)) {
            return !TextUtils.isEmpty(editPhone)
        }
        return if (editPhone.length == 11 && editPhone.startsWith("1") && checkRegex(
                editPhone.toString().trim()
            )
        ) {
            true
        } else {
            ToastUtil.toastShort("不是正确的手机号")
            false
        }
    }

    private fun checkRegex(phone: String): Boolean {
        val regex = "^1+[23456789]+\\d{9}"
        return phone.matches(regex.toRegex())
    }

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