package com.ccwangluo.accelerator.utils

import android.content.Intent
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.http.HttpGo
import com.chuanglan.shanyan_sdk.OneKeyLoginManager
import com.github.shadowsocks.Core
import com.hjq.toast.ToastUtils
import com.tencent.mmkv.MMKV
import com.xuexiang.xpage.base.XPageFragment
import kotlinx.coroutines.Dispatchers
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(xPageFragment: XPageFragment, callBack: (Boolean) -> Unit) {
        PhoneUtils.openLoginAuth(xPageFragment) { b, s ->
            if (b) {
                val map = mutableMapOf<String, String>()
                map.put("token", s)
                xPageFragment.lifecycleScope.launch(Dispatchers.IO) {
                    val res = HttpGo.postSync<LoginRes>("/api/user/flash/login", map)
                    res?.let {
                        if (it.code == 200) {
                            token = it.data?.token
                            withContext(Dispatchers.Main) {
                                ToastUtils.show("登录成功")
                                OneKeyLoginManager.getInstance().finishAuthActivity()
                                callBack(true)
                            }
                        } else {
                            it.error?.let {
                                ToastUtils.show(it)
                            }
                            withContext(Dispatchers.Main) {
                                callBack(false)
                            }
                        }
                    }
                }
            } else {
                xPageFragment.startActivity(
                    Intent(
                        xPageFragment.context,
                        PhoneLoginActivity::class.java
                    )
                )
            }
        }
    }

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

    fun clearToken() {
        Core.stopService()
        MMKV.defaultMMKV().remove(KEY_TOKEN)
    }

    var token: String?
        get() = MMKV.defaultMMKV().decodeString(KEY_TOKEN, null)
        set(token) {
            MMKV.defaultMMKV().putString(KEY_TOKEN, token)
        }

    fun hasToken(): Boolean {
        return MMKV.defaultMMKV().containsKey(KEY_TOKEN)
    }

    fun logout() {

    }


}