-- 答题活动
local Msg = require("core.Msg")
local AbsActExcel = require("excel.absAct")
local Grid = require("bag.Grid")
local Broadcast = require("broadcast.Broadcast")
local Lang = require("common.Lang")
local AbsActLogic = require("absAct.AbsActLogic")
local AbsActDefine = require("absAct.AbsActDefine")
local BagLogic = require("bag.BagLogic")
local HeroExcel = require("excel.hero").hero
local MailManager = require("mail.MailManager")
local MailExcel = require("excel.mail")
local Util = require("common.Util")
local ObjHuman = require("core.ObjHuman")
local Config = require("Config")
local RoleDefine = require("role.RoleDefine")
local CombatDefine = require("combat.CombatDefine")
local RoleLogic = require("role.RoleLogic")
local InnerMsg = require("core.InnerMsg")
local Lang  = require("common.Lang")
local Broadcast = require("broadcast.Broadcast")
local YunYingLogic = require("yunying.YunYingLogic")
local RoleDBLogic = require("role.RoleDBLogic")
local Log = require("common.Log")

ABS_BILLBOARD_TYPE_1 = 1        -- 高抽
ABS_BILLBOARD_TYPE_2 = 2        -- 充值
ABS_BILLBOARD_TYPE_3 = 3        -- 天命召唤
ABS_BILLBOARD_TYPE_4 = 4        -- 钻石消耗

function isOpen(human, YYInfo, funcConfig)
    local state, endTime, startTime = AbsActLogic.isStarted(human, funcConfig.funcID)
    if not state then return end
    local absAct = human.db.absAct[funcConfig.funcID]
    if absAct and absAct.dayCnt and absAct.dayCnt <= 0 and #absAct.item <= 0 then
        return false
    end
    return true, endTime, startTime
end

function isActive(human, YYInfo, funcConfig)
    return not isOpen(human, YYInfo, funcConfig)
end

function getConfigByRank(rank,mainId,actId)
    local config = AbsActExcel.billboard
    local len = #config
    for i = 1, len do
        if config[i].mainId == mainId and config[i].actId == actId then
            if config[i].maxRank <= rank and config[i].minRank >= rank then
                return config[i]
            end
        end
    end
end

function reRankDataByConfig(data,mainId,actId)
    local newTb = {}
    local listLen = data[0]
    local index = 1
    local config = AbsActExcel.billboard
    local len = #config
    local newTbIndex = 1
    local configNeedValue = {}
    local count = 0
    for i = 1,len do
        if config[i].mainId == mainId and config[i].actId == actId then
            count = count + 1
            configNeedValue[count] = configNeedValue[count] or {}
            configNeedValue[count].value = config[i].totalNeedValue 
            configNeedValue[count].rankCnt = config[i].cnt
        end
    end
    local newRank = 1
    for i = 1,count do
        if index > listLen then
            break
        end
        while true do
            if data[index].param >= configNeedValue[i].value and configNeedValue[i].rankCnt > 0 then
                newTb[newRank] = data[index]
                newRank = newRank + 1
                index = index + 1
                configNeedValue[i].rankCnt = configNeedValue[i].rankCnt - 1
            else
                newRank = newRank + configNeedValue[i].rankCnt
                break
            end
            if index > listLen then
                break
            end
        end
    end
    return newTb
end

function getAndSendMsg(human, id)
    -- 判断活动是否开起
    local state, endTime, starTime = AbsActLogic.isStarted(human, id)
    if not state then return end

    local absConfig = AbsActExcel.absActivity[id]
    if not absConfig then return end

    local absAct = human.db.absAct[id]
    if not absAct then
        return
    end

    -- 请求中心服数据
    local msgRet = InnerMsg.lw.LW_ABS_ACT_BILLBOARD_QUERY
    msgRet.uuid = human.db._id
    msgRet.actId = absConfig.actId
    msgRet.mainId = id
    InnerMsg.sendMsg(0, msgRet)
end

-- 查询回馈 充值
function middleQuery(fd, msg)
    local id = msg.mainId
     
    local newRankTb = reRankDataByConfig(msg.list,msg.mainId,msg.actId)

    local human =  ObjHuman.onlineUuid[msg.uuid]
    if human == nil then
       return
    end

    local state, endTime, starTime = AbsActLogic.isStarted(human, id)
    if not state then return end

    local absConfig = AbsActExcel.absActivity[id]
    if not absConfig then return end

    local absAct = human.db.absAct[id]
    if not absAct then
        return
    end

    local config = AbsActExcel.billboard
    local msgRet = Msg.gc.GC_ABS_BILLBOARD_QUERY
    msgRet.id = id
    msgRet.myRank.rank = 0
    msgRet.myRank.maxRank = 0
    msgRet.myRank.minRank = 0
    msgRet.myRank.roleBase[0] = 1
    RoleLogic.getRoleBase(human, msgRet.myRank.roleBase[1])
    msgRet.myRank.desc = ""
    msgRet.myRank.item[0] = 0
    msgRet.myRank.param = 0
    local listLen = msg.list[0]
	local len = 0
    for k = 1,10 do
        local db = newRankTb[k]
        if k <= 10 then
            len = len + 1
            local net= msgRet.rankList[len]
            local cfg = getConfigByRank(k,id,absConfig.actId)
            net.rank = k
            net.maxRank = 0
            net.minRank = 0
            if db then
                net.roleBase[0] = 1
		        RoleLogic.makeRoleBase(db.roleBase,net.roleBase[1])
            else
                net.roleBase[0] = 0
            end
            net.desc = Util.format(cfg.desc,cfg.totalNeedValue)
            local itemLen = #cfg.item
            for j = 1,itemLen do
                Grid.makeItem(net.item[j],cfg.item[j][1],cfg.item[j][2])
            end
            net.item[0] = itemLen
            net.param = db and db.param or 0
        end
    end
    msgRet.rankList[0] = len

    for k,db in pairs(newRankTb) do
        if db.roleBase.uuid == human.db._id then
            local cfg = getConfigByRank(k,id,absConfig.actId)
            msgRet.myRank.rank = k
            msgRet.myRank.maxRank = 0
            msgRet.myRank.minRank = 0
            msgRet.myRank.roleBase[0] = 1
		    RoleLogic.makeRoleBase(db.roleBase,msgRet.myRank.roleBase[1])
            msgRet.myRank.desc = Util.format(cfg.desc,cfg.totalNeedValue)
            local itemLen = #cfg.item
            for j = 1,itemLen do
                Grid.makeItem(msgRet.myRank.item[j],cfg.item[j][1],cfg.item[j][2])
            end
            msgRet.myRank.item[0] = itemLen
            msgRet.myRank.param = db.param
        end
    end

    len = 0
    for k, v in ipairs(config) do
        if v.mainId == id and v.actId == absConfig.actId then
            len = len + 1
            local net= msgRet.rewardList[len]
            net.rank = 0
            net.maxRank = v.maxRank
            net.minRank = v.minRank
            net.roleBase[0] = 0
            net.desc = Util.format(v.desc,v.totalNeedValue)
            net.param = 0
            local itemLen = #v.item
            for j = 1,itemLen do
                Grid.makeItem(net.item[j],v.item[j][1],v.item[j][2])
            end
            net.item[0] = itemLen
        end
    end
    msgRet.rewardList[0] = len

    Msg.send(msgRet, human.fd)
end

-- 高抽
function onDrawCard(human,funcID, parameter)
    onTouchBack(human,funcID,ABS_BILLBOARD_TYPE_1,parameter)
end

-- 天命
function onTMDrawCard(human,funcID, parameter)
    onTouchBack(human,funcID,ABS_BILLBOARD_TYPE_3,parameter)
end

-- 充值
function onCharge(human, parameter,funcID)
    onTouchBack(human,funcID,ABS_BILLBOARD_TYPE_2,parameter)
end

-- 消耗钻石
function onDecZuanshi(human,funcID,parameter)
    onTouchBack(human,funcID,ABS_BILLBOARD_TYPE_4,parameter)
end


-- 回调
function onTouchBack(human,id,type, param)
    local state, endTime, starTime = AbsActLogic.isStarted(human, id)
    if not state then return end

    local absConfig = AbsActExcel.absActivity[id]
    if not absConfig then return end

    if type ~= absConfig.param[1] then
        return
    end

    AbsActLogic.checkAbsActClean(human, id)
    local absAct = human.db.absAct[id]
    if not absAct then
        return
    end

    -- 提交充值金额
    absAct.param = absAct.param or 0
    absAct.param = absAct.param + param

    -- 更新充值榜
    local msgRet = InnerMsg.lw.LW_ABS_ACT_BILLBOARD_SET
    msgRet.roleBase = {}
    RoleLogic.makeRoleBase(human.db, msgRet.roleBase)
    msgRet.svrIndex = Config.SVR_INDEX
    msgRet.svrName = Config.SVR_NAME
    msgRet.op = {}
    msgRet.op.param = absAct.param
    msgRet.actId = absConfig.actId
    msgRet.mainId = id
    InnerMsg.sendMsg(0, msgRet)
end

function sendBillboardReward()
    if _G.is_middle == true then return end
    for k,v in pairs(AbsActExcel.absActivity) do
        if v.type == AbsActDefine.ABS_ACT_TYPE_73 then
            -- 活动开启期间不发奖励
            local state, endTime, starTime = AbsActLogic.isStarted(human, k)
            if state then return end
            print("csdasew")
            local msg = InnerMsg.lw.LW_ABS_ACT_BILLBOARD_DB
            msg.mainId = k
            msg.actId = v.turns[1]
            InnerMsg.sendMsg(0,msg)
            Log.write(Log.LOGID_DEBUG, "sendBillboardReward",msg.mainId,msg.actId)
        end
    end
end

function WL_ABS_ACT_BILLBOARD_DB_RETURN(fd,msg)
    Log.write(Log.LOGID_DEBUG, "WL_ABS_ACT_BILLBOARD_DB_RETURN true")
    local data = msg.rankDb
    local config = Util.copyTable(AbsActExcel.billboard)
    if not config then return end
    local boardLen = #data.rank2data
    local configLen = #config
    Log.write(Log.LOGID_DEBUG, "WL_ABS_ACT_BILLBOARD_DB_RETURN",boardLen)
    if boardLen > 0 then
        boardLen = math.min(boardLen, AbsActDefine.BILLBOARD_MAX_CNT)
        for i = 1, boardLen do
            local dbData = data.rank2data[i]
            local uuid = dbData and dbData.uuid

            local dcId = 0
            
            -- 选出所在档次
            for j = 1,configLen do
                if config[j].actId == msg.actId and config[j].mainId == msg.mainId then
                    if dbData.value1 >= config[j].totalNeedValue and config[j].cnt > 0 then
                        if dcId == 0 then
                            dcId = j
                        else
                            dcId = dcId > j and j or dcId
                        end
                    end
                end
            end

            if dcId ~= 0 then
                config[dcId].cnt = config[dcId].cnt - 1
                local rank = config[dcId].minRank - config[dcId].cnt
                local charDb = RoleDBLogic.getDb(uuid)
                if charDb then
             	    local mailConfig = MailExcel.mail[config[dcId].mailId]
	                local title = mailConfig.title
	                local senderName = mailConfig.senderName
                    local content = Util.format(mailConfig.content, rank)
                    MailManager.add(MailManager.SYSTEM, uuid, title, content, config[dcId].item, senderName)
                    Log.write(Log.LOGID_DEBUG, "sendMailSuccess",charDb.name)
                end
            else
                Log.write(Log.LOGID_DEBUG, "billboardReward: "..dcId.." uuid: "..uuid.." rank: "..i)
            end
        end
        Log.write(Log.LOGID_DEBUG, "billboardReward send reward success",boardLen)
    end
end

function cleanBillBoardDB()
    if _G.is_middle == true then return end
    for k,v in pairs(AbsActExcel.absActivity) do
        if v.type == AbsActDefine.ABS_ACT_TYPE_73 then
            -- 活动开启期间不发奖励
            local state, endTime, starTime = AbsActLogic.isStarted(human, k)
            if state then return end
            print("clean db success")
            local msg = InnerMsg.lw.LW_ABS_ACT_BILLBOARD_DB_CLEAN
            msg.mainId = k
            msg.actId = v.turns[1]
            InnerMsg.sendMsg(0,msg)
            Log.write(Log.LOGID_DEBUG, "cleanBillBoardDB",msg.mainId,msg.actId)
        end
    end
end

function getLeftTime(human, YInfo, funcConfig)
    local ret, endTime, startTime = AbsActLogic.isStarted(human, funcConfig.funcID)
    if ret == true then
        return endTime - os.time()
    else
        return 0
    end
end