local GiftPopUI = class("GiftPopUI", BaseUI)

local GIFT_BG_NAME = {
    [PayManager.PURCHARSE_TYPE.ACT_GIFT] = {
        [PayManager.PURCHARSE_ACT_TYPE.FIRST_RECHARGE] = "assets/arts/textures/background/shop/shop_gift_bg_1.png",
        [PayManager.PURCHARSE_ACT_TYPE.BEGINNER_GIFT] = "assets/arts/textures/background/shop/shop_gift_bg_1.png",
        [PayManager.PURCHARSE_ACT_TYPE.LEVEL_UP_GIFT] = "assets/arts/textures/background/shop/shop_gift_bg_1.png",
        [PayManager.PURCHARSE_ACT_TYPE.COIN_GIFT] = "assets/arts/textures/background/shop/shop_gift_bg_1.png",
        [PayManager.PURCHARSE_ACT_TYPE.WEAPON_GIFT] = "assets/arts/textures/background/shop/shop_gift_bg_2.png",
        [PayManager.PURCHARSE_ACT_TYPE.ARMOR_GIFT] = "assets/arts/textures/background/shop/shop_gift_bg_2.png",
        [PayManager.PURCHARSE_ACT_TYPE.WEAPON_UPGRADE_GIFT] = "assets/arts/textures/background/shop/shop_gift_bg_2.png",
        [PayManager.PURCHARSE_ACT_TYPE.ARMOR_UPGRADE_GIFT] = "assets/arts/textures/background/shop/shop_gift_bg_2.png",
    },
	[PayManager.PURCHARSE_TYPE.CHAPTER_GIFT] = "assets/arts/textures/background/shop/shop_gift_bg_1.png",
    [PayManager.PURCHARSE_TYPE.GROW_UP_GIFT_NEW] = "assets/arts/textures/background/shop/shop_gift_bg_1.png",
}

local GIFT_BG_BANNER_NAME = {
    [PayManager.PURCHARSE_TYPE.ACT_GIFT] = {
        [PayManager.PURCHARSE_ACT_TYPE.FIRST_RECHARGE] = "assets/arts/textures/background/shop/shop_gift_banner_1_1.png",
        [PayManager.PURCHARSE_ACT_TYPE.BEGINNER_GIFT] = "assets/arts/textures/background/shop/shop_gift_banner_3_1.png",
        [PayManager.PURCHARSE_ACT_TYPE.LEVEL_UP_GIFT] = "assets/arts/textures/background/shop/shop_gift_banner_4_1.png",
        [PayManager.PURCHARSE_ACT_TYPE.COIN_GIFT] = "assets/arts/textures/background/shop/shop_gift_banner_6_1.png",
        [PayManager.PURCHARSE_ACT_TYPE.WEAPON_GIFT] = "assets/arts/textures/background/shop/shop_gift_banner_8_2.png",
        [PayManager.PURCHARSE_ACT_TYPE.ARMOR_GIFT] = "assets/arts/textures/background/shop/shop_gift_banner_7_2.png",
        [PayManager.PURCHARSE_ACT_TYPE.WEAPON_UPGRADE_GIFT] = "assets/arts/textures/background/shop/shop_gift_banner_8_2.png",
        [PayManager.PURCHARSE_ACT_TYPE.ARMOR_UPGRADE_GIFT] = "assets/arts/textures/background/shop/shop_gift_banner_7_2.png",
    },
	[PayManager.PURCHARSE_TYPE.CHAPTER_GIFT] = "assets/arts/textures/background/shop/shop_gift_banner_2_1.png",
    [PayManager.PURCHARSE_TYPE.GROW_UP_GIFT_NEW] = "assets/arts/textures/background/shop/shop_gift_banner_5_1.png",
}

