local ZhanbuExcel = require("excel.zhanbu")
local Msg = require("core.Msg")
local BagLogic = require("bag.BagLogic")
local HeroGrid = require("hero.HeroGrid")
local Util = require("common.Util")
local ObjHuman = require("core.ObjHuman")
local RoleSystemLogic = require("roleSystem.RoleSystemLogic")
local RoleSystemDefine = require("roleSystem.RoleSystemDefine")
local Lang  = require("common.Lang")
local Broadcast = require("broadcast.Broadcast")
local SysParameter = require("common.SysParameter")
local ChengjiuLogic = require("chengjiu.ChengjiuLogic")
local ChengjiuDefine = require("chengjiu.ChengjiuDefine")
local HeroExcel = require("excel.hero")
local HeroBook = require("hero.HeroBook")
local DropExchangeLogic = require("absAct.DropExchangeLogic")
local HeroGrowUp = require("absAct.HeroGrowUp")
local MengxinLogic = require("present.MengxinLogic")
local AbsZhanbuLunpanLogic = require("absAct.AbsZhanbuLunpanLogic")
local YunYingLogic = require("yunying.YunYingLogic")
--[[
    pool 卡池
    hand 手牌
    handCnt 手牌数量
    money 拥有道具数量
    lv 卡池等级
    refreshCnt 刷新次数
    ts 道具回复计时
    isGuide 是否新手引导
    handMaxCnt 手牌格子
    heartHero 心仪英雄
]]

local CARD_POOL_MAX_CNT = 5         -- 卡池英雄数量
local AUTO_GET_MONEY_MAX = 99           -- 自动回复最大道具数量
local CARD_POOL_REFRESH = 2             -- 刷新卡池所需道具数
local AUTO_GET_MONEY_TS = 300          -- 自动回复道具时间
CARD_POOL = CARD_POOL or {}

function initAfterStart()
    for i = 1,#ZhanbuExcel.pool do
        local grade = ZhanbuExcel.pool[i].grade
        local heroID = ZhanbuExcel.pool[i].heroID
        local weight = ZhanbuExcel.pool[i].weight
        CARD_POOL[grade] = CARD_POOL[grade] or {}
        CARD_POOL[grade].weight = CARD_POOL[grade].weight or 0
        CARD_POOL[grade].weight = CARD_POOL[grade].weight + ZhanbuExcel.pool[i].weight
        CARD_POOL[grade].pool = CARD_POOL[grade].pool or {}
        CARD_POOL[grade].pool[#CARD_POOL[grade].pool + 1] = {heroID,weight,i}
    end
end

local function initDB(human)
    if human.db.zhanbu == nil then
        human.db.zhanbu = {}
        local zhanbu = human.db.zhanbu
        zhanbu.hand = {}
        zhanbu.handCnt = 0
        zhanbu.handMaxCnt = 4   -- 最大手牌数为4张
        zhanbu.money = AUTO_GET_MONEY_MAX
        zhanbu.lv = 1
        zhanbu.isGuide = 1
        zhanbu.refreshCnt = 0
        zhanbu.heartHero = {}
        zhanbu.pool = {}
        refreshPool(human)
    end

    -- 老用户没有heartHero
    if human.db.zhanbu.heartHero == nil then
        human.db.zhanbu.heartHero = {}
    end

    local cjPrivilege = ChengjiuLogic.checkPrivilege(human, ChengjiuDefine.PRIVILEGE_TYPE_7)
    if cjPrivilege then
        -- 已激活宝具特权，改为5张
        human.db.zhanbu.handMaxCnt = 5
    else
        if human.db.zhanbu.hand[5] ~= nil then
            -- 线上玩家第五张手牌有牌者，默认激活
            human.db.zhanbu.handMaxCnt = 5
        else
            human.db.zhanbu.handMaxCnt = 4
        end
    end
end

function refreshPool(human)
    -- 初始化数据
    initDB(human)

    local totalWeight = 0
    local weightConfig = ZhanbuExcel.poolLv[human.db.zhanbu.lv]
    for i = 1,#weightConfig.weight do
        totalWeight = totalWeight + weightConfig.weight[i]
    end
    -- 另存一份
    local cardPoolTb = Util.copyTable(CARD_POOL)
    for i = 1,#cardPoolTb[3].pool do
        if cardPoolTb[3].pool[i][1] == human.db.zhanbu.heartHero[1] or
           cardPoolTb[3].pool[i][1] == human.db.zhanbu.heartHero[2] or
           cardPoolTb[3].pool[i][1] == human.db.zhanbu.heartHero[3] then
            local newWeight = math.floor(cardPoolTb[3].pool[i][2] * 20 / 100)
            cardPoolTb[3].weight = cardPoolTb[3].weight + newWeight
            cardPoolTb[3].pool[i][2] = cardPoolTb[3].pool[i][2] + newWeight
        end
    end 
    -- 卡池五张卡
    for i = 1,CARD_POOL_MAX_CNT do
        local randomGrade = math.random(1,totalWeight)
        -- 抽取级别 R or SR or SSR
        for j = 1,#weightConfig.weight do
            if randomGrade <= weightConfig.weight[j] then
                local randomCard = math.random(1,cardPoolTb[j].weight)
                -- 抽取卡
                for k = 1,#cardPoolTb[j].pool do
                    if randomCard <= cardPoolTb[j].pool[k][2] then
                        human.db.zhanbu.pool[i] = cardPoolTb[j].pool[k][3]
                        break
                    end
                    randomCard = randomCard - cardPoolTb[j].pool[k][2]
                end
                break
            end
            randomGrade = randomGrade - weightConfig.weight[j]
        end
    end
end

function zhanbuQuery(human)
    -- 初始化数据
    initDB(human)

    local msgRet = Msg.gc.GC_ZHANBU_QUERY
    local len = 0
    for i = 1,CARD_POOL_MAX_CNT do
        if human.db.zhanbu.pool[i] ~= nil then
            len = len + 1
            local index = human.db.zhanbu.pool[i]
            local config = ZhanbuExcel.pool[index]
            HeroGrid.makeHeroSimpleByID(msgRet.heroPool[len].heroInfo, config.heroID)
            msgRet.heroPool[len].price = config.price
            msgRet.heroPool[len].index = i
        end
    end
    msgRet.isGuide = human.db.zhanbu.isGuide or 0
    -- 新手引导，将配表中数据放到卡池中
    if human.db.zhanbu.isGuide == 1 then
        len = 0
        sysHeroList = SysParameter.getSysParameterTb(SysParameter.PARAMETER_16)
        for i = 1,#sysHeroList do
            len = len + 1
            local index = sysHeroList[i]
            local config = ZhanbuExcel.pool[index]
            human.db.zhanbu.pool[i] = index
            HeroGrid.makeHeroSimpleByID(msgRet.heroPool[len].heroInfo, config.heroID)
            msgRet.heroPool[len].price = config.price
            msgRet.heroPool[len].index = i
        end
        human.db.zhanbu.isGuide = 0
    end
    msgRet.heroPool[0] = len
    msgRet.isLock = 1
    if human.db.zhanbu.handMaxCnt == 5 then
        msgRet.isLock = 0
    end
    len = 0
    for i = 1,human.db.zhanbu.handMaxCnt do
        if human.db.zhanbu.hand[i] ~= nil then
            len = len + 1
            local index = human.db.zhanbu.hand[i]
            local config = ZhanbuExcel.pool[index]
            HeroGrid.makeHeroSimpleByID(msgRet.hand[len].heroInfo, config.heroID)
            msgRet.hand[len].price = config.price
            msgRet.hand[len].index = i
        end
    end
    msgRet.hand[0] = len

    msgRet.cardRate = Util.copyTable(ZhanbuExcel.poolLv[human.db.zhanbu.lv].weight)
    msgRet.cardRate[0] = 3

    msgRet.lv = human.db.zhanbu.lv

    msgRet.money = human.db.zhanbu.money
    msgRet.moneyMax = AUTO_GET_MONEY_MAX
    msgRet.moneyCost = 1
    msgRet.nextRecover = AUTO_GET_MONEY_TS
    msgRet.recoverTs = AUTO_GET_MONEY_TS
    if human.db.zhanbu.ts then
        local now = os.time()
        msgRet.nextRecover = human.db.zhanbu.ts + AUTO_GET_MONEY_TS - now
    end

    msgRet.hasRed = xinyiDot(human) and 1 or 0

    Msg.send(msgRet,human.fd)
end

function buyCard(human,index,heroID)
    -- 错误，数据都没有，乱搞
    if human.db.zhanbu == nil or human.db.zhanbu.pool == nil then
        return
    end

    local heroIndex = human.db.zhanbu.pool[index]
    -- 错误，数据对不上
    local config = ZhanbuExcel.pool[heroIndex]
    if not config or config.heroID ~= heroID then
        return
    end
    
    -- 判断是否可合成碎片
    local sameCnt = 0
    for i = 1,human.db.zhanbu.handMaxCnt do
        if human.db.zhanbu.hand[i] ~= nil and 
           human.db.zhanbu.hand[i] == heroIndex then
            sameCnt = sameCnt + 1
        end
    end
    
    -- 判断消耗是否够
    if human.db.zhanbu.money < config.price then
        return Broadcast.sendErr(human,Lang.ABS_ITEM_ERR)
    end
    
    local msgRet = Msg.gc.GC_ZHANBU_BUY_CARD

    -- 可合成碎片
    if sameCnt >= 2 then
        -- 扣除消耗
        human.db.zhanbu.money = human.db.zhanbu.money - config.price
        RoleSystemLogic.onDot(human,RoleSystemDefine.ROLE_SYS_ID_502)
        
        -- 自动回复计时
        if human.db.zhanbu.money < AUTO_GET_MONEY_MAX then
            human.db.zhanbu.ts = human.db.zhanbu.ts or os.time()
        end

        -- 扣除手牌
        for i = 1,human.db.zhanbu.handMaxCnt do
            if human.db.zhanbu.hand[i] ~= nil and 
               human.db.zhanbu.hand[i] == heroIndex then
                human.db.zhanbu.hand[i] = nil
                human.db.zhanbu.handCnt = human.db.zhanbu.handCnt - 1
            end
        end
        -- 从卡池中删除
        human.db.zhanbu.pool[index] = nil

        -- 增加碎片
        local randomCnt = math.random(config.chipCnt[1],config.chipCnt[2])
        local item = {}
        item[config.heroID] = randomCnt
        BagLogic.addItem(human, config.heroID, randomCnt, "zhanbu")
        if config.grade == 3 then
           DropExchangeLogic.drawSSR(human, item, 1)
        end

        local zhanbuActItemID,zhanbuActCnt = AbsZhanbuLunpanLogic.getZhanbuComposeCnt(human, config.grade)
        if zhanbuActCnt and zhanbuActCnt > 0 then
            item[zhanbuActItemID] = zhanbuActCnt
            BagLogic.addItem(human, zhanbuActItemID, zhanbuActCnt, "zhanbu")
        end
        BagLogic.sendItemGetList(human, item, "zhanbu")
        
        msgRet.index = 0
        
        HeroGrowUp.onCallback(human, HeroGrowUp.TASKTYPE3, 1)
        MengxinLogic.onCallBack(human,MengxinLogic.MX_TASK_TYPE_6,1)
    else
        -- 判断手牌是否已满
        if human.db.zhanbu.handCnt >= human.db.zhanbu.handMaxCnt then
            return Broadcast.sendErr(human,Lang.ZHANBU_HAND_CARD_FULL)
        end

        -- 扣除消耗
        human.db.zhanbu.money = human.db.zhanbu.money - config.price
        RoleSystemLogic.onDot(human,RoleSystemDefine.ROLE_SYS_ID_502)
        
        -- 自动回复计时
        if human.db.zhanbu.money < AUTO_GET_MONEY_MAX then
            human.db.zhanbu.ts = human.db.zhanbu.ts or os.time()
        end

        -- 从卡池中删除
        human.db.zhanbu.pool[index] = nil

        for i = 1,human.db.zhanbu.handMaxCnt do
            if human.db.zhanbu.hand[i] == nil then
                human.db.zhanbu.handCnt = human.db.zhanbu.handCnt + 1
                human.db.zhanbu.hand[i] = heroIndex
                msgRet.index = i
                break
            end
        end
    end
    
    -- 通知客户端购买成功
    Msg.send(msgRet,human.fd)

    -- 刷新界面
    zhanbuQuery(human)

    YunYingLogic.onCallBack(human, "onZhanBuBuyCard", config.price)

end

function sellCard(human,index,heroID)
    -- 错误，数据都没有，乱搞
    if human.db.zhanbu == nil or human.db.zhanbu.hand == nil then
        return
    end

    -- 校验卡的合法性
    local heroIndex = human.db.zhanbu.hand[index]
    local config = ZhanbuExcel.pool[heroIndex]
    if heroIndex == nil or config == nil then
        return
    end
    
    -- 删除手牌
    human.db.zhanbu.hand[index] = nil
    human.db.zhanbu.handCnt = human.db.zhanbu.handCnt - 1

    -- 增加道具
    human.db.zhanbu.money = human.db.zhanbu.money + config.price

    RoleSystemLogic.onDot(human,RoleSystemDefine.ROLE_SYS_ID_502)

    -- 自动回复计时
    if human.db.zhanbu.money >= AUTO_GET_MONEY_MAX then
        human.db.zhanbu.ts = nil
    end

    -- 通知客户端售出成功
    Msg.send(Msg.gc.GC_ZHANBU_SELL_CARD,human.fd)

    -- 刷新界面
    zhanbuQuery(human)
    YunYingLogic.onCallBack(human, "onZhanBuBuyCard", -config.price)
end

function changePos(human,posList)
    -- 错误，数据都没有，乱搞
    if human.db.zhanbu == nil or human.db.zhanbu.hand == nil then
        return
    end

    -- 检验所有位置是否合法
    local tb = Util.split(posList, "|")

    -- 长度不对，不合法
    if #tb > human.db.zhanbu.handMaxCnt then
        return
    end

    for i = 1,#tb do
        -- 不能将卡删除
        tb[i] = tonumber(tb[i])
        if tb[i] == 0 and human.db.zhanbu.hand[i] ~= nil then
            return
        end
        -- 新位置不合法
        if tb[i] > human.db.zhanbu.handMaxCnt then
            return
        end
    end

    -- 交换位置
    local dataList = Util.copyTable(human.db.zhanbu.hand)
    human.db.zhanbu.hand = {}
    for i = 1,human.db.zhanbu.handMaxCnt do
        if tb[i] ~= 0 then
            human.db.zhanbu.hand[tb[i]] = dataList[i]
        end
    end
    
    zhanbuQuery(human)
end

function refreshCardPool(human)
    -- 错误，数据都没有，乱搞
    if human.db.zhanbu == nil or human.db.zhanbu.hand == nil then
        return
    end

    -- 校验材料不够
    if human.db.zhanbu.money < CARD_POOL_REFRESH then
        return Broadcast.sendErr(human,Lang.ABS_ITEM_ERR)
    end

    -- 扣除材料
    human.db.zhanbu.money = human.db.zhanbu.money - CARD_POOL_REFRESH
    
    RoleSystemLogic.onDot(human,RoleSystemDefine.ROLE_SYS_ID_502)
    
    -- 自动回复计时
    if human.db.zhanbu.money < AUTO_GET_MONEY_MAX then
        human.db.zhanbu.ts = human.db.zhanbu.ts or os.time()
    end

    -- 刷新
    refreshPool(human)
    
    -- 刷新成功，次数+1
    onLv(human)

    -- 刷新界面
    zhanbuQuery(human)

    --占卜轮盘活动 刷新后回调
    AbsZhanbuLunpanLogic.onZhanbuRefresh(human)
    YunYingLogic.onCallBack(human, "onZhanBuBuyCard", CARD_POOL_REFRESH)
end

-- 心仪英雄
function zhanbuHeartHeroQuery(human)
    -- 错误，数据都没有，乱搞
    if human.db.zhanbu == nil or human.db.zhanbu.hand == nil then
        return
    end
    
    local msgRet = Msg.gc.GC_ZHANBU_HEART_HERO_QUERY
    for i = 1,3 do
        local heroID = human.db.zhanbu.heartHero[i]
        msgRet.heroInfo[i] = heroID or 0
    end
    msgRet.heroInfo[0] = 3
    local len = 0
    for heroID,v in pairs(human.db.heroBook) do
        local heroConfig = HeroExcel.hero[heroID]
        if heroConfig and heroConfig.grade == 4 then
            len = len + 1
            msgRet.heroList[len] = heroID
        end
    end
    msgRet.heroList[0] = len
    Msg.send(msgRet,human.fd)
end

-- 设置心仪英雄
function setHeartHero(human,heroList)
    -- 错误，数据都没有，乱搞
    if human.db.zhanbu == nil or human.db.zhanbu.hand == nil then
        return
    end

    -- 检验所有位置是否合法
    local tb = Util.split(heroList, "|")

    -- 长度不对，不合法
    local len = #tb
    if len > 3 then
        return
    end

    -- 校验英雄是否是图鉴中，是否是SSR
    for i  = 1,len do
        tb[i] = tonumber(tb[i])
        local heroID = tb[i]
        if heroID ~= 0 then
            local heroConfig = HeroExcel.hero[heroID]
            -- 不是已激活图鉴中，返回
            if not HeroBook.isGet(human, heroID,heroConfig.star) then
                return
            end

            -- 不是SSR，返回
            if heroConfig.grade ~= 4 then
                return
            end
        end
    end

    -- 保存至玩家数据
    human.db.zhanbu.heartHero = {}
    for i  = 1,len do
        if tb[i] ~= 0 then
            human.db.zhanbu.heartHero[i] = tb[i]
        end
    end

    -- 刷新心仪英雄数据
    zhanbuHeartHeroQuery(human)
end


function onLv(human)
    human.db.zhanbu.refreshCnt = human.db.zhanbu.refreshCnt + 1
    if human.db.zhanbu.refreshCnt >= ZhanbuExcel.poolLv[human.db.zhanbu.lv].cnt and 
       human.db.zhanbu.lv < #ZhanbuExcel.poolLv then
        human.db.zhanbu.lv = human.db.zhanbu.lv + 1
        local msgRet = Msg.gc.GC_ZHANBU_LVUP
        msgRet.cardRate = Util.copyTable(ZhanbuExcel.poolLv[human.db.zhanbu.lv].weight)
        msgRet.cardRate[0] = 3
        msgRet.lv = human.db.zhanbu.lv
        Msg.send(msgRet,human.fd)
    end
end

function checkRecover()
    local now = os.time()
    for _,human in pairs(ObjHuman.onlineUuid) do
        if human.db.zhanbu and human.db.zhanbu.ts then
            local ts = now - human.db.zhanbu.ts
            local cnt = math.floor(ts/AUTO_GET_MONEY_TS)
            if cnt >= 1 and human.db.zhanbu.money < AUTO_GET_MONEY_MAX then
                human.db.zhanbu.money = human.db.zhanbu.money + cnt
                human.db.zhanbu.ts = human.db.zhanbu.ts + AUTO_GET_MONEY_TS * cnt
                if human.db.zhanbu.money >= AUTO_GET_MONEY_MAX then
                    human.db.zhanbu.ts = nil
                    human.db.zhanbu.money = AUTO_GET_MONEY_MAX
                end
                RoleSystemLogic.onDot(human,RoleSystemDefine.ROLE_SYS_ID_502)
            elseif human.db.zhanbu.money >= AUTO_GET_MONEY_MAX then
                human.db.zhanbu.ts = nil
            end
        end
    end
end

function isDot(human)
    if human.db.lv < 14 then
        return
    end
    initDB(human)
    if human.db.zhanbu and human.db.zhanbu.money >= 30 then
        return true
    end

    if xinyiDot(human) then
        return true
    end

    return 
end

function updateDaily(human)
    if human.db.zhanbu == nil then
        return
    end
    human.db.zhanbu.lv = 1
    human.db.zhanbu.refreshCnt = 0
end

function addZhanbuItem(human,cnt)
    -- 初始化数据
    initDB(human)

    human.db.zhanbu.money = human.db.zhanbu.money + cnt
end

function xinyiDot(human)
    if human.db.heroBook == nil then return end
    local count = 0
    for k ,v in pairs(human.db.heroBook) do
        if type(k) == "number" then
            if HeroExcel.hero[k].grade == 4 then
                count = count + 1
            end 
        end
    end
    local xinyiCount = 0
    for i = 1, 3 do
        if human.db.zhanbu.heartHero[i] ~= nil then
            xinyiCount = xinyiCount + 1 
        end
    end
    if xinyiCount < count and xinyiCount < 3 then
        return true
    end
end