-- 代金券投资
-- db
--[=[
    human.db.voucherInvestData = {
        getRecord = { -- 领取记录数组, 初始为nil
            idx1,
            idx2,
        }
        isBuy = nil, 是否已经充值, 充值成功后为true
        nowRound = nil, 当前轮数, 默认为1
    }
]=]--

local Util = require("common.Util")
local Lang = require("common.Lang")
local Broadcast = require("broadcast.Broadcast")
local Msg = require("core.Msg")
local Grid = require("bag.Grid")
local BagLogic = require("bag.BagLogic")
local BuyLogic = require("topup.BuyLogic")
local YunYingLogic = require("yunying.YunYingLogic")
local voucherInvestConfig = require("excel.VoucherInvest").Sheet1
local CommonDefine = require("common.CommonDefine")
local YunYingExcel = require("excel.yunying")
local VoucherShopDefine = require("voucher.VoucherShopDefine")


local LOGTYPE = "VoucherInvest" -- 日志标识
local ACT_ID = 8203 -- 活动Id
local VOUCHERSHOP_ACTID = 27


local function initData(human)
    human.db.voucherInvestData = {
        nowRound = 1,
        isBuy = false,
    }
end

local function getData(human)
    if not human.db.voucherInvestData then
        initData(human)
    end
    return human.db.voucherInvestData
end

local function updateBuyState(human, buyState)
    local voucherInvestData = getData(human)
    voucherInvestData.isBuy = buyState
end

local function updateGetRecord(human, idx)
    local voucherInvestData = getData(human)
    voucherInvestData.getRecord = voucherInvestData.getRecord or {}
    table.insert(voucherInvestData.getRecord, idx)
end

local function resetData(human, newRound)
    local voucherInvestData = getData(human)
    voucherInvestData.nowRound = newRound
    voucherInvestData.isBuy = false
    Util.initTable(voucherInvestData.getRecord)
end



-- 是否已经充值
local function isBuy(human)
    local voucherInvestData = getData(human)
    return voucherInvestData.isBuy
end

-- 通过轮数获取购买项Id
local function getBuyIdByRound(round)
    for _, v in ipairs(voucherInvestConfig) do
        if v.round and v.round == round then
            return v.buyid
        end
    end
end