local GIFT_TITLE_TEXT = {
    [PayManager.PURCHARSE_TYPE.ACT_GIFT] = {
        [PayManager.PURCHARSE_ACT_TYPE.FIRST_RECHARGE] = I18N.GlobalConst.SHOP_DESC_9,
        [PayManager.PURCHARSE_ACT_TYPE.BEGINNER_GIFT] = I18N.GlobalConst.SHOP_DESC_11,
        [PayManager.PURCHARSE_ACT_TYPE.LEVEL_UP_GIFT] = I18N.GlobalConst.SHOP_DESC_12,
        [PayManager.PURCHARSE_ACT_TYPE.COIN_GIFT] = I18N.GlobalConst.SHOP_DESC_14,
        [PayManager.PURCHARSE_ACT_TYPE.WEAPON_GIFT] = I18N.GlobalConst.EQUIP_DESC_24,
        [PayManager.PURCHARSE_ACT_TYPE.ARMOR_GIFT] = I18N.GlobalConst.EQUIP_DESC_25,
    },
    [PayManager.PURCHARSE_TYPE.CHAPTER_GIFT] = I18N.GlobalConst.SHOP_DESC_10,
    [PayManager.PURCHARSE_TYPE.GROW_UP_GIFT_NEW] = I18N.GlobalConst.SHOP_DESC_13,
}

local MAX_ITEM_NUM = 4

function GiftPopUI:ctor(params)
	params = params or {}

	self.actType = params.type
    if type(params.id) == "table" then
        self.actIds = params.id
        self.actId = self.actIds[1]
    else
        self.actId = params.id
    end
    self.onlySelf = params.onlySelf -- 有此标记时 关闭直接关闭界面
    self.showType = params.showType
end

function GiftPopUI:isFullScreen()
    return false
end

function GiftPopUI:getPrefabPath()
    return "assets/prefabs/ui/shop/gift_pop_ui.prefab"
end

function GiftPopUI:onLoadRootComplete()
    if not self.actType or not self.actId then
        self:closeUI()
    end

    self.uiMap = self.root:genAllChildren()
	self.uiMap["gift_pop_ui.close_btn"]:addClickListener(function()
        if self.onlySelf then
            self:closeUI()
        else
		    self:checkNextPopGiftOrClose()
        end
	end)

	self.titleTx = self.uiMap["gift_pop_ui.bg.title"]
	self.banner = self.uiMap["gift_pop_ui.bg.banner"]
	self.bg = self.uiMap["gift_pop_ui.bg"]

    self.offNode = self.uiMap["gift_pop_ui.bg.off_img"]
    self.offText = self.uiMap["gift_pop_ui.bg.off_img.text"]

    self.rewardCellList = {}
    for i = 1, MAX_ITEM_NUM do
        table.insert(self.rewardCellList, CellManager:addCellComp(self.uiMap["gift_pop_ui.bg.item_node.pop_reward_cell_" .. i], GConst.TYPEOF_LUA_CLASS.POP_REWARD_CELL))
    end
    self.itemNodeLayout =  self.uiMap["gift_pop_ui.bg.item_node"]:getComponent(GConst.TYPEOF_UNITY_CLASS.BF_HORIZONTAL_OR_VERTICAL_LAYOUT)

    self.timeNode = self.uiMap["gift_pop_ui.bg.time_node"]
    self.timeText = self.uiMap["gift_pop_ui.bg.time_node.text"]
    
	self.buyBtn = self.uiMap["gift_pop_ui.bg.buy_btn"]
	self.buyBtnTx = self.uiMap["gift_pop_ui.bg.buy_btn.text"]
	self.buyBtnIcon = self.uiMap["gift_pop_ui.bg.buy_btn.icon"]

    -- 界面切换
    self.nodeSwitch = self.uiMap["gift_pop_ui.switch_node"]
    self.btnRight = self.uiMap["gift_pop_ui.switch_node.btn_right"]
    self.btnLeft = self.uiMap["gift_pop_ui.switch_node.btn_left"]
    self.pointsRoot = self.uiMap["gift_pop_ui.switch_node.points"]:getComponent(GConst.TYPEOF_UNITY_CLASS.BF_HORIZONTAL_OR_VERTICAL_LAYOUT)
    self.points = {}
    for i = 1, 10 do
        table.insert(self.points, self.uiMap["gift_pop_ui.switch_node.points.point_" .. i])
    end

    self.btnRight:addClickListener(function()
		local idx = table.indexof(self.actIds, self.actId)
        if idx and idx + 1 <= #self.actIds then
            self.actId = self.actIds[idx + 1]
        end
        self:refresh()
	end)
    self.btnLeft:addClickListener(function()
		local idx = table.indexof(self.actIds, self.actId)
        if idx and idx - 1 > 0 then
            self.actId = self.actIds[idx - 1]
        end
        self:refresh()
	end)
	self.buyBtn:addClickListener(function()
		self:onClickGift()
	end)

    self:_bind()
	self:scheduleGlobal(function()
        self:updateTime()
	end, 1)
	self:refresh()
