-----------------------------------------------------------------
-- 文件名       ：  NewFirstChargeLogic.lua
-- 文件说明     ：  新首充
-- 创建时间     :   2025/1/22
-- 创建人       :   FC
-----------------------------------------------------------

local Msg = require("core.Msg")
local Util = require("common.Util")
local PresentExcel = require("excel.present")
local Grid = require("bag.Grid")
local BagLogic = require("bag.BagLogic")
local Broadcast = require("broadcast.Broadcast")
local PanelDefine = require("broadcast.PanelDefine")
local ChatPaoMaLogic = require("chat.ChatPaoMaLogic")
local YunYingLogic = require("yunying.YunYingLogic")
local SceneHandler = require("scene.Handler")
local ObjHuman = require("core.ObjHuman")
local BuyLogic = require("topup.BuyLogic")
local CommonDefine = require("common.CommonDefine")

local NEWFIRST_CHARGE_TYPE1 = 1         -- 1元
local NEWFIRST_CHARGE_TYPE2 = 2         -- 8元
local NEWFIRST_CHARGE_TYPE3 = 3         -- 18元

local tMoneyToType = 
{
    [1] = NEWFIRST_CHARGE_TYPE1,
    [8] = NEWFIRST_CHARGE_TYPE2,
    [18] = NEWFIRST_CHARGE_TYPE3,
}

local tBuyID2Speed = 
{
    [1] = 1,
    [8] = 2,
    [18] = 3,

    [6] = 1,
    [30] = 2,
    [68] = 2,
    [98] = 3,

    [50] = 1,
    [300] = 2,
    [690] = 3,
}

local NEWFIRST_DAY = 3          -- 奖励天数,策划也没配置，直接写死吧
local OPENNEWLV = 12             -- 等级9开

-- 状态
NEWFIRST_STATE_CANT_GET = 0      -- 不可领
NEWFIRST_STATE_CAT_GET = 1       -- 可领
NEWFIRST_STATE_HAD_GET = 2       -- 已领

-- local tNewFirstChargeCof = nil      -- 配置 Key = nBuyID
-- local tPrizeDataByTypeDay = nil     -- 具体奖励配置 [nType] = {[nDay] = v}




local itemID2Type = {
    [92001] = 1,
    [92002] = 2,
    [92003] = 3,

    [92004] = 4,
    [92005] = 5,
    [92006] = 6,
}


-- 是否是特殊的渠道
local function isCorrectChanel(human)
    if not human then
        return false
    end

    if human.phpChanelID == CommonDefine.CHANNEL_TAG_WX and not human.db.newFirstCharge then
        return false
    end


    return true

    -- if human.phpChanelID == CommonDefine.CHANNEL_TAG_MUZI or human.phpChanelID == CommonDefine.CHANNEL_TAG_SANLI_QQ then
    --     return true
    -- end

    -- return false
end

-- 是否使用新加的首充配置
local function isUseNewCfg(human)
    if not isCorrectChanel(human) then
        return false
    end

    local newFirstChargeData = human.db.newFirstCharge

    -- 如果原来的首充礼包一个都没购买, 就只能购买新的首充礼包
    if not newFirstChargeData or not next(newFirstChargeData) then
        return true
    end


    local subNum = 0

    -- 如果购买了老的首充, 必须全部购买且领完, 才能开启下新夹首充礼包
    for i=NEWFIRST_CHARGE_TYPE1, NEWFIRST_CHARGE_TYPE3 do
        local data = newFirstChargeData[i]
        if data then
            for k = 1, NEWFIRST_DAY do
                if data.tDayStatus[k] ~= NEWFIRST_STATE_HAD_GET then
                    return false
                end
            end

            subNum = subNum + 1
        end

        if i == NEWFIRST_CHARGE_TYPE3 and subNum > 0 and subNum < NEWFIRST_CHARGE_TYPE3 then
            return false
        end

    end

    return true
end


local function getFinalOffset(human)
    local startIdx, endIdx = NEWFIRST_CHARGE_TYPE1, NEWFIRST_CHARGE_TYPE3

    if isUseNewCfg(human) then
        startIdx = 4
        endIdx = 6
    end

    return startIdx, endIdx
end


local function getFinalType(nType, isUseNew)
    if isUseNew then
        nType = nType + 3
    end
    return nType
end




local function getNeedList(isNew)
    local startIdx, endIdx = 1, 3
    if isNew then
        startIdx, endIdx = 11, 13
    end

    local tNewFirstChargeCof = {}
    local tPrizeDataByTypeDay = {}


    -- for nID, tPrize in pairs(PresentExcel.newfirstcharge) do
    --     if type(tPrize) == "table" then
    --         --table.print_lua_table(tPrize)
    --         local nBuyID = tPrize.nBuyID
    --         tNewFirstChargeCof[nBuyID] = tPrize
    --         if tMoneyToType[tPrize.nMoney] then
    --             tNewFirstChargeCof[nBuyID].nType = tMoneyToType[tPrize.nMoney]
    --         else
    --             print("[getNeedList] 配置了不正确的金额 nMoney = "..tPrize.nMoney.." nID = "..nID)
    --         end
    --     else
    --         print("[getNeedList] tType = \n"..type(tPrize))
    --     end
    -- end

    for i = startIdx, endIdx do
        local singleCfg = PresentExcel.newfirstcharge[i]
        local nBuyID = singleCfg.nBuyID
        tNewFirstChargeCof[nBuyID] = singleCfg
        tNewFirstChargeCof[nBuyID].nType = itemID2Type[singleCfg.nBuyID]
    end


    for nID, tPrize in pairs(tNewFirstChargeCof) do
        local nType = tPrize.nType
        tPrizeDataByTypeDay[nType] = {}
        for i = 1, NEWFIRST_DAY, 1 do
            local tItem = i == 1 and tPrize.tPrize1 or ( i == 2 and tPrize.tPrize2 or tPrize.tPrize3)
            tPrizeDataByTypeDay[nType][i] = tItem
        end
    end

    return tNewFirstChargeCof, tPrizeDataByTypeDay
end

-- 初始化对应类型的DB类型数据
local function NewFirstCharge_InitDBByType(human, nType)
    if not human.db.newFirstCharge then
        human.db.newFirstCharge = {}
    end

    human.db.newFirstCharge[nType] = 
    {
        nBuyTime = 0,
        nSatus = NEWFIRST_STATE_CANT_GET,
        tDayStatus = {},
    }

    for i = 1, NEWFIRST_DAY, 1 do
        human.db.newFirstCharge[nType].tDayStatus[i] = NEWFIRST_STATE_CANT_GET
    end
end

-- 创建DB数据
local function NewFirstCharge_CreateDB(human)
    if not human then
        return
    end

    if not human.db.newFirstCharge then
        human.db.newFirstCharge = {}
    end

    -- for i = NEWFIRST_CHARGE_TYPE1, NEWFIRST_CHARGE_TYPE3, 1 do
    --     if not human.db.newFirstCharge[i] then
    --         NewFirstCharge_InitDBByType(human, i)
    --     end
    -- end


    local startIdx, endIdx = getFinalOffset(human)

    for i = startIdx, endIdx do
        if not human.db.newFirstCharge[i] then
            NewFirstCharge_InitDBByType(human, i)
        end
    end

    --table.print_lua_table(human.db.newFirstCharge)
    print("[NewFirstCharge_CreateDB] \n")
end


-- 设置对应天数领取了奖励
local function NewFirstCharge_SetPrizeStauts(human, nType, nDay, nValue)
    if not human.db.newFirstCharge or not human.db.newFirstCharge[nType] then
        return
    end

    human.db.newFirstCharge[nType].tDayStatus[nDay] = nValue
end


-- 获取对应类型对应天数奖励状态
local function NewFirstCharge_GetPrizeStauts(human, nType, nDay)
    if not human.db.newFirstCharge or not human.db.newFirstCharge[nType] then
        return NEWFIRST_STATE_CANT_GET
    end

    --table.print_lua_table(human.db.newFirstCharge[nType])
    --print("\n")
    return human.db.newFirstCharge[nType].tDayStatus[nDay]
end

-- 设置购买状态
local function NewFirstCharge_SetBuyStatus(human, nType)
    if not human.db.newFirstCharge then
        NewFirstCharge_InitDBByType(human, nType)
    end

    human.db.newFirstCharge[nType].nBuyTime = os.time()
    human.db.newFirstCharge[nType].nSatus = NEWFIRST_STATE_HAD_GET
    NewFirstCharge_SetPrizeStauts(human, nType, 1, NEWFIRST_STATE_CAT_GET)
end

-- 获取购买状态
local function NewFirstCharge_GetBuyStatus(human, nType)
    if not human.db.newFirstCharge then
        NewFirstCharge_InitDBByType(human, nType)
    end


    if not human.db.newFirstCharge[nType] then
        NewFirstCharge_InitDBByType(human, nType)
    end

    return human.db.newFirstCharge[nType].nSatus
end

-- 设置时间
local function NewFirstCharge_SetTime(human, nType, nTime)
    if not human.db.newFirstCharge then
        NewFirstCharge_InitDBByType(human, nType)
    end

    human.db.newFirstCharge[nType].nBuyTime = nTime
end

-- 获取时间
local function NewFirstCharge_GetTime(human, nType)
    if not human.db.newFirstCharge then
        NewFirstCharge_InitDBByType(human, nType)
    end

    return human.db.newFirstCharge[nType].nBuyTime
end

local function isOpenByType(human,giftType)
    if not human.db.newFirstCharge or not human.db.newFirstCharge[giftType] then 
        return true
    end

    -- 未购买，显示
    if NEWFIRST_STATE_CANT_GET == human.db.newFirstCharge[giftType].nSatus then
        return true
    end

    -- 购买了
    for nDay = 1, NEWFIRST_DAY, 1 do
       local nDayStatus = NewFirstCharge_GetPrizeStauts(human, giftType, nDay)

       -- 只要没领取，都是开启的
       if NEWFIRST_STATE_HAD_GET ~= nDayStatus then
            return true
       end
    end

    return false
end

-- 根据类型判断是否有红点
local function isRedByType(human, giftType)
    if not human.db.newFirstCharge or not human.db.newFirstCharge[giftType] then 
        return false
    end

    -- 未购买
    if NEWFIRST_STATE_CANT_GET == human.db.newFirstCharge[giftType].nSatus then
        return false
    end

    for i = 1, NEWFIRST_DAY,  1  do
        local nDayStatus = NewFirstCharge_GetPrizeStauts(human, giftType, i)
        if NEWFIRST_STATE_CAT_GET == nDayStatus then
            return true
        end
    end

    return false
end



function isOpen(human,YYInfo,funcConfig)
	if not SceneHandler.canCharge(human) then
        print("[NewFirstCharge- isOpen] 不能充值返回")
		return false
	end

    if OPENNEWLV > human.db.lv  then
        print("[NewFirstCharge- isOpen] 等级不足 不够 lv = "..human.db.lv)
        return false
    end

    -- for i = NEWFIRST_CHARGE_TYPE1, NEWFIRST_CHARGE_TYPE3, 1 do
    --     if true == isOpenByType(human,i) then
    --         print("[NewFirstCharge- isOpen] 满足条件 ")
    --         return true
    --     end
    -- end

    local startIdx, endIdx = getFinalOffset(human)
    for i = startIdx, endIdx, 1 do
        if true == isOpenByType(human,i) then
            print("[NewFirstCharge- isOpen] 满足条件 ")
            return true
        end
    end

   
    print("[NewFirstCharge- isOpen] 不满足条件 ")
    return false
end

function isRed(human,YYInfo,funcConfig)
    -- for i = NEWFIRST_CHARGE_TYPE1, NEWFIRST_CHARGE_TYPE3, 1 do
    --     if true == isRedByType(human,i) then
    --        return true
    --     end
    -- end

    local startIdx, endIdx = getFinalOffset(human)
    for i = startIdx, endIdx, 1 do
        if true == isRedByType(human,i) then
           return true
        end
    end

    return false
end

function NewFirstCharge_Query(human, nType)
    local bl = isUseNewCfg(human)
    local tAllConf, tItemConfByType = getNeedList(bl)
    local tTypeConf = nil
    local finalType = getFinalType(nType, bl)

    for _, v in pairs(tAllConf) do
        if v.nType == finalType then
            tTypeConf = v
            break
        end
    end

    if not tTypeConf then
        print("[NewFirstCharge_Query] 不存在对应类型的配置 nType = "..finalType)
        return
    end

    if not human.db.newFirstCharge then
        NewFirstCharge_CreateDB(human)
    end

    local tMsgData = Msg.gc.GC_NEW_FIRST_CHARGE_QUERY
    tMsgData.nType = nType
    tMsgData.nState = NewFirstCharge_GetBuyStatus(human, finalType)
    print("[NewFirstCharge_Query] 购买状态 nSatus = "..tMsgData.nState)
    tMsgData.nMoney = tTypeConf.nMoney
    tMsgData.tRed[0] = NEWFIRST_CHARGE_TYPE3

    local len = 0
    local startIdx, endIdx = getFinalOffset(human)

    for i = startIdx, endIdx, 1 do
        len = len + 1
        tMsgData.tRed[len] = 0
        if true == isRedByType(human, i) then
            tMsgData.tRed[len] = 1
        end
    end
    
    BuyLogic.fontBuyItem(human, tMsgData.buyItem, tTypeConf.nBuyID)

    tMsgData.list[0] = 0
    for i = 1, NEWFIRST_DAY, 1 do
        tMsgData.list[0] = tMsgData.list[0] + 1
        local tNodeData =  tMsgData.list[tMsgData.list[0]]
        tNodeData.nState = NewFirstCharge_GetPrizeStauts(human, finalType, i)
        print("[NewFirstCharge_Query] 奖励天数状态 nSatus = "..tNodeData.nState.." i = "..i)

        tNodeData.nDay = i
        tNodeData.item[0] = 0

        local tItemConf = tItemConfByType[finalType][i]

        if not tItemConf then
            print("[NewFirstCharge_Query] 居然不存在对应的奖励配置")
        else
            for _, v in ipairs(tItemConf) do
                tNodeData.item[0] = tNodeData.item[0] + 1

                Grid.makeItem(tNodeData.item[tNodeData.item[0]], v[1], v[2])
                if v[3] then
                    tNodeData.item[tNodeData.item[0]].rare = v[3]
                end
            end
        end
    end

    Msg.send(tMsgData, human.fd)
    -- print("[NewFirstCharge_Query] 发送数据成功\n")
    -- if human.db.nSpeed and _G.next(human.db.nSpeed) then
    --     table.print_lua_table(human.db.nSpeed)
    -- end
end

function NewFirstCharge_Get(human, nType)
    local bl = isUseNewCfg(human)
    local tAllConf, tItemConfByType = getNeedList(bl)
    local tTypeConf = nil
    local finalType = getFinalType(nType, bl)

    for _, v in pairs(tAllConf) do
        if v.nType == finalType then
            tTypeConf = v
            break
        end
    end

    if not tTypeConf or not tItemConfByType[finalType] then
        print("[NewFirstCharge_Get] 不存在对应类型的配置 nType = "..finalType)
        return
    end

    local nMoney = tTypeConf.nMoney

    local bChange = false
    local tItems = {}
    for nDay, value in pairs(tItemConfByType[finalType]) do
        local nStatus = NewFirstCharge_GetPrizeStauts(human, finalType, nDay)
        if NEWFIRST_STATE_CAT_GET == nStatus then
            for _, v in pairs(value) do
                table.insert(tItems, v)
            end

            if nDay == 1 then
                bChange = true
                local nIndex = tBuyID2Speed[nMoney]
                if not human.db.nSpeed then
                    human.db.nSpeed = {}
                end
                human.db.nSpeed[nIndex] = 1
            end

            NewFirstCharge_SetPrizeStauts(human, finalType, nDay, NEWFIRST_STATE_HAD_GET)
        end
    end

    if nil ~= _G.next(tItems) then
        BagLogic.addItemList(human, tItems, "shouchong")

       for k, v in pairs(funcID) do
          YunYingLogic.updateIcon(YYInfo[k], human)
          YunYingLogic.sendGroupUpdate(YYInfo[k], human, PanelDefine.PANEL_ID_3302)
          break
       end

        -- 如果购买了老的首充且全部领完， 开启新加的首充
        if isUseNewCfg(human) then
            NewFirstCharge_CreateDB(human)
            NewFirstCharge_GetPrice(human)
        end

       NewFirstCharge_Query(human, nType)

       if true == bChange then
            ObjHuman.sendHumanInfo(human)
       end

    end
end

-- 获取所有礼包价格
function NewFirstCharge_GetPrice(human)
    local bl = isUseNewCfg(human)
    local tAllConf = getNeedList(bl)

    local len = 0
    local tMsgData = Msg.gc.GC_NEW_FIRST_PRIZE_QUERY

    local tbl = {}
    for _,v in pairs(tAllConf) do
        len = len + 1
        tbl[len] = v.nMoney
    end
    tMsgData.priceList[0] = len

    table.sort(tbl)

    for k, v in ipairs(tbl) do
        tMsgData.priceList[k] = v
    end

    Msg.send(tMsgData, human.fd)
end



-- 充值回调
function onCharge(human, nBuyID)
    -- print("[NewFirstChargeLogic-onCharge] nBuyID = "..nBuyID)
    local bl = isUseNewCfg(human)
    local tConfByBuyid = getNeedList(bl)
    local isChange = false
    if tConfByBuyid[nBuyID] then
        --print("[onCharge] nType = ".. tConfByBuyid[nBuyID].nType.." nBuyID = "..nBuyID)
        NewFirstCharge_SetBuyStatus(human, tConfByBuyid[nBuyID].nType)
        isChange = true

        -- 客户端只传1 ~3
        local targetType = tConfByBuyid[nBuyID].nType
        if bl then
            targetType = targetType - 3
        end
        -- NewFirstCharge_Query(human, tConfByBuyid[nBuyID].nType)
        NewFirstCharge_Query(human, targetType)


        if IsBuyAllgift(human) then
            local CombatPosLogic = require("combat.CombatPosLogic")
            CombatPosLogic.sendAllCombatPos(human)
        end
    else
        print("[NewFirstChargeLogic-onCharge] 不存在对应的礼包id nBuyID = "..nBuyID)
        return
    end

    if isChange then
        for k, v in pairs(funcID) do
            print("[NewFirstChargeLogic - onCharge], k = "..k)
            YunYingLogic.updateIcon(YYInfo[k], human)
            break
        end
    end
end

function updateDaily(human, funcID)
    if human.db.newFirstCharge then
        local nNowTime = os.time()


        -- for i = NEWFIRST_CHARGE_TYPE1, NEWFIRST_CHARGE_TYPE3, 1 do
        --     local nBuyStatus = NewFirstCharge_GetBuyStatus(human, i)
        --     local nLastTime = NewFirstCharge_GetTime(human, i)
        --     local bIsDay = Util.isSameDayByTimes(nNowTime, nLastTime)
            
        --     -- 遍历该类型全部天数
        --     if NEWFIRST_STATE_HAD_GET == nBuyStatus and true ~= bIsDay then
        --         for nDay = 1, NEWFIRST_DAY, 1 do
        --             local nDayStatus = NewFirstCharge_GetPrizeStauts(human, i, nDay)
        --             -- 当天奖励未领取
        --             if NEWFIRST_STATE_CANT_GET == nDayStatus then
        --                 NewFirstCharge_SetPrizeStauts(human, i, nDay, NEWFIRST_STATE_CAT_GET)
        --                 NewFirstCharge_SetTime(human, i, nNowTime)
        --                 print("[NewFirstChargeLogic - updateDaily] 隔天刷新 奖励 nType = "..i.." nDay = "..nDay)
        --                 break
        --             end
        --         end
        --     end
        -- end

        local startIdx, endIdx = getFinalOffset(human)
        for i = startIdx, endIdx do
            local nBuyStatus = NewFirstCharge_GetBuyStatus(human, i)
            local nLastTime = NewFirstCharge_GetTime(human, i)
            local bIsDay = Util.isSameDayByTimes(nNowTime, nLastTime)
            
            -- 遍历该类型全部天数
            if NEWFIRST_STATE_HAD_GET == nBuyStatus and true ~= bIsDay then
                for nDay = 1, NEWFIRST_DAY, 1 do
                    local nDayStatus = NewFirstCharge_GetPrizeStauts(human, i, nDay)
                    -- 当天奖励未领取
                    if NEWFIRST_STATE_CANT_GET == nDayStatus then
                        NewFirstCharge_SetPrizeStauts(human, i, nDay, NEWFIRST_STATE_CAT_GET)
                        NewFirstCharge_SetTime(human, i, nNowTime)
                        print("[NewFirstChargeLogic - updateDaily] 隔天刷新 奖励 nType = "..i.." nDay = "..nDay)
                        break
                    end
                end
            end
        end
    end
end

-- 是否已激活首充
function isActive(human, YYInfo, funcConfig)
    return not isOpen(human, YYInfo, funcConfig)
end

-- 玩家整点
function onZero(human, funcID)
    updateDaily(human, funcID)
end

-- GM 命令
function NewFirstCharge_GMClear(human)
    human.db.newFirstCharge = nil
    print("[NewFirstCharge_GMClear] 清空完成")
end

-- 是否购买了所有的新首充礼包
function IsBuyAllgift(human)
    local newFirstChargeData = human.db.newFirstCharge
    if not newFirstChargeData or not next(newFirstChargeData) then
        return false
    end

    local bl = true
    -- 旧礼包判断,1~3为旧礼包的类型
    for i=1, 3 do
        if not newFirstChargeData[i] or newFirstChargeData[i].nBuyTime <= 0 then
            bl = false
            break
        end
    end

    if bl then
        return true
    end

    -- 新礼包判断, 4~6为新礼包的类型
    bl = true
    for i=4, 6 do
        if not newFirstChargeData[i] or newFirstChargeData[i].nBuyTime <= 0 then
            bl = false
            break
        end
    end

    return bl
end

-- function GetRemainNum(human, nBuyID)
--     local bl = isUseNewCfg(human)
--     local tConfByBuyid = getNeedList(bl)
--     if tConfByBuyid[nBuyID] then
--         local nStatus = NewFirstCharge_GetBuyStatus(human, tConfByBuyid[nBuyID].nType)
--         return NEWFIRST_STATE_CANT_GET == nStatus and 1 or 0
--     else
--         return 0
--     end
-- end