package com.img.rabbit.viewmodel

import android.app.Activity
import android.content.Context
import android.util.Log
import android.widget.Toast
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import com.g.gysdk.GYManager
import com.g.gysdk.GYResponse
import com.g.gysdk.GyCallBack
import com.g.gysdk.GyConfig
import com.google.gson.JsonObject
import com.img.rabbit.bean.local.ErrorBean
import com.img.rabbit.bean.local.OnekeyPreLogin
import com.img.rabbit.bean.response.LoginInfoEntity
import com.img.rabbit.pages.screen.mine.setting.BindScreenType
import com.img.rabbit.provider.api.ApiManager
import com.img.rabbit.provider.api.ResultVo
import com.img.rabbit.provider.storage.PreferenceUtil
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPI
import kotlinx.serialization.json.Json
import okhttp3.RequestBody.Companion.toRequestBody

class BindViewModel : BaseViewModel() {
    private val TAG = "BindViewModel"
    private val ONEKEY_TAG = "BindViewModel_OneKey"
    val bindScreenType = mutableStateOf(BindScreenType.BIND_NORMAL)
    // 登录状态
    val bindState = mutableStateOf<ResultVo<LoginInfoEntity>?>(null)
    // 错误状态
    val errorState = mutableStateOf<ErrorBean?>(null)

    // 是否同意政策协议
    private val _policyAgreement = mutableStateOf(true)
    val isPolicyAgreement: State<Boolean> = _policyAgreement
    fun setIsPolicyAgreement(isAgreement: Boolean) {
        _policyAgreement.value = isAgreement
    }


    // 一键登录是否有效
    private val isGYUIDValid = mutableStateOf(false)
    var oneKeyPreLogin: OnekeyPreLogin? = null
    // 登录用户名
    val userName = mutableStateOf("")
    fun setUserName(loginName: String) {
        userName.value = loginName
    }
    // 登录验证码
    val captcha = mutableStateOf("")
    // 登录验证码发送时间戳
    val captchaTimestamp = mutableStateOf("")
    fun setCaptcha(loginCaptcha: String) {
        captcha.value = loginCaptcha
    }


    fun oneKeyLoginForGeTuiSdk(activity: Activity, onShowOneKeyScreen:(Boolean)->Unit) {
        // 初始化 SDK
        GYManager.getInstance().init(GyConfig.with(activity.applicationContext).callBack(object : GyCallBack {
            override fun onSuccess(response: GYResponse?) {
                isGYUIDValid.value = true
                Log.i(ONEKEY_TAG, "--->初始化: onSuccess")

                //预登录（提高拉起速度，可选但推荐）
                GYManager.getInstance().ePreLogin(/* timeout = */ 8000, /* gyCallBack = */ object : GyCallBack {
                    override fun onSuccess(response: GYResponse?) {
                        Log.i(ONEKEY_TAG, "--->预登录: onSuccess--->${response}")
                        val preLoginData = response?.msg
                        if (!preLoginData.isNullOrEmpty()) {
                            try {
                                val json = Json { ignoreUnknownKeys = true }
                                oneKeyPreLogin =
                                    json.decodeFromString<OnekeyPreLogin>(preLoginData)

                                // 打印解析后的详细数据
                                Log.i(ONEKEY_TAG, "=== 预登录数据解析结果 ===")
                                Log.i(ONEKEY_TAG, "流程ID: ${oneKeyPreLogin?.process_id}")
                                Log.i(ONEKEY_TAG, "运营商类型: ${oneKeyPreLogin?.operatorType}")
                                Log.i(ONEKEY_TAG, "客户端类型: ${oneKeyPreLogin?.clienttype}")
                                Log.i(ONEKEY_TAG, "访问码: ${oneKeyPreLogin?.accessCode}")
                                Log.i(ONEKEY_TAG, "手机号: ${oneKeyPreLogin?.number}")
                                Log.i(ONEKEY_TAG, "过期时间: ${oneKeyPreLogin?.expiredTime}")
                                Log.i(ONEKEY_TAG, "错误码: ${oneKeyPreLogin?.errorCode}")
                                Log.i(ONEKEY_TAG, "错误描述: ${oneKeyPreLogin?.errorDesc}")
                                Log.i(ONEKEY_TAG, "耗时: ${oneKeyPreLogin?.costTime}ms")
                                Log.i(ONEKEY_TAG, "================================")

                                // 根据解析结果决定是否继续（根据errorCode判断）
                                if (oneKeyPreLogin?.errorCode == 0) {
                                    oneKeyLoginValid(
                                        onShowOneKeyScreen = onShowOneKeyScreen
                                    )
                                } else {
                                    onShowOneKeyScreen(false)
                                    Log.e(ONEKEY_TAG, "预登录校验失败: ${oneKeyPreLogin?.errorDesc}")
                                }

                            } catch (e: Exception) {
                                Log.e(ONEKEY_TAG, "JSON解析失败: ${e.message}")
                                Log.e(ONEKEY_TAG, "原始数据: $preLoginData")
                                // 解析失败时继续执行原逻辑
                                onShowOneKeyScreen(false)
                            }
                        }
                    }

                    override fun onFailed(response: GYResponse?) {
                        onShowOneKeyScreen(false)
                        Log.i(ONEKEY_TAG, "--->预登录: onFailed--->${response}")
                    }
                })
            }

            override fun onFailed(response: GYResponse?) {
                onShowOneKeyScreen(false)
                Log.i(ONEKEY_TAG, "--->初始化: onFailed--->${response}")
            }
        }).build())
    }