end

function GiftPopUI:_bind()
    self:bind(DataManager.ShopData, "isDirty", function()
        self:refresh(true)
    end)
end

function GiftPopUI:refresh(needCheck)
    if needCheck then
        -- 如果已经购买过了 则切为下一个或关闭UI 目前都是唯一礼包
        local bought = DataManager.ShopData:getGiftBoughtNum(self.actType, self.actId)
        if bought ~= self.buyCount then
            self:checkNextPopGiftOrClose()
            return
        end
    else
        self.buyCount = DataManager.ShopData:getGiftBoughtNum(self.actType, self.actId) -- 触发时该礼包的购买数量
    end

    if self.actType == PayManager.PURCHARSE_TYPE.ACT_GIFT then
        local giftType = PayManager:getGiftConfigInfo(self.actType, self.actId).type
        if giftType == PayManager.PURCHARSE_ACT_TYPE.WEAPON_UPGRADE_GIFT or giftType == PayManager.PURCHARSE_ACT_TYPE.ARMOR_UPGRADE_GIFT then
            self.titleTx:setText(DataManager.EquipData:getGiftTitle(self.actId))
        else
            self.titleTx:setText(I18N:getGlobalText(GIFT_TITLE_TEXT[self.actType][giftType]))
        end
        self.banner:setVisible(false)
        self.banner:setTexture(GIFT_BG_BANNER_NAME[self.actType][giftType], function()
            self.banner:setVisible(true)
        end)
        self.bg:setTexture(GIFT_BG_NAME[self.actType][giftType])
    else
        self.titleTx:setText(I18N:getGlobalText(GIFT_TITLE_TEXT[self.actType]))
        self.banner:setVisible(false)
        self.banner:setTexture(GIFT_BG_BANNER_NAME[self.actType], function()
            self.banner:setVisible(true)
        end)
        self.bg:setTexture(GIFT_BG_NAME[self.actType])
    end

    local cfgInfo = PayManager:getGiftConfigInfo(self.actType, self.actId)
    if cfgInfo then
        local off = cfgInfo.value or 0
        if off < 100 then -- 统一为百分比格式
            off = off * 100
        end
        if off > 0 then
            self.offNode:setVisible(true)
            self.offText:setText(tostring(off) .. "%")
        else
            self.offNode:setVisible(false)
        end
    end

	local rewards = cfgInfo.reward or {}
	for i = 1, MAX_ITEM_NUM do
        for i = 1, MAX_ITEM_NUM do
            if i <= #rewards then
                self.rewardCellList[i]:setVisible(true, 0.8)
                self.rewardCellList[i]:refresh(rewards[i].id, rewards[i].num, true)
            else
                self.rewardCellList[i]:setVisible(false)
            end
        end
	end
	self.itemNodeLayout:RefreshLayout()

    local rechargeId = cfgInfo.recharge_id
    if rechargeId then
	    self.buyBtnTx:setText(GFunc.getFormatPrice(rechargeId))
    end

    -- 对于首充礼包,有跳转商店和领取2个分支
    if self.actType == PayManager.PURCHARSE_TYPE.ACT_GIFT and self.actId == GConst.ShopConst.FIRST_RECHARGE_ID then
        local canGet = DataManager.ShopData:getHasFirstRechargeReward()
        if canGet then
            self.buyBtnTx:setText(I18N:getGlobalText(I18N.GlobalConst.BTN_CLAIM))
        else
            local hasGet = DataManager.ShopData:getHasGotFirstRechargeReward()
            if hasGet then
                self:closeUI()
            else
                self.buyBtnTx:setText(I18N:getGlobalText(I18N.GlobalConst.SHOP_DESC_15)) -- 前往商店
            end
        end
    end
    
    -- 上报
    local giftType = PayManager:getGiftType(self.actType, self.actId)
    BIReport:postPayUIShow(giftType, self.actId, self.showType)

    self:updateTime()
    self:showSwitch()
end

