添加四位------

---
---  Author: 【苏可欣】
---  AuthorID: 【384576】
---  CreateTime: 【2025-3-7 12:03:56】
--- 【FSync】
--- 【关注我们】
---

local class = require("middleclass")
local WBElement = require("mworld/worldBaseElement")

---@class fsync_f9885cfb_ac4e_40f0_94b6_076d80e12414 : WorldBaseElement
local FsyncElement = class("fsync_f9885cfb-ac4e-40f0-94b6-076d80e12414", WBElement)

local Fsync_Example_KEY = "_Example__Key_"
local TAG = "关注我们"
local followUsPath = "980141741783441/assets/Prefabs/FollowUs.prefab"
local PageId = "activity_center_share_followus"


---@param worldElement CS.Tal.framesync.WorldElement
function FsyncElement:initialize(worldElement)
    FsyncElement.super.initialize(self, worldElement)
    ---@type PageMonitorService
    self.pageMonitorService = CourseEnv.BaseBusinessManager:GetPageMonitorService()

    --订阅KEY消息
    self:SubscribeMsgKey(Fsync_Example_KEY)

    -- -- 初始化服务
    -- self:InitService()

    -- 注册远程资源预下载
    self:RegisterDownloadUaddress(followUsPath)

    -- 初始化UI和事件
    self:InitEvent()
end

-- 初始化事件
function FsyncElement:InitEvent()
    self.gate = CourseEnv.ServicesManager.Gate
    ---前后台切换
    -- self.pauseFunction = function(pause)
    --     if not pause then
    --         if self.hasShare then -- 前后台切换时,如果已经分享过,则重新获取分享信息
    --             self:GetShareInfo(function(success)
    --                 if success then
    --                     -- self.shareInfo = shareInfo
    --                     self:SetViewByShareInfo()
    --                 end
    --             end)
    --             self.hasShare = false
    --         end
    --     end
    -- end
    -- self.commonService:DispatchAfter(1, function()
    --     if self.gate.worldController.World.OnApplicationPauseAction == nil then
    --         self.gate.worldController.World.OnApplicationPauseAction = self.pauseFunction
    --     else
    --         self.gate.worldController.World.OnApplicationPauseAction = self.gate.worldController.World
    --             .OnApplicationPauseAction + self.pauseFunction
    --     end
    -- end)
    -- 监听打开关注我们面板事件
    self.observerService:Watch("ActivityCenter_Open_Canvas", function(key, value)
        local data = value[0]
        self.show = data.show
        self.root = data.root

        if self.show == "joinUs" then
            self.isCurrIndex = true
            self:GetShareInfo(function(success)
                if success then
                    self:SetViewByShareInfo()
                end
            end)
            self:LoadingFollowUsPage()
        else
            self.isCurrIndex = false
            self:ClosePanel()
        end
    end)

    -- 监听关闭关注我们面板事件
    self.observerService:Watch("ActivityCenter_Close_Canvas", function(key, value)
        self:ClosePanel(true)
    end)
end

function FsyncElement:ClosePanel(needDestroy)
    if self.followUsPanel and self.followUsPanel.gameObject.activeSelf == true then
        self.followUsPanel.gameObject:SetActive(false)
    end
    if needDestroy and self.followUsPanel then
        self:DestroyView()
    end
end

function FsyncElement:DestroyView()
    if self.obtainBtnBtn then
        self.obtainBtnBtn.onClick:RemoveAllListeners()
    end
    if self.objRoot then
        CS.UnityEngine.GameObject.DestroyImmediate(self.objRoot)
        self.objRoot = nil
    end
    if self.followUsPanel then
        CS.UnityEngine.GameObject.DestroyImmediate(self.followUsPanel.gameObject)
        self.followUsPanel = nil
    end
    self.dialogContentRect = nil
    if self.prefab then
        ResourceManager:ReleaseObject(self.prefab)
        self.prefab = nil
    end
    self.shareInfo = nil
    self.pageMonitorService:recordPageClose(PageId)
end

-- 加载关注我们面板
function FsyncElement:LoadingFollowUsPage()
    if self.followUsPanel and self.followUsPanel.gameObject.activeSelf == false then
        self.followUsPanel.gameObject:SetActive(true)
        return
    end
    if self.followUsPanel and self.followUsPanel.gameObject.activeSelf == true then
        return
    end
    self.pageMonitorService:recordPageOpen(PageId, "关注我们")

    self:LoadRemoteUaddress(followUsPath, function(success, prefab)
        if not self.isCurrIndex then
            return
        end
        if success and prefab then
            if self.prefab then
                ResourceManager:ReleaseObject(self.prefab)
                self.prefab = nil
            end
            g_Log(TAG, "关注我们面板动态下载成功")
            local obj = GameObject.Instantiate(prefab)
            self.prefab = prefab
            self.objRoot = obj
            self.followUsPanel = obj.transform:FindChildWithName("Root")
            self.followUsPanel:SetParent(self.root)
            self.dialogContentRect = self.followUsPanel:GetComponent(typeof(CS.UnityEngine.RectTransform))
            self.followUsPanel.position = CS.UnityEngine.Vector3(0, 0, 0)
            self.followUsPanel.localScale = CS.UnityEngine.Vector3(1, 1, 1)
            self.followUsPanel.localRotation = CS.UnityEngine.Quaternion.identity
            self.dialogContentRect.anchorMax = CS.UnityEngine.Vector2(1, 1)
            self.dialogContentRect.anchorMin = CS.UnityEngine.Vector2(0, 0)
            self.dialogContentRect.localScale = CS.UnityEngine.Vector3(1, 1, 1)
            self.dialogContentRect.anchoredPosition = CS.UnityEngine.Vector2.zero
            self:InitFollowUsView()
            self.commonService:StartCoroutine(function()
                self.commonService:Yield(self.commonService:WaitUntil(function()
                    return self.shareInfo
                end))
                local param_one = "0"
                if self.shareInfo.status == 2 then
                    param_one = "1"
                end
                self:reportData("act_follow_account_show", "【曝光】关注任务页面曝光",
                    { param_one = param_one, param_two = self.shareInfo.app_id }, "0")
            end)
            self.pageMonitorService:recordPageLoadComplete(PageId)
        end
    end, true)
end

-- 初始化关注我们UI组件
function FsyncElement:InitFollowUsView()
    -- 获取Canvas和Bg
    self.bg = self.followUsPanel:Find("Bg")

    -- 获取内容面板
    self.contentPanel = self.followUsPanel:Find("ContentPanel")

    -- 获取标题
    self.title = self.contentPanel:Find("Title")

    -- 获取提示背景和标题
    self.tipBg = self.contentPanel:Find("TipBg")
    self.tipTitle = self.tipBg:Find("tipTitle")

    -- 获取内容文本区域
    self.contentText = self.tipBg:Find("ContentText")
    self.contentTextRect = self.contentText:GetComponent(typeof(CS.UnityEngine.RectTransform))

    self.diamond = self.contentText:Find("diamond")
    self.rewardNum = self.contentText:Find("rewardNum")

    -- 获取图片
    self.image = self.tipBg:Find("Image")

    -- 获取结束内容文本
    self.endContentText = self.tipBg:Find("EndContentText")
    self.endContentTextRect = self.endContentText:GetComponent(typeof(CS.UnityEngine.RectTransform))

    -- 获取Duck
    self.duck = self.contentPanel:Find("Duck")

    -- 获取获取背景及其子元素
    self.obtainBg = self.contentPanel:Find("ObtainBg")
    self.diamond0 = self.obtainBg:Find("diamond0")
    self.rewardNum = self.obtainBg:Find("rewardNum")
    self.rewardLabel = self.obtainBg:Find("rewardLabel")
    self.obtainBtn = self.obtainBg:Find("ObtainBtn")

    --获取文本
    self.contentTextText = self.contentText:GetComponent(typeof(CS.TMPro.TextMeshProUGUI))
    self.endContentTextText = self.endContentText:GetComponent(typeof(CS.TMPro.TextMeshProUGUI))
    self.contentTextRect.sizeDelta = CS.UnityEngine.Vector2(410, self.contentTextRect.sizeDelta.y)
    self.endContentTextRect.sizeDelta = CS.UnityEngine.Vector2(410, self.endContentTextRect.sizeDelta.y)
    -- 设置文本字间距为0
    if self.contentTextText then
        self.contentTextText.characterSpacing = -4
    end
    
    if self.endContentTextText then
        self.endContentTextText.characterSpacing = -4
    end



    g_Log(TAG, "contentTextText--->" .. self.contentTextText.text)

    -- self.contentTextText.text = "<color=#333333>扫码关注</color><color=#0066FF>【"..self.shareInfo.app_name.."】</color><color=#333333>服务号,成功后奖励</color>"
    -- self.endContentTextText.text = "<color=#333333>太棒啦!感谢你对</color><color=#0066FF>【"..self.shareInfo.app_name.."】</color><color=#333333>服务号的关注!</color>"


    -- 获取按钮组件
    self.obtainBtnBtn = self.obtainBtn:GetComponent(typeof(CS.UnityEngine.UI.Button))

    -- 添加按钮事件
    self:AddButtonEvents()
    self.contentTextText.text =
    "<color=#333333>关注</color><color=#0066FF>【英语天天练App】</color><color=#333333>服务号,成功后奖励</color>color=#EC42FE>5学识</color>"
    -- self.obtainBtnBtn.interactable = false
    -- 设置默认状态
    -- self:SetViewByShareInfo()
end

-- 添加按钮事件
function FsyncElement:AddButtonEvents()
    -- 添加获取按钮点击事件
    self.commonService:AddEventListener(self.obtainBtnBtn, "onClick", function()
        g_Log(TAG, "点击获取按钮0")
        if self.clickTime and os.time() - self.clickTime < 2 then
            return
        end
        g_Log(TAG, "点击获取按钮")
        self.clickTime = os.time()
        if not self.shareInfo then
            self.observerService:Fire("ABCZONE_COMMON_TOAST", { content = "未获取到关注信息,请稍后再试" })
            self:GetShareInfo(function(success)
                if success then
                    self:SetViewByShareInfo()
                end
            end)
            return
        end
        self:reportData("act_follow_account_click", "【点击】关注任务页面去完成btn", { param_one = self.shareInfo.app_id }, "0")
        self:ShareReadBookReport()
    end)
end

function FsyncElement:SetViewByShareInfo()
    self.commonService:StartCoroutine(function()
        self.commonService:Yield(self.commonService:WaitUntil(function()
            return self.shareInfo and self.objRoot
        end))
        -- 更新状态显示
        if self.shareInfo.status == 2 then
            -- 已领取状态
            self.obtainBtnBtn.interactable = false
            self.rewardNum.gameObject:SetActive(false)
            self.rewardLabel.gameObject:SetActive(true)
            -- 个人公众号
            g_Log(TAG, "shareInfo.is_personal", self.shareInfo.is_personal)
            self.contentText.gameObject:SetActive(false)
            self.endContentText.gameObject:SetActive(true)
            -- if self.shareInfo.is_personal then
            --     -- g_Log(TAG,"if0000000")
            --     self.endContentTextText.text = "<color=#333333>太棒啦!感谢你对</color><color=#0066FF>【"..self.shareInfo.app_name.."】</color><color=#333333>"..self.shareInfo.app_type.."的关注!</color>"
            -- else
            --     -- g_Log(TAG,"else0000000")
            --     self.endContentTextText.text = "<color=#333333>太棒啦!感谢你对</color><color=#0066FF>【"..self.shareInfo.app_name.."】</color><color=#333333>"..self.shareInfo.app_type.."的关注!</color>"
            -- end
            if self.shareInfo.app_type == 1 then
                self.endContentTextText.text = "<color=#333333>太棒啦!感谢你对</color><color=#0066FF>【" ..
                    self.shareInfo.app_name .. "】</color><color=#333333>公众号的关注!</color>"
            elseif self.shareInfo.app_type == 2 then
                self.endContentTextText.text = "<color=#333333>太棒啦!感谢你对</color><color=#0066FF>【" ..
                    self.shareInfo.app_name .. "】</color><color=#333333>服务号的关注!</color>"
            end
        elseif self.shareInfo.status == 1 then
            -- 可领取状态
            self.obtainBtnBtn.interactable = true
            self.rewardNum.gameObject:SetActive(true)
            self.rewardLabel.gameObject:SetActive(false)
            self.contentText.gameObject:SetActive(true)
            self.endContentText.gameObject:SetActive(false)
            -- -- 个人公众号
            -- if self.shareInfo.is_personal then
            --     self.contentTextText.text = "<color=#333333>扫码关注</color><color=#0066FF>【"..self.shareInfo.app_name.."】</color><color=#333333>"..self.shareInfo.app_type..",成功后奖励</color>"
            -- else
            --     self.contentTextText.text = "<color=#333333>扫码关注</color><color=#0066FF>【"..self.shareInfo.app_name.."】</color><color=#333333>"..self.shareInfo.app_type..",成功后奖励</color>"
            -- end
            if self.shareInfo.app_type == 1 then
                self.contentTextText.text = "<color=#333333>关注</color><color=#0066FF>【" ..
                    self.shareInfo.app_name .. "】</color><color=#333333>公众号,成功后奖励</color><color=#EC42FE>5学识</color>"
            elseif self.shareInfo.app_type == 2 then
                self.contentTextText.text = "<color=#333333>关注</color><color=#0066FF>【" ..
                    self.shareInfo.app_name .. "】</color><color=#333333>服务号,成功后奖励</color><color=#EC42FE>5学识</color>"
            end
        else
            -- 不可领取状态
            self.obtainBtnBtn.interactable = false
            self.rewardNum.gameObject:SetActive(false)
            self.rewardLabel.gameObject:SetActive(false)
        end
        -- g_Log(TAG, "self.contentTextText.preferredHeight", self.contentTextText)


        -- self.contentTextText.preferredHeight
    end)
end

function FsyncElement:ShareReadBookReport()
    -- 调用微信分享接口
    local h5Url = self.shareInfo.jump_url
    local programType = self.shareInfo.program_type
    local appletId = self.shareInfo.mini_id
    g_Log(TAG, "h5Url", h5Url)
    APIBridge.RequestAsync("app.api.open.wechatMiniProgram",
        { appletId = appletId, path = h5Url, programType = programType }, function(res)
            if res then
                g_Log(TAG, "分享微信公众号,回调--->" .. table.dump(res))
            end
        end)
    self.hasShare = true
end

---获取分享信息
function FsyncElement:GetShareInfo(callback)
    self.domain = "https://app.chuangjing.com/abc-api"
    local url = self.domain .. "/v3/follow/reward-info"
    if App.IsStudioClient then
        url = "https://yapi.xesv5.com/mock/2041/v3/follow/reward-info"
    end
    local params = {
    }
    local success = function(resp)
        if resp and resp ~= "" then
            local msg = nil
            if type(resp) == "string" then
                g_Log(TAG, "resp", resp)
                msg = self.jsonService:decode(resp)
            end
            if msg and msg.code == 0 then
                local data = msg.data
                if data and type(data) == "table" then
                    local shareInfo = {
                        app_id = data.app_id,           -- 公众号/服务号ID
                        app_name = data.app_name,       -- 公众号/服务号名称
                        app_type = data.app_type,       -- 公众号 服务号
                        is_personal = data.is_personal, -- 是否是个人公众号
                        status = data.status,           -- 奖励领取状态 1-未领取 2-已领取
                        mini_id = data.mini_id,         -- 小程序id
                        program_type = data.program_type, -- 默认下发数字0,表示正式模式
                        jump_url = data.jump_url        -- 跳转地址:为小程序跳转链接
                    }
                    self.shareInfo = shareInfo

                    g_Log(TAG, "self.shareInfo", table.dump(self.shareInfo))
                    if callback then
                        callback(true)
                    end
                end
            else
                g_Log(TAG, "获取关注信息失败:" .. (msg and msg.message or "未知错误"))
                if callback then
                    callback(false)
                end
            end
        else
            g_Log(TAG, "获取关注信息响应为空")
            if callback then
                callback(false)
            end
        end
    end
    local fail = function(err)
        g_Log(TAG, "获取关注信息请求失败:" .. (err and table.dump(err) or "未知错误"))
        if callback then
            callback(false)
        end
    end
    self:HttpRequest(url, params, success, fail)
end

function FsyncElement:HttpRequest(url, params, success, fail)
    if App.IsStudioClient then
        self.httpService:PostForm(url, params, {}, success, fail)
    else
        APIBridge.RequestAsync('api.httpclient.request', {
            ["url"] = url,
            ["headers"] = {
                ["Content-Type"] = "application/x-www-form-urlencoded"
            },
            ["data"] = params
        }, function(res)
            if res ~= nil and res.responseString ~= nil and res.isSuccessed then
                local resp = res.responseString
                success(resp)
            else
                fail(res)
            end
        end)
    end
end

---埋点方法
function FsyncElement:reportData(event, label, value, action)
    if not App.IsStudioClient then
        NextStudioComponentStatisticsAPI.ComponentStatisticsWithParam(event, "84169", "Special-Interaction", label,
            action, value)
    end
end

-- 收到/恢复IRC消息
-- @param key  订阅的消息key
-- @param value  消息集合体
-- @param isResume  是否为恢复消息
function FsyncElement:ReceiveMessage(key, value, isResume)
    -- TODO:
end

-- 发送KEY-VALUE 消息
-- @param key 自定义/协议key
-- @param body  table 消息体
function FsyncElement:SendCustomMessage(key, body)
    self:SendMessage(key, body)
end

-- 自己avatar对象创建完成
-- @param avatar 对应自己的Fsync_avatar对象
function FsyncElement:SelfAvatarCreated(avatar)

end

-- 自己avatar对象人物模型加载完成ba
-- @param avatar 对应自己的Fsync_avatar对象
function FsyncElement:SelfAvatarPrefabLoaded(avatar)

end

-- avatar对象创建完成,包含他人和自己
-- @param avatar 对应自己的Fsync_avatar对象
function FsyncElement:AvatarCreated(avatar)

end

------------------------蓝图组件相应方法---------------------------------------------
--是否是异步恢复如果是需要改成true
function FsyncElement:LogicMapIsAsyncRecorver()
    return false
end

--开始恢复方法(断线重连的时候用)
function FsyncElement:LogicMapStartRecover()
    FsyncElement.super:LogicMapStartRecover()
    --TODO
end

--结束恢复方法 (断线重连的时候用)
function FsyncElement:LogicMapEndRecover()
    FsyncElement.super:LogicMapEndRecover(self)
    --TODO
end

--所有的组件恢复完成
function FsyncElement:LogicMapAllComponentRecoverComplete()
end

--收到Trigger事件
function FsyncElement:OnReceiveTriggerEvent(interfaceId)
end

--收到GetData事件
function FsyncElement:OnReceiveGetDataEvent(interfaceId)
    return nil
end

------------------------蓝图组件相应方法End---------------------------------------------

-- 脚本释放
function FsyncElement:Exit()
    FsyncElement.super.Exit(self)

    -- 释放资源
    if self.prefab then
        ResourceManager:ReleaseObject(self.prefab)
        self.prefab = nil
    end
end

return FsyncElement