    private fun oneKeyLoginValid(onShowOneKeyScreen:(Boolean)->Unit) {
        if (GYManager.getInstance().isPreLoginResultValid) {
            //预登录有效，启动登录授权页
            onShowOneKeyScreen(true)
        } else {
            //考虑到是用户在等待，建议超时8s以上，至少设置5s以上
            GYManager.getInstance().ePreLogin(5000, object : GyCallBack {
                override fun onSuccess(response: GYResponse?) {
                    //预登录成功，启动登录授权页
                    onShowOneKeyScreen(true)
                }

                override fun onFailed(response: GYResponse?) {
                    //预登录失败，提示用户稍后重试
                    onShowOneKeyScreen(false)
                }
            })
        }
    }

    fun requestOneKeyLogin(gyuid: String, token: String) {
        isLoading.value = true // 开始加载

        // 调用 API 获取数据
        val jsonOneKey = JsonObject()

        jsonOneKey.addProperty("gyuid", gyuid)
        jsonOneKey.addProperty("token", token)
        val jsonObject = JsonObject()
        jsonObject.addProperty("type", "onekey")
        jsonObject.addProperty("bind", "1")
        jsonObject.add("data", jsonOneKey)

        requestBind(jsonObject)
    }

    /**
     * 请求验证码
     */
    fun requestCaptcha(phone: String) {
        //  发送请求获取验证码
        isLoading.value = true // 开始加载

        mLaunch {
            // 调用 API 获取数据
            val jsonObject = JsonObject()
            jsonObject.addProperty("phone", phone)
            val response = ApiManager.serviceVo.sendCode(jsonObject.toString().toRequestBody())
            if (response.status) {
                Log.w(TAG, "请求验证码成功: ${response.data.timestamp}")
                captchaTimestamp.value = response.data.timestamp
            }else{
                errorState.value = ErrorBean(response.code.toString(), response.message.ifEmpty { "获取验证码失败" })
            }
            isLoading.value = false // 加载完成
        }
    }

    /**
     * 请求登录(验证码)
     */
    fun requestBindForCaptcha(phone: String, code: String) {
        isLoading.value = true // 开始加载

        // 调用 API 获取数据
        val jsonPhone = JsonObject()
        jsonPhone.addProperty("timestamp", captchaTimestamp.value)
        jsonPhone.addProperty("phone", phone)
        jsonPhone.addProperty("code", code)

        val jsonObject = JsonObject()
        jsonObject.addProperty("type", "phone")
        jsonObject.addProperty("bind", "1")
        jsonObject.add("data", jsonPhone)

        requestBind(jsonObject)
    }

    /**
     * 请求微信授权
     */
    fun requestWithWechatAuth(context: Context, wxApi: IWXAPI) {
        if (isPolicyAgreement.value) {
            doWechatAuth(context, wxApi)
        }else{
            Toast.makeText(context, "请先同意用户协议和隐私政策", Toast.LENGTH_SHORT).show()
        }
    }

    //获取微信授权
    private fun doWechatAuth(context: Context, wxApi: IWXAPI) {
        if (!wxApi.isWXAppInstalled) {
            Toast.makeText(context, "您没有安装微信客户端,请先下载安装", Toast.LENGTH_SHORT).show()
            return
        }
        val req = SendAuth.Req()
        req.scope = "snsapi_userinfo" // 只能填 snsapi_userinfo
        req.state = context.packageName + Math.random() * 1000 + "_phone"
        wxApi.sendReq(req)
    }

    /**
     * 拿着微信授权码完成登录(在WXEntryActivity中调用)
     * @param wechatCode 微信授权码
     */
    fun requestWxBind(wechatCode: String) {
        if(wechatCode.isEmpty()){
            return
        }
        isLoading.value = true // 开始加载
        PreferenceUtil.saveWxCode(wechatCode)

        // 调用 API 获取数据
        val jsonWx = JsonObject()
        jsonWx.addProperty("code", wechatCode)
        jsonWx.addProperty("code_type", "")

        val jsonObject = JsonObject()
        jsonObject.addProperty("type", "weixin")
        jsonObject.addProperty("bind", "1")
        jsonObject.add("data", jsonWx)

        requestBind(jsonObject)
    }


    //请求绑定
    private fun requestBind(jsonObject: JsonObject){
        mLaunch {
            val response = ApiManager.serviceVo.login(jsonObject.toString().toRequestBody())
            if (response.status) {
                bindState.value = response
            }else{
                errorState.value = ErrorBean(response.code.toString(), response.message.ifEmpty { "登录失败" })
            }
            isLoading.value = false // 加载完成
        }
    }



    enum class BindType(val type: Int,val desc: String){
        FROM_PHONE(0,"手机号"),
        FROM_WX(1,"微信")
    }
}