
local luaVersion = "1" -- 脚本版本
local luaNoticeId = "102" -- 公告id
--下面2781775952就是qq号可以替换你的
local luaIcon= "https://q.qlogo.cn/headimg_dl?dst_uin=2781775952&spec=640&img_type=jpg"
local dexUrl = "https://pan.iema.cn/f/d/jKQf8/SDK_2.0.dex"
--以下是验证配置
local authConfig = {
    appId = "APPID",
    appKey = "APPKEY",
    signature = {
        type = "MD5",
        rule = 1
    },
    encryption = {
        type = "RC4",
        key = "RC4KEY"
    },
    antiHijack = true,
    encode = "BASE64",
    code = 1
}

function isFile(path)
    local File = import("java.io.File")
    local fileObj = File(path)
    return fileObj:exists()
end

function createDir(path)
    local File = import("java.io.File")
    local dir = File(path)
    if not dir:exists() then
        return dir:mkdirs()
    end
    return true
end

local function initializeSDK(dexUrl, authConfig)
    local dexDir = gg.PATH .. "/AGG/"
    local dexFileName = "SDK.dex"
    local dexFilePath = dexDir .. dexFileName
    
    if not createDir(dexDir) then
        gg.alert("创建目录失败: " .. dexDir)
        return false
    end
    if not isFile(dexFilePath) then
        gg.toast("首次启动需要加载数据包，请稍等...")
        local response = gg.makeRequest(dexUrl)
        
        if not response or not response.content then
            gg.alert("下载SDK失败")
            return false
        end
        
        local file, err = io.open(dexFilePath, "wb")
        if not file then
            gg.alert("无法创建文件: " .. tostring(err))
            return false
        end
        
        file:write(response.content)
        file:close()
    end

    local sdkClass = gg.loadClass(dexFilePath, "SDK")
    if type(sdkClass) ~= "function" then
        gg.alert("SDK加载失败")
        return false
    end

    local ArtAuth = sdkClass()
    local auth, err = ArtAuth:new(authConfig)
    if not auth then
        gg.alert("脚本初始化失败！\n错误代码：" .. tostring(err))
        return false
    end

    return auth
end

function initFK()
    local Build = luajava.bindClass("android.os.Build")
    local Tools = luajava.bindClass("android.ext.Tools")
    if Build.VERSION.SDK_INT > 26 then
        Tools.isText = true
    end
end

initFK()

function exit()
    os.exit()
    while true do
        _ENV = nil
    end
end

local auth, err = initializeSDK(dexUrl, authConfig)

function checkVersion()
    local result, verErr = auth:getVersion()
    if result.code == auth:getCode() then
        local ver = result.data
        local verText = string.format("脚本已更新！\n\n" .. "⏳最新版本: %s \n" .. "⌛️当前版本: %s \n" .. "⏱️更新时间: %s\n" .. "---------------------------\n%s", ver.num or "N/A", luaVersion or "N/A", ver.updateTime or "N/A", ver.content or "无")
        if ver.num ~= luaVersion then
            info = gg.alert(verText, "", nil, nil)
            if info and ver.forced == 1 and ver.addr ~= "" then
                local f = io.open(gg.File(), "w")
                f:write(gg.makeRequest(ver.addr).content)
                f:close()
                gg.alert("更新成功！")
                exit()
            else
                exit()
            end
        end
    end
end

if not auth then
    gg.alert("初始化失败", err or "未知错误")
    os.exit()
end

function luajavaView()
    local Tools = luajava.bindClass("android.ext.Tools")
    local ThreadManager = import("android.ext.ThreadManager")
    local Context = Tools.getContext()
    local LinearLayout = luajava.bindClass("android.widget.LinearLayout")
    local ScrollView = luajava.bindClass("android.widget.ScrollView")
    local LayoutParams = luajava.bindClass("android.widget.LinearLayout$LayoutParams")
    local TextView = luajava.bindClass("android.widget.TextView")
    local Color = luajava.bindClass("android.graphics.Color")
    local GradientDrawable = luajava.bindClass("android.graphics.drawable.GradientDrawable")
    local MaterialCardView = luajava.bindClass("com.google.android.material.card.MaterialCardView")
    local MaterialButton = luajava.bindClass("com.google.android.material.button.MaterialButton")
    
    local ContextThemeWrapper = luajava.bindClass("android.view.ContextThemeWrapper")
    local TextInputLayout = luajava.bindClass("com.google.android.material.textfield.TextInputLayout")
    local TextInputEditText = luajava.bindClass("com.google.android.material.textfield.TextInputEditText")
    local ColorStateList = luajava.bindClass("android.content.res.ColorStateList")

    local Handler = luajava.bindClass("android.os.Handler")
    local Looper = luajava.bindClass("android.os.Looper")
    local mainHandler = Handler(Looper.getMainLooper())

    local allThemes = AppTheme.getThemes()
    local activeTheme = allThemes['MaterialDynamicColors'] 
    if not activeTheme then activeTheme = allThemes['DeepBlue'] end
    
    if not activeTheme then
        activeTheme = {
            primary = 0xFF6750A4, background = 0xFFF5F7FA, surface = 0xFFFFFFFF,
            text = 0xFF000000, textSecondary = 0xFF808080, onPrimary = 0xFFFFFFFF,
            onSurfaceVariant = 0xFF808080, border = 0xFFE0E0E0
        }
    end

    local C_PRIMARY   = activeTheme.primary
    local C_ON_PRIM   = activeTheme.onPrimary
    local C_BG_ROOT   = activeTheme.background
    local C_CARD_BG   = activeTheme.surface
    local C_TEXT_MAIN = activeTheme.text
    local C_TEXT_SUB  = activeTheme.textSecondary
    local C_HINT      = activeTheme.onSurfaceVariant
    local C_BORDER    = activeTheme.border
    local C_WARN      = 0xFFB3261E 

    local VIEW_VISIBLE = 0
    local VIEW_GONE = 8
    local GRAVITY_CENTER_V = 16
    local STYLE_OUTLINED_BOX = 0x7f1404d3

    local FONT_SIZE_TITLE = 15
    local FONT_SIZE_BODY = 12
    local BTN_HEIGHT = Tools.dp2px(40)
    local BTN_RADIUS = Tools.dp2px(20)

    local function createStrokeBg(color, radius, strokeColor, strokeWidth)
        local gd = GradientDrawable()
        gd.setColor(color)
        gd.setCornerRadius(radius)
        if strokeColor then gd.setStroke(Tools.dp2px(strokeWidth), strokeColor) end
        return gd
    end

    local rootLayout = LinearLayout(Context)
    rootLayout.setOrientation(LinearLayout.VERTICAL)
    rootLayout.setLayoutParams(LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
    rootLayout.setBackgroundColor(C_BG_ROOT)

    local scrollView = ScrollView(Context)
    scrollView.setLayoutParams(LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
    scrollView.setFillViewport(true)
    rootLayout.addView(scrollView)
    
    local contentLinear = LinearLayout(Context)
    contentLinear.setOrientation(LinearLayout.VERTICAL)
    contentLinear.setPadding(Tools.dp2px(12), Tools.dp2px(12), Tools.dp2px(12), Tools.dp2px(12))
    scrollView.addView(contentLinear)

    local cardParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
    cardParams.bottomMargin = Tools.dp2px(12)

    local cardActive = MaterialCardView(Context)
    cardActive.setLayoutParams(cardParams)
    cardActive.setCardBackgroundColor(C_CARD_BG)
    cardActive.setRadius(Tools.dp2px(10))
    cardActive.setCardElevation(Tools.dp2px(3))

    local c1_Linear = LinearLayout(Context)
    c1_Linear.setOrientation(LinearLayout.VERTICAL)
    c1_Linear.setPadding(Tools.dp2px(14), Tools.dp2px(16), Tools.dp2px(14), Tools.dp2px(16))

    local txt_ActTitle = TextView(Context)
    txt_ActTitle.setText("卡密激活")
    txt_ActTitle.setTextSize(FONT_SIZE_TITLE) 
    txt_ActTitle.setTextColor(C_TEXT_MAIN)
    txt_ActTitle.setTypeface(nil, 1) 
    local titleParams = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
    titleParams.bottomMargin = Tools.dp2px(12)
    txt_ActTitle.setLayoutParams(titleParams)

    local styledContext = ContextThemeWrapper(Context, STYLE_OUTLINED_BOX)
    local inputLayout = TextInputLayout(styledContext)
    inputLayout.setLayoutParams(LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT))
    inputLayout.setHint("请输入卡密")
    inputLayout.setBoxStrokeColor(C_PRIMARY)
    inputLayout.setDefaultHintTextColor(ColorStateList.valueOf(C_HINT))

    local edit_Kami = TextInputEditText(styledContext)
    edit_Kami.setLayoutParams(LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT))
    edit_Kami.setSingleLine(true)
    edit_Kami.setTextSize(FONT_SIZE_BODY)
    edit_Kami.setTextColor(C_TEXT_MAIN)
    edit_Kami.setHintTextColor(C_HINT)
    
    local savedCard = auth:getSavedCard()
    if savedCard and savedCard ~= "" then edit_Kami.setText(savedCard) end

    inputLayout.addView(edit_Kami)
    
    local btnRow = LinearLayout(Context)
    btnRow.setOrientation(LinearLayout.HORIZONTAL)
    local rowParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
    rowParams.topMargin = Tools.dp2px(16)
    btnRow.setLayoutParams(rowParams)

    local btnActivate = MaterialButton(Context)
    local p1 = LayoutParams(0, BTN_HEIGHT)
    p1.weight = 1
    p1.rightMargin = Tools.dp2px(4)
    btnActivate.setLayoutParams(p1)
    btnActivate.setText("单码登录")
    btnActivate.setTextSize(FONT_SIZE_BODY) 
    btnActivate.setBackgroundColor(C_PRIMARY)
    btnActivate.setTextColor(C_ON_PRIM)
    btnActivate.setCornerRadius(BTN_RADIUS)
    btnActivate.setInsetTop(0)
    btnActivate.setInsetBottom(0)

    local btnUnbind = MaterialButton(Context)
    local p2 = LayoutParams(0, BTN_HEIGHT)
    p2.weight = 1
    p2.leftMargin = Tools.dp2px(4)
    btnUnbind.setLayoutParams(p2)
    btnUnbind.setText("解绑卡密")
    btnUnbind.setTextSize(FONT_SIZE_BODY) 
    btnUnbind.setTextColor(C_WARN) 
    btnUnbind.setBackgroundColor(Color.TRANSPARENT)
    btnUnbind.setCornerRadius(BTN_RADIUS)
    btnUnbind.setBackground(createStrokeBg(Color.TRANSPARENT, BTN_RADIUS, C_WARN, 1))
    btnUnbind.setInsetTop(0)
    btnUnbind.setInsetBottom(0)

    btnRow.addView(btnActivate)
    btnRow.addView(btnUnbind)

    c1_Linear.addView(txt_ActTitle)
    c1_Linear.addView(inputLayout)
    c1_Linear.addView(btnRow)
    cardActive.addView(c1_Linear)
    contentLinear.addView(cardActive)

    local cardInfo = MaterialCardView(Context)
    cardInfo.setLayoutParams(cardParams)
    cardInfo.setCardBackgroundColor(C_CARD_BG)
    cardInfo.setRadius(Tools.dp2px(10))
    cardInfo.setCardElevation(Tools.dp2px(3))
    cardInfo.setVisibility(VIEW_GONE) 

    local c2_Linear = LinearLayout(Context)
    c2_Linear.setOrientation(LinearLayout.VERTICAL)
    c2_Linear.setPadding(Tools.dp2px(14), Tools.dp2px(16), Tools.dp2px(14), Tools.dp2px(16))

    local txt_InfoTitle = TextView(Context)
    txt_InfoTitle.setText("卡密信息")
    txt_InfoTitle.setTextSize(FONT_SIZE_TITLE) 
    txt_InfoTitle.setTextColor(C_TEXT_MAIN)
    txt_InfoTitle.setTypeface(nil, 1)
    local infoTParams = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
    infoTParams.bottomMargin = Tools.dp2px(12)
    txt_InfoTitle.setLayoutParams(infoTParams)
    c2_Linear.addView(txt_InfoTitle)

    local txt_Status_Value
    local txt_Type_Value
    local txt_Time_Value

    local function addInfoRow(label, value, valueColor)
        local row = LinearLayout(Context)
        row.setOrientation(LinearLayout.HORIZONTAL)
        local rp = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
        rp.bottomMargin = Tools.dp2px(6) 
        row.setLayoutParams(rp)
        
        local l = TextView(Context)
        l.setText(label)
        l.setTextSize(FONT_SIZE_BODY) 
        l.setTextColor(C_TEXT_SUB)
        
        local v = TextView(Context)
        v.setText(value)
        v.setTextSize(FONT_SIZE_BODY) 
        v.setTextColor(valueColor or C_TEXT_MAIN)
        v.setPadding(Tools.dp2px(8), 0, 0, 0)
        
        row.addView(l)
        row.addView(v)
        c2_Linear.addView(row)
        return v
    end

    txt_Status_Value = addInfoRow("状态：", "未验证", C_PRIMARY)
    txt_Type_Value = addInfoRow("卡号：", "-")
    txt_Time_Value = addInfoRow("到期：", "-")

    cardInfo.addView(c2_Linear)
    contentLinear.addView(cardInfo)

    local cardNotice = MaterialCardView(Context)
    cardNotice.setLayoutParams(cardParams)
    cardNotice.setCardBackgroundColor(C_CARD_BG)
    cardNotice.setRadius(Tools.dp2px(10))
    cardNotice.setCardElevation(Tools.dp2px(3))
    cardNotice.setVisibility(VIEW_VISIBLE)

    local c3_Linear = LinearLayout(Context)
    c3_Linear.setOrientation(LinearLayout.VERTICAL)
    c3_Linear.setPadding(Tools.dp2px(14), Tools.dp2px(16), Tools.dp2px(14), Tools.dp2px(16))

    local c3_Header = LinearLayout(Context)
    c3_Header.setOrientation(LinearLayout.HORIZONTAL)
    c3_Header.setGravity(GRAVITY_CENTER_V)
    local headParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
    headParams.bottomMargin = Tools.dp2px(10)
    c3_Header.setLayoutParams(headParams)

    local txt_AnnTitle = TextView(Context)
    txt_AnnTitle.setText("系统公告")
    txt_AnnTitle.setTextSize(FONT_SIZE_TITLE) 
    txt_AnnTitle.setTextColor(C_TEXT_MAIN)
    txt_AnnTitle.setTypeface(nil, 1)
    local atParams = LayoutParams(0, LayoutParams.WRAP_CONTENT)
    atParams.weight = 1
    txt_AnnTitle.setLayoutParams(atParams)

    local btnRefresh = MaterialButton(Context)
    btnRefresh.setText("刷新")
    btnRefresh.setTextSize(10) 
    btnRefresh.setTextColor(C_PRIMARY)
    btnRefresh.setBackgroundColor(Color.TRANSPARENT)
    btnRefresh.setCornerRadius(Tools.dp2px(12))
    local refreshParams = LayoutParams(Tools.dp2px(50), Tools.dp2px(26))
    btnRefresh.setLayoutParams(refreshParams)
    btnRefresh.setPadding(0,0,0,0)
    btnRefresh.setBackground(createStrokeBg(Color.TRANSPARENT, Tools.dp2px(12), C_PRIMARY, 1))
    
    c3_Header.addView(txt_AnnTitle)
    c3_Header.addView(btnRefresh)

    local txt_Content = TextView(Context)
    txt_Content.setText("点击刷新获取最新公告...")
    txt_Content.setTextSize(FONT_SIZE_BODY) 
    txt_Content.setTextColor(C_TEXT_SUB)
    
    c3_Linear.addView(c3_Header)
    c3_Linear.addView(txt_Content)
    cardNotice.addView(c3_Linear)
    contentLinear.addView(cardNotice)

    local function loadNotice()
        txt_Content.setText("加载中...")
        gg.toast("正在刷新公告...")
        
        local status, res = pcall(function() 
            if luaNoticeId == "" then return {code = -1, msg = "未配置公告ID"} end
            return auth:getVariable(tonumber(luaNoticeId)) 
        end)
        
        if status then
            if res and res.code == auth:getCode() then
                local content = "暂无内容"
                if type(res.data) == "table" then
                    if res.data.content then content = res.data.content end
                elseif type(res.data) == "string" then
                    content = res.data
                else
                    content = tostring(res.data)
                end
                txt_Content.setText(content)
                gg.toast("公告刷新成功")
            else
                local errMsg = (res and res.msg) or "未知错误"
                txt_Content.setText("获取失败: " .. tostring(errMsg))
            end
        else
            txt_Content.setText("异常: " .. tostring(res))
        end
    end

    btnActivate.setOnClickListener({
        onClick = function(v)
            local card = edit_Kami.getText().toString()
            if card == "" then gg.toast("请输入卡密") return end
            gg.toast("正在连接服务器...")
            
            local res, err = auth:login(card)
            if not res then
                gg.alert("请求失败: " .. tostring(err))
            else
                if res.code == auth:getCode() then
                    if auth:verify(res.timestamp, res.signature) then
                        auth:saveCard(card)
                        gg.toast("验证成功")
                        cardInfo.setVisibility(VIEW_VISIBLE)
                        txt_Status_Value.setText("已激活")
                        txt_Type_Value.setText(card)
                        txt_Time_Value.setText(res.data.endTime)
                        local runT = {["run"] = function()
                            --content
                            gg.alert("你好")
                            --上面
                        end}
                        ThreadManager.runOnMainThread(runT)
                    else
                        gg.alert("签名验证失败")
                    end
                else
                    gg.alert("验证失败: " .. tostring(res.msg))
                end
            end
        end
    })

    btnRefresh.setOnClickListener({ onClick = function(v) loadNotice() end })
    
    btnUnbind.setOnClickListener({
        onClick = function(v)
            local card = edit_Kami.getText().toString()
            if card == "" then gg.toast("请输入卡密") return end
            
            gg.toast("正在解绑...")
            local res, err = auth:unbind(card)
            
            if not res then
                gg.alert("网络错误: " .. tostring(err))
            else
                gg.alert(tostring(res.msg))
                if res.code == auth:getCode() then
                    cardInfo.setVisibility(VIEW_GONE)
                    txt_Status_Value.setText("未验证")
                end
            end
        end
    })

    window = gg.mainTabs("用户中心", rootLayout, false, window)
    window.setIcon(luaIcon)
    window.setTitle("ArtAuth")
    window.setMinIcon(luaIcon)
end

checkVersion()
luajavaView()
gg.setVisible(false)
gg.setTabVisible(false)
gg.sleep(800)
gg.setTabVisible(true)
gg.toast("欢迎使用")
local serviceMain = import("android.ext.MainService")
local hotPoint = serviceMain.instance.hotPoint
hotPoint.hide()
