local Msg = require("core.Msg")
local PanelDefine = require("broadcast.PanelDefine")
local UnionDBLogic = require("union.UnionDBLogic")
local UnionDefine = require("union.UnionDefine")
local UnionExcel = require("excel.union")
local Grid = require("bag.Grid")
local BagLogic = require("bag.BagLogic")
local RoleLogic = require("role.RoleLogic")
local BuyLogic = require("topup.BuyLogic")
local ChatPaoMaLogic = require("chat.ChatPaoMaLogic")
local ChatUnion = require("chat.ChatUnion")
local LiLianLogic = require("dailyTask.LiLianLogic")
local UnionLivenessLogic = require("union.UnionLivenessLogic")

-- 红包记录查询
function unionRedBagQuery(human)
    -- 判断玩家是否有公会
    local union = UnionDBLogic.getUnion(human.db.unionUuid)
    if union == nil then
        return
    end

    local now = os.time()
    local msgRet = Msg.gc.GC_UNION_RED_BAG_QUERY
    
    if union.redBag == nil then
        -- 无公会红包记录
        msgRet.redBagList[0] = 0
    else
        -- 有公会红包记录
        local cnt = 0
        for k,v in pairs(union.redBag) do
            cnt = cnt + 1
            local net = msgRet.redBagList[cnt]
            local config = v.index and UnionExcel.redBag[v.index]
            net.id = k
            net.name = v.name
            net.type = v.type
            RoleLogic.makeRoleBase(v.sender,net.sender)
            net.senderPost = v.senderPost
            net.bagCnt = v.bagCnt
            net.nowCnt = v.nowCnt
            net.time = v.time - now
            -- 已过期
            if now > v.time then
                net.statu = 3
            else
                if v.record ~= nil and v.record[human.db._id] ~= nil then
                    net.statu = 2       -- 已领取
                elseif v.nowCnt >= v.bagCnt then
                    net.statu = 4       -- 已领完
                else
                    net.statu = 1       -- 可领
                end
            end
            net.desc = config and config.desc or ""
            net.item[0] = config and #config.content or 0
            for i = 1, net.item[0] do
                local itemID = config.content[i][1]
                local itemCnt = config.content[i][2]
                Grid.makeItem(net.item[i], itemID, itemCnt)
            end
        end
        msgRet.redBagList[0] = cnt
    end

    Msg.send(msgRet,human.fd)
end

-- 单个红包查询
function singleRedBag(human,id)
    -- 判断玩家是否有公会
    local union = UnionDBLogic.getUnion(human.db.unionUuid)
    if union == nil then
        return
    end
    
    -- 校验红包是否存在
    if id == nil or union.redBag[id] == nil then
        return
    end

    local msgRet = Msg.gc.GC_UNION_SINGLE_RED_BAG_QUERY

    if union.redBag[id].record == nil then
        msgRet.getRedBagList[0] = 0
    else
        local cnt = 0 
        for k,v in pairs(union.redBag[id].record) do
            cnt = cnt + 1
            local net = msgRet.getRedBagList[cnt]
            RoleLogic.getRoleBaseByUuid(k,net.role)
            net.time = v.time
            Grid.makeItem(net.item,v.itemID,v.itemCnt)
        end
        msgRet.getRedBagList[0] = cnt
    end

    Msg.send(msgRet,human.fd)
end

-- 单个红包手气最佳
function mostLucky(human,id)
    -- 判断玩家是否有公会
    local union = UnionDBLogic.getUnion(human.db.unionUuid)
    if union == nil then
        return 
    end
    
    -- 校验红包是否存在
    if id == nil or union.redBag[id] == nil then
        return
    end

    local uuid = nil
    local luckCnt = 0
    if union.redBag[id].record == nil then
        return 
    else
        for k,v in pairs(union.redBag[id].record) do
            cnt = cnt + 1
            if luckCnt == 0 or luckCnt < v.itemCnt then
                luckCnt = v.itemCnt
                uuid = k
            end
        end
    end
    return uuid,luckCnt
end

-- 发红包查询
function sendRedBagQuery(human)
    -- 判断玩家是否有公会
    local union = UnionDBLogic.getUnion(human.db.unionUuid)
    if union == nil then
        return
    end

    local msgRet = Msg.gc.GC_UNION_SEND_RED_BAG_QUERY

    local config = UnionExcel.redBag
    local len = #config 
    for i = 1,len do
        local net = msgRet.redBag[i]
        local v = config[i]
        net.type = v.type
        net.index = i
        net.name = v.name
        if human.db.redBagCnt == nil or human.db.redBagCnt[v.type] == nil then
            net.maxSendCnt = v.maxSendCnt
        else
            net.maxSendCnt = v.maxSendCnt - human.db.redBagCnt[v.type]
        end
        net.bagCnt = v.bagCnt
        net.desc = v.desc
        net.buttonTxt = v.buttonTxt
        net.rewardTxt = v.rewardTxt
        
        -- 红包发送奖励
        local rewardLen = #v.reward
        for j = 1,rewardLen do
            Grid.makeItem(net.reward[j],v.reward[j][1],v.reward[j][2])
        end
        net.reward[0] = rewardLen

        -- 红包内容
        local contentLen = #v.content
        for j = 1,contentLen do
            Grid.makeItem(net.item[j],v.content[j][1],v.content[j][2])
        end
        net.item[0] = contentLen
        -- 红包buyMsg
        BuyLogic.fontBuyItem(human, net.buyItem, v.buyID)
    end
    msgRet.redBag[0] = len

    Msg.send(msgRet,human.fd)
end

-- 发红包回调
function sendRedBagCallBack(human,index)
    -- 判断玩家是否有公会
    local union = UnionDBLogic.getUnion(human.db.unionUuid)
    if union == nil then
        return
    end
    
    local config = UnionExcel.redBag[index]

    -- 发送失败 次数上限
    if human.db.redBagCnt ~= nil 
    and human.db.redBagCnt[config.type] ~= nil 
    and human.db.redBagCnt[config.type] + config.cnt > config.maxSendCnt then
        return
    end

    -- 发送成功
    -- 写数据库
    human.db.redBagCnt = human.db.redBagCnt or {}
    human.db.redBagCnt[config.type] = human.db.redBagCnt[config.type] or 0
    human.db.redBagCnt[config.type] = human.db.redBagCnt[config.type] + config.cnt

    local roleBase = {}
    RoleLogic.getRoleBase(human,roleBase)

    local member = UnionDBLogic.getUnionMember(union, human.db._id)
    if not member then return end

    local redBagID = union.redBagID and union.redBagID + 1 or 1
    local txtID = config.type..redBagID         -- 由于用数字做id,在刷新公会信息时，会使数据库红包数据由object 变为Array ，id会被改变
    UnionDBLogic.insertSendRedBag(union._id,txtID,config.name,roleBase,member.post,config,index)
    
    -- 发送发红包者奖励
    BagLogic.addItemList(human,  config.reward, "send_redbag") 

    -- 发送公会通知
    ChatUnion.chatUnionRedBag(human)
    -- 跑马灯
    -- todo
    ChatPaoMaLogic.broadcast(human, ChatPaoMaLogic.PAOMA_TYPE_BROAD_TYPE24,PanelDefine.PANEL_ID_201)
    -- 查询
    unionRedBagQuery(human)

    local price = config.price
    LiLianLogic.onCallback(human,LiLianLogic.LILIAN_OUTID32,price)

    
    UnionLivenessLogic.touchLiveness(human,UnionDefine.UNION_LIVENESS_RED_BAG,1)
end

function getRedBag(human,id)
    -- 判断玩家是否有公会
    local union = UnionDBLogic.getUnion(human.db.unionUuid)
    if union == nil then
        return
    end

    -- 校验红包是否存在
    if id == nil or union.redBag[id] == nil then
        return
    end
    
    -- 判断是否能抢
    local now = os.time()
    local net = union.redBag[id]

    -- 已超时
    if now > union.redBag[id].time then
        return
    end

    -- 已领取
    if net.record ~= nil and net.record[human.db._id] ~= nil then
        return
    end

    -- 已领完
    if net.nowCnt >= net.bagCnt then
        return
    end

    -- 计算抢到多少
    local leftCnt = net.bagCnt - net.nowCnt
    local leftItem = net.leftCnt
    local getCnt = 0
    if leftCnt == 1 then
        getCnt = leftItem
    else
        getCnt = math.random(1,leftItem)
    end

    -- 防止某人手气太好，剩余数量不足以发剩余红包
    local temoLeftItem = leftItem - getCnt
    
    if temoLeftItem < leftCnt - 1 then
        temoLeftItem = leftCnt - 1
        getCnt = leftItem - temoLeftItem
        leftItem = temoLeftItem
    end

    -- 写数据库
    UnionDBLogic.updateRedBagRecord(human.db.unionUuid,human.db._id,id,net.itemID,getCnt)

    -- 发送物品
 --   BagLogic.addItem(human,net.itemID,getCnt,"get_redbag")
    BagLogic.cleanMomentItemList()
	BagLogic.updateMomentItem(1, net.itemID,getCnt)
	BagLogic.addMomentItemList(human, "get_redbag")
    -- 查询
    singleRedBag(human,id)

    union = UnionDBLogic.getUnion(human.db.unionUuid)
    local net = union.redBag[id]
    if net.nowCnt >= net.bagCnt then
        local mostUuid = mostLucky(human,id)
        if mostUuid then
            LiLianLogic.onCallbackByUuid(mostUuid,LiLianLogic.LILIAN_OUTID31,1)
        end
    end
end

--红包榜查询
function redBagBillboardQuery(human)
    -- 判断玩家是否有公会
    local union = UnionDBLogic.getUnion(human.db.unionUuid)
    if union == nil then
        return
    end

    local msgRet = Msg.gc.GC_UNION_RED_BAG_BILLBOARD
    
    if union.redBagRank == nil then
        msgRet.redBagRank[0] = 0
    else
        local rankTb = union.redBagRank
        table.sort(rankTb,function (a,b)
            return a.totalMoney > b.totalMoney
        end)

        local cnt = 0
        for uuid,v in pairs(rankTb) do
            cnt = cnt + 1
            local net = msgRet.redBagRank[cnt]
            local member = UnionDBLogic.getUnionMember(union, uuid)
            RoleLogic.getRoleBaseByUuid(uuid,net.role)
            net.totalMoney = v.totalMoney
            net.bagCnt = v.bagCnt
            net.post = member and member.post or UnionDefine.POST_MEMBER
        end
        msgRet.redBagRank[0] = cnt
    end

    Msg.send(msgRet,human.fd)
end

-- 每日更新红包次数
function updateDaily(human)
    UnionDBLogic.cleanRedBagCnt(human)
end
