package com.yidianling.user.ui

import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.util.Log
import android.view.View
import com.ydl.ydlcommon.base.BaseActivity
import com.ydl.ydlcommon.bean.StatusBarOptions
import com.ydl.ydlcommon.data.http.RxUtils
import com.ydl.ydlcommon.data.http.ThrowableConsumer
import com.ydl.ydlcommon.router.YdlCommonOut
import com.ydl.ydlcommon.utils.ActivityManager
import com.ydl.ydlcommon.utils.UserInfoCache
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import com.ydl.ydlcommon.utils.log.AliYunLogConfig
import com.ydl.ydlcommon.utils.log.AliYunRichLogsHelper
import com.ydl.ydlcommon.utils.remind.ToastHelper
import com.yidianling.im.api.bean.IMLoginInfo
import com.yidianling.im.api.bean.IMRequestCallback
import com.yidianling.user.LoginUtils
import com.yidianling.user.StatusUtils
import com.yidianling.user.UserConstants
import com.yidianling.user.api.bean.UserResponseBean
import com.yidianling.user.constants.UserBIConstants
import com.yidianling.user.http.UserHttp
import com.yidianling.user.http.UserHttpImpl
import com.yidianling.user.http.request.CodeParam
import com.yidianling.user.http.request.LoginParam
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 io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.user_activity_get_identifying_code.*
import java.util.concurrent.TimeUnit


/**
 * 短信快捷登录界面
 * author : Zhangwenchao
 * e-mail : zhangwch@yidianling.com
 * time   : 2018/01/10
 */
class SmsLoginActivity : BaseActivity() {

    companion object {

        private val KEY_CODE = "code"
        private val KEY_NUM = "phone_num"
        private val KEY_SPLASH = "from_splash"

        @JvmStatic
        fun start(context: Context, code: String, phoneNum: String, isFromSplash: Boolean) {
            val intent = Intent(context, SmsLoginActivity::class.java)
            intent.putExtra(KEY_NUM, phoneNum)
            intent.putExtra(KEY_CODE, code)
            intent.putExtra(KEY_SPLASH, isFromSplash)
            context.startActivity(intent)
        }
    }

    private lateinit var phoneNum: String
    private lateinit var code: String
    private var isFromSplash: Boolean = false

    override fun layoutResId(): Int {
        return com.yidianling.user.R.layout.user_activity_get_identifying_code
    }

    override fun initDataAndEvent() {
        phoneNum = intent.getStringExtra(KEY_NUM)
        code = intent.getStringExtra(KEY_CODE)
        isFromSplash = intent.getBooleanExtra(KEY_SPLASH, false)
        initView()
        requestVCode()

    }

    override fun getStatusViewOptions(): StatusBarOptions {
        return StatusBarOptions(isAddStatusView = true, statusBarDarkMode = true)
    }

    override fun onDestroy() {
        super.onDestroy()
        unsubscribe(timerSub)
        unsubscribe(vCodeSub)
        unsubscribe(loginSub)
    }

    private fun initView() {
        lin_login_pass.visibility = View.GONE
        text_pass_tip.visibility = View.GONE
        tb_title.title = title.toString()
        rcb_submit.text = "登录"
        tv_phone.text = phoneNum
        tv_get_code.setOnClickListener { requestVCode() }
        rcb_submit.setOnClickListener { login() }
    }

    private var vCodeSub: Disposable? = null

    private val userHttp: UserHttp = UserHttpImpl.getInstance()

    // 获取验证码
    private fun requestVCode() {
        initTimer()
/*        vCodeSub = RetrofitUtils.getCode(Command.GetCode(code, phoneNum, UserConstants.SIGNIN_ACTION))
                .subscribeOn(Schedulers.io())
                .compose(RxUtils.handlerError())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({}, {
                    RetrofitUtils.handleError(this, it)
                })*/

        vCodeSub = userHttp.code(CodeParam(code, phoneNum, UserConstants.SIGNIN_ACTION))
            .compose(RxUtils.resultData())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(Consumer {}, object : ThrowableConsumer() {
                override fun accept(msg: String) {
                    ToastHelper.show(msg)
                }
            })
    }

    private var loginSub: Disposable? = null

    // 登录
    private fun login() {
        if (TextUtils.isEmpty(et_code.text)) {
            ToastHelper.show("请输入验证码")
            return
        }

        ActionCountUtils.count(
            UserBIConstants.POSITION_LOGIN_CLICK,
            UserBIConstants.ACTION_TYPE_CODE_LOGIN
        )

        Log.e("短信验证码：", code + " - " + phoneNum + " - " + et_code.text.toString());
        loginSub = userHttp.login(LoginParam(code, phoneNum, null, 2, et_code.text.toString()))
            .compose(RxUtils.resultData())
            .doOnNext { LoginUtils.saveData(it) }
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSubscribe { showProgressDialog("") }
            .doAfterTerminate { dismissProgressDialog() }
            .subscribe(Consumer {
                LoginUtils.onLogin(it)
                //关闭手势解锁页面与指纹解锁页面
                finishFinger()
                if (it.firstLogin == 1) {
                    StatusUtils.isFirstLogin = true
                    baiduActionBury()
                } else {
                    ActionCountUtils.countUid(
                        UserBIConstants.POSITION_LOGIN_SUCCESS_CLICK,
                        it.uid!!,
                        UserBIConstants.ACTION_TYPE_CODE_LOGIN
                    )
                }
//                    ActivityManager.finishActivity(LoginActivity::class.java)
//                    if (ActivityManager.getActivitySize() <= 1) {
//                        UserIn.mainIntent(this)
//                    }
//                    finish()
                LoginUtils.loginSuccessOperate(this)

                AliYunRichLogsHelper.getInstance()
                    .sendRichLog(AliYunLogConfig.LOGIN, "短信验证码 成功")
            }, object : ThrowableConsumer() {
                override fun accept(msg: String) {
                    dismissProgressDialog()
                    YdlCommonOut.showToast(msg)
                    AliYunRichLogsHelper.getInstance()
                        .sendRichLog(AliYunLogConfig.LOGIN, "短信验证码 失败 msg：$msg ")
                }
            })
    }

    /**
     * 注册流程成功之后，进行百度监测 注册埋点
     */
    fun baiduActionBury() {
        ActionCountUtils.baiduCount(
            UserBIConstants.APP_REGISTER_PAGE,
            UserBIConstants.POSITION_CODE_REGISTER_CLICK,
            25
        )
    }

    //关闭手势解锁页面与指纹解锁页面
    private fun finishFinger() {
        ActivityManager.getInstance().finishActivity(FingerPrintCheckActivity::class.java)
        ActivityManager.getInstance().finishActivity(HandUnlockCheckActivity::class.java)
        FingerPrintUtil.instance().setCurrentUnLockTime(System.currentTimeMillis())
    }


    // 登录 IM
    private fun loginIM(info: UserResponseBean) {
        val loginInfo = IMLoginInfo(info.uid.toString(), info.hxpwd!!)
        val callback = object : IMRequestCallback<IMLoginInfo> {
            override fun onSuccess(loginInfo: IMLoginInfo?) {
                setHXInfo(info.userInfo)
            }

            override fun onFailed(i: Int) {
                ToastHelper.show("未知错误01")
            }

            override fun onException(throwable: Throwable?) {
                ToastHelper.show("未知错误02")
            }
        }
        UserIn.imSetAccount(loginInfo.account)
        UserIn.imLogin(loginInfo, callback)
    }

    //用户信息 获取登陆信息
    fun setHXInfo(userInfo: UserResponseBean.UserInfo?) {
        try {
            if (userInfo != null) {
                UserIn.imSetAccount(userInfo.uid.toString())
                UserInfoCache.getInstance().saveYDLUser(
                    userInfo.uid.toString(),
                    userInfo.nick_name,
                    userInfo.head
                )
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private var timerSub: Disposable? = null

    private fun initTimer() {
        timerSub = Observable.interval(0, 1, TimeUnit.SECONDS)
            .subscribeOn(Schedulers.computation())
            .take(60)
            .map { String.format("重发(%d)", 59 - it) }
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSubscribe {
                tv_get_code.isEnabled = false
                tv_get_code.setTextColor(-0x525253)
            }
            .subscribe({
                tv_get_code.text = it
            }, {}, {
                tv_get_code.text = "重新发送"
                tv_get_code.isEnabled = true
                tv_get_code.setTextColor(-0xb62d7f)
            })
    }


    private fun unsubscribe(s: Disposable?) {
        if (s != null && !s.isDisposed) {
            s.dispose()
        }

    }
}