package com.ccwangluo.accelerator.utils

import android.content.Context
import android.content.Intent
import android.content.Intent.FLAG_ACTIVITY_NEW_TASK
import androidx.lifecycle.lifecycleScope
import com.ccwangluo.accelerator.model.LoginRes
import com.ccwangluo.accelerator.model.UserProfile
import com.ccwangluo.accelerator.ui.login.PhoneLoginActivity
import com.ccwangluo.accelerator.utils.datareport.DataRePortUtils
import com.ccwangluo.accelerator.utils.http.HttpGo
import com.chuanglan.shanyan_sdk.OneKeyLoginManager
import com.github.shadowsocks.Core
import com.github.shadowsocks.bg.AuthManager
import com.hjq.toast.ToastUtils
import com.tencent.mmkv.MMKV
import com.xuexiang.xpage.base.XPageFragment
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.*

/**
 * 登录信息工具类
 */
object LoginUtils {

    private var timeNumber = 60

    private var userProfile: UserProfile? = null

    private var timer: Timer? = null
    private var timerTask: TimerTask? = null

    private var timerCallBack: (Int) -> Unit? = {}

    fun getUserProfile(xPageFragment: XPageFragment, callBack: (UserProfile?) -> Unit) {
        xPageFragment.lifecycleScope.launch(Dispatchers.IO) {
            val res = HttpGo.getSync<UserProfile>("/api/user/profile")
            res?.let {
                if (it.code == 200) {
                    it.data?.let {
                        userProfile = it
                    }
                } else {
//                    ToastUtils.show(it.error)
                }
                withContext(Dispatchers.Main) {
                    callBack(userProfile)
                }
            }
        }
    }

    fun getUserHasTimer(xPageFragment: XPageFragment, callBack: (Boolean) -> Unit) {
        getUserProfile(xPageFragment) {
            it?.let {
                val dateToStamp = TimeUtils.dateToStamp(it.vipExpireTime) + 24 * 60 * 60 * 1000
                callBack(it.vip && dateToStamp > System.currentTimeMillis())
            } ?: let {
                callBack(false)
            }
        }
    }

    fun getUserHasTimer(callBack: (Boolean) -> Unit) {
        userProfile?.let {
            val dateToStamp = TimeUtils.dateToStamp(it.vipExpireTime) + 24 * 60 * 60 * 1000
//            && it.vipExpireTime > System.currentTimeMillis()
            callBack(it.vip && dateToStamp > System.currentTimeMillis())
        }
    }

    fun registerTimerCallBack(callBack: (Int) -> Unit) {
        timerCallBack = callBack
    }

    fun unRegisterTimerCallBack() {
        timerCallBack = {}
    }

    var _phone = ""
    fun startTimer(phone: String) {
        _phone = phone
        timeNumber = 60
        timer?.cancel()
        timerTask = object : TimerTask() {
            override fun run() {
                timeNumber--
                timerCallBack(timeNumber)
                if (timeNumber <= 0) {
                    timer?.cancel()
                    _phone = ""
                }
            }
        }
        timer = Timer();
        timer?.schedule(timerTask, 0, 1000);
    }

    fun stopTimer() {
        _phone = ""
        timer?.cancel()
    }

    fun login(context: Context, callBack: (Boolean) -> Unit) {
        PhoneUtils.openLoginAuth(context) { b, s ->
            if (b) {
                val map = mutableMapOf<String, String>()
                map.put("token", s)
                SysUtils.getDeviceUUID()?.let { map.put("did", it) }
                GlobalScope.launch(Dispatchers.IO) {
                    val res = HttpGo.postSync<LoginRes>("/api/user/flash/login", map)
                    res?.let {
                        if (it.code == 200) {
                            token = it.data?.token
                            uid = it.data?.phone
                            withContext(Dispatchers.Main) {
                                ToastUtils.show("登录成功")
                                OneKeyLoginManager.getInstance().finishAuthActivity()
                                DataRePortUtils.report("role_entry", mutableMapOf("login" to "login_all"))
                                callBack(true)
                            }
                        } else {
                            it.error?.let {
                                ToastUtils.show(it)
                            }
                            withContext(Dispatchers.Main) {
                                callBack(false)
                            }
                        }
                    }
                }
            } else {
                val intent = Intent(
                    context,
                    PhoneLoginActivity::class.java
                )
                intent.addFlags(FLAG_ACTIVITY_NEW_TASK)
                context.startActivity(
                    intent
                )
            }
        }
    }

    private const val KEY_TOKEN = "com.ccwangluo.KEY_TOKEN"

    fun clearToken() {
        Core.stopService()
        token = null
    }

    var token: String?
        get() = AuthManager.authToken
        set(token) {
            AuthManager.authToken = token
        }

    fun hasToken(): Boolean {
        return !AuthManager.authToken.isNullOrBlank()
    }

    var uid: String?
        get() = MMKV.defaultMMKV().decodeString("ACC_UID", null)
        set(acc_uid) {
            MMKV.defaultMMKV().putString("ACC_UID", acc_uid)
        }

    fun logout() {

    }


}