-- 通过轮数获取配置Id
local function getRounCfgIdArr(round)
    local idArr = {}
    for id, v in ipairs(voucherInvestConfig) do
        if v.round and v.round == round then
            idArr[#idArr+1] = id
        end
    end

    return idArr
end

-- 获取最大轮数
local function getMaxRound()
    return voucherInvestConfig[#voucherInvestConfig].round
end

-- 奖励状态
local function getAwardState(human, id)
    local voucherInvestData = getData(human)
    local getRecordData = voucherInvestData.getRecord or {}

    if table.find(getRecordData, id) then
        return CommonDefine.COMMON_PRIZE_STATE_GET
    else
        if not isBuy(human) then
            return CommonDefine.COMMON_PRIZE_STATE_NOGET
        end

        local cfg = voucherInvestConfig[id]
        if human.db.zhandouli >= cfg.power then
            return CommonDefine.COMMON_PRIZE_STATE_CANGET
        end
    end

    return CommonDefine.COMMON_PRIZE_STATE_NOGET
end

-- 填充协议结构
local function populateAwardMsg(human, net, id, cfg, nowRound, maxRound)
    if nowRound > maxRound then
        net.state = CommonDefine.COMMON_PRIZE_STATE_GET
    else
        net.state = getAwardState(human, id)
    end

    Grid.makeItem(net.item, cfg.reward[1], cfg.reward[2])
    net.needPower = cfg.power
end

-- 主动刷新一次红点
local function updateRedDot(human)
    -- YunYingLogic.sendBanner(human)
    local config = YunYingExcel.func[ACT_ID]
    YunYingLogic.sendGroupUpdate(YYInfo[ACT_ID], human, config.panelID)

    YunYingLogic.sendIconUpdate(VOUCHERSHOP_ACTID, human)
end



function isOpen(human, YYInfo, funcConfig)
    if human.version and table.find(VoucherShopDefine.VOUCHER_NO_OPEN_TAG_ARR, human.version) then
        return false
    end

    if human.db.phpChanelID and (human.db.phpChanelID == 13 or human.db.phpChanelID == "13") then
        return false
    end

    if human.db.lv < VoucherShopDefine.VOUCHER_OPEN_LV_COND then
        return false
    end

    if not human.db.nFirstBuy or human.db.nFirstBuy ~= 1 then
        --print("[VoucherShop is open] 33333")
        return false
    end

    return true
end

function isRed(human)
    if not isOpen(human) then
        return false
    end

    if not isBuy(human) then
        return false
    end

    local voucherInvestData = getData(human)
    local nowRound = voucherInvestData.nowRound
    local maxRound = getMaxRound()
    -- 已经领完最后一轮
    if nowRound > maxRound then
        return false
    end

    local ids = getRounCfgIdArr(nowRound)
    for _, id in ipairs(ids) do
        local awardState = getAwardState(human, id)
        if awardState == CommonDefine.COMMON_PRIZE_STATE_CANGET then
            return true
        end
    end

    return false
end

function onCharge(human, nBuyID, buyNum)
    if not isOpen(human) then
        return
    end

    if isBuy(human) then
        return
    end

    local voucherInvestData = getData(human)
    local nowRound = voucherInvestData.nowRound
    local buyId = getBuyIdByRound(nowRound)
    if buyId ~= nBuyID then
        return
    end

    updateBuyState(human, true)

    updateRedDot(human)

    VoucherInvest_Query(human)
end

-- 战力更新
function onZhandouli(human)
    if not isOpen(human) then
        return
    end

    if not isBuy(human) then
        return
    end

    updateRedDot(human)
end

-- 战力更新
function PowerUpdate(human)
    if not isOpen(human) then
        return
    end

    if not isBuy(human) then
        return
    end

    updateRedDot(human)
end




-- 查询
function VoucherInvest_Query(human)
    if not isOpen(human) then
        return Broadcast.sendErr(human, Lang.YUNYING_ERR_TIME)
    end

    local voucherInvestData = getData(human)
    local nowRound = voucherInvestData.nowRound
    local maxRound = getMaxRound()
    nowRound = math.min(nowRound, maxRound)
    local buyId = getBuyIdByRound(nowRound)

    local msgRet = Msg.gc.GC_VOUCHER_INVEST_QUERY
    BuyLogic.fontBuyItem(human, msgRet.buyItem, buyId)

    msgRet.isBuy = voucherInvestData.isBuy and 1 or 0
    if voucherInvestData.nowRound > maxRound then
        msgRet.isBuy = 1
    end
    msgRet.awardArr[0] = 0
    msgRet.isEnd = 0
    msgRet.isStart = 1

    local ids = getRounCfgIdArr(nowRound)
    local cfgNum = #ids
    local len, msgOnceLen = 0, 15

    for _, id in ipairs(ids) do
        len = len + 1
        msgRet.awardArr[0] = len
        local cfg = voucherInvestConfig[id]
        populateAwardMsg(human, msgRet.awardArr[len], id, cfg, voucherInvestData.nowRound, maxRound)

        if len >= msgOnceLen then
            cfgNum = cfgNum - len
            if cfgNum <= 0 then
                msgRet.isEnd = 1
                return Msg.send(msgRet, human.fd)
            end

            Msg.send(msgRet, human.fd)
            len = 0
            msgRet.isStart = 0
        end
    end

    if len > 0 then
        msgRet.isEnd = 1
        Msg.send(msgRet, human.fd)
    end
end

-- 领奖
function VoucherInvest_Get(human)
    if not isOpen(human) then
        return Broadcast.sendErr(human, Lang.YUNYING_ERR_TIME)
    end

    if not isBuy(human) then
        return Broadcast.sendErr(human, Lang.SHARE_GROUP_GET_ERR_CNT)
    end

    local voucherInvestData = getData(human)
    local nowRound = voucherInvestData.nowRound
    local maxRound = getMaxRound()

    if nowRound > maxRound then
        return Broadcast.sendErr(human, Lang.SHARE_GROUP_GET_ERR_CNT)
    end

    local ids = getRounCfgIdArr(voucherInvestData.nowRound)
    local itemList = {}

    for _, id in ipairs(ids) do
        local cfg = voucherInvestConfig[id]
        local awardState = getAwardState(human, id)

        if awardState == CommonDefine.COMMON_PRIZE_STATE_CANGET then
            -- 更新领取记录
            updateGetRecord(human, id)

            local itemId, itemNum = cfg.reward[1], cfg.reward[2]
            itemList[itemId] = (itemList[itemId] or 0) + itemNum
        end
    end

    if not next(itemList) then
        Broadcast.sendErr(human, Lang.SHARE_GROUP_GET_ERR_CNT)
    end

    BagLogic.addItemList(human, itemList, LOGTYPE)

    -- 领完则进入下一轮
    if #voucherInvestData.getRecord == #ids then
        resetData(human, voucherInvestData.nowRound + 1)
    end

    updateRedDot(human)
    VoucherInvest_Query(human)
end