function GiftPopUI:updateTime()
    local hasTime = false
    -- 部分礼包有倒计时
    if self.actType == PayManager.PURCHARSE_TYPE.ACT_GIFT then
        local cfgInfo = DataManager.ShopData:getActGiftConfig()[self.actId]
        if cfgInfo then
            if cfgInfo and cfgInfo.type == PayManager.PURCHARSE_ACT_TYPE.COIN_GIFT then -- 金币礼包
                hasTime = true
                local remainTime = 0
                local triggerTime = DataManager.ShopData:getCoinGiftTriggerTime()
                remainTime = triggerTime + (cfgInfo.limit_time or 0) * 3600 - Time:getServerTime()
                if remainTime <= 0 then
                    remainTime = 0
                    self:checkNextPopGiftOrClose()
                end
                self.timeText:setText(Time:formatNumTime(remainTime))
            elseif cfgInfo and (cfgInfo.type == PayManager.PURCHARSE_ACT_TYPE.WEAPON_GIFT or cfgInfo.type == PayManager.PURCHARSE_ACT_TYPE.ARMOR_GIFT) then-- 装备礼包
                hasTime = true
                local remainTime = DataManager.ShopData:getGiftRemainTime(cfgInfo.type)
                if remainTime <= 0 then
                    remainTime = 0
                    self:checkNextPopGiftOrClose()
                end
                self.timeText:setText(Time:formatNumTime(remainTime))
            elseif cfgInfo and (cfgInfo.type == PayManager.PURCHARSE_ACT_TYPE.WEAPON_UPGRADE_GIFT or cfgInfo.type == PayManager.PURCHARSE_ACT_TYPE.ARMOR_UPGRADE_GIFT) then-- 新装备礼包
                hasTime = true
                local remainTime = DataManager.EquipData:getGiftRemainTime(self.actId)
                if remainTime <= 0 then
                    remainTime = 0
                    self:checkNextPopGiftOrClose()
                end
                self.timeText:setText(Time:formatNumTime(remainTime))
            end
        end
    elseif self.actType == PayManager.PURCHARSE_TYPE.GROW_UP_GIFT_NEW then -- 成长礼包
        hasTime = true
        local remainTime = DataManager.ShopData:getGrowUpGiftRemainTime()
        if remainTime <= 0 then
            remainTime = 0
            self:checkNextPopGiftOrClose()
        end
        self.timeText:setText(Time:formatNumTime(remainTime))
    end
    self.timeNode:setVisible(hasTime)
end

function GiftPopUI:onClickGift()
    -- 对于首充礼包,有跳转商店和领取2个分支
    if self.actType == PayManager.PURCHARSE_TYPE.ACT_GIFT and self.actId == GConst.ShopConst.FIRST_RECHARGE_ID then
        local canGet = DataManager.ShopData:getHasFirstRechargeReward()
        if canGet then
            PayManager:purchasePackage(self.actId, self.actType)
        else
            EventManager:dispatchEvent(EventManager.CUSTOM_EVENT.GO_SHOP, {page = GConst.ShopConst.PAGE_TYPE.DISCOUNT})
            self:closeUI()
        end
    else
        PayManager:purchasePackage(self.actId, self.actType)
    end
end

-- 如果还有需要显示的 则直接刷新而不是关闭本界面
function GiftPopUI:checkNextPopGiftOrClose()
    local actType, actId = DataManager.ShopData:getNextPopGiftData(self.actType, self.actId)
    if actType and actId then
        -- 更新数据
        self.actType = actType
        self.actId = actId

        self:refresh()
        -- 移除弹窗列表
        DataManager.ShopData:removePopUpGift(self.actType, self.actId)
    else
        self:closeUI()
    end
end

-- 显示切换相关内容
function GiftPopUI:showSwitch()
    if self.actIds == nil or #self.actIds <= 1 then
        self.nodeSwitch:setActive(false)
        return
    end

    self.nodeSwitch:setActive(true)
    local curIdx = table.indexof(self.actIds, self.actId)
    self.btnRight:setActive(curIdx < #self.actIds)
    self.btnLeft:setActive(curIdx > 1)

    for index, item in ipairs(self.points) do
        if self.actIds[index] then
            item:setActive(true)
            item:getComponent(GConst.TYPEOF_UNITY_CLASS.CANVAS_GROUP).alpha = self.actIds[index] == self.actId and 1 or 0.5
        else
            item:setActive(false)
        end
    end
    self.pointsRoot:RefreshLayout()
end

return GiftPopUI