

local OrderExcel = require("excel.warOrder")
local Grid = require("bag.Grid")
local ItemDefine = require("bag.ItemDefine")
local BagLogic = require("bag.BagLogic")
local BuyLogic = require("topup.BuyLogic")
local Json                   = require("common.Json")
local RoleSystemLogic = require("roleSystem.RoleSystemLogic")
local RoleSystemDefine = require("roleSystem.RoleSystemDefine")
------------------------------------------------------
-- 战令对应数据
------------------------------------------------------
local battleOrder = 1
local devilOrder = 2
local clanOrder = 3
local arenaOrder = 4
local tiantiOrder = 5
local dengjiOrder = 6
local zhaomuOrder = 7
local shenyuanOrder = 8


local passBattleExp = 5
local passDevilExp = 5
local passClanBattleExp = 10 * 3  --改为原来的3倍
local victoryArenaBattleExp = 3 * 3 --改为原来的3倍
local tiantiExp = 30
local HumanLvExp = 20           -- 等级
local zhaomuExp = 1             -- 招募
local shenyuanExp = 4           -- 深渊

local orderExpMap = {
    [battleOrder] = passBattleExp,
    [devilOrder] = passDevilExp,
    [clanOrder] = passClanBattleExp,
    [arenaOrder] = victoryArenaBattleExp,
    [tiantiOrder] = tiantiExp,
    [dengjiOrder] = HumanLvExp,
    [zhaomuOrder] = zhaomuExp,
    [shenyuanOrder] = shenyuanExp,
}

local orderNameMap = {
    [battleOrder] = "battleOrder",
    [devilOrder] = "devilOrder",
    [clanOrder] = "clanOrder",
    [arenaOrder] = "arenaOrder",
    [tiantiOrder] = "tiantiOrder",
    [dengjiOrder] = "dengjiOrder",
    [zhaomuOrder] = "zhaomuOrder",
    [shenyuanOrder] = "shenyuanOrder",
}

local GC_WARORDER_CHANGE = 53
local isRed = {}
------------------------------------------------------
-- local 函数
------------------------------------------------------
--[[
    warOrder = {
        [battleOrder] = {
            unlock = number
            exp = number
            finish = {
                [lv] = number
            }
            upgradeFinish = {}
        }
    }
]]

local function checkRewardByIdx(human,orderType,idx) 
    local orderName = orderNameMap[orderType]
    local orderData = human.db.warOrder[orderName]
    local isUpgradeOk
    if orderData.unlock ~= 0 and not orderData.upgradeFinish[idx] then 
        isUpgradeOk = true
    end
    return not orderData.finish[idx] , isUpgradeOk
end

local function checkRed(human,orderType)
    if isRed[orderType] then 
        --return 1
    end
    local orderName = orderNameMap[orderType]
    local cfg = OrderExcel[orderName]
    local orderData = human.db.warOrder[orderName]
    local nBuy = orderData.unlock

    local exp = orderData.exp
    local maxFinishIdx = 0
    for lv in ipairs(orderData.finish) do 
        if maxFinishIdx <= lv then 
            maxFinishIdx = lv
        end
    end
    local maxUpgradeFinishIdx = 0
    for lv in ipairs(orderData.upgradeFinish) do 
        if maxUpgradeFinishIdx <= lv then 
            maxUpgradeFinishIdx = lv
        end
    end

    if 1 == nBuy then
        maxFinishIdx = (maxFinishIdx > maxUpgradeFinishIdx) and maxUpgradeFinishIdx or maxFinishIdx        
    end
    
    local maxExpIdx = 0
    for _,cfg in pairs(cfg) do 
        if cfg.process <= exp and maxExpIdx <= cfg.idx then 
            maxExpIdx = cfg.idx
        end
    end
    isRed[orderType] = maxFinishIdx < maxExpIdx
    return isRed[orderType] and 1 or 0 
end

local function push2Client(human,orderType)
    local orderName = orderNameMap[orderType]
    local orderData = human.db.warOrder[orderName]
    local finish = {}
    for lv in pairs(orderData.finish) do 
        finish[#finish+1] = lv
    end
    local upgradeFinish = {}
    for lv in pairs(orderData.upgradeFinish) do 
        upgradeFinish[#upgradeFinish+1] = lv
    end
    local data = {
        orderType = orderType,
        exp = orderData.exp,
        unlock = orderData.unlock,
        finish = finish,
        upgradeFinish = upgradeFinish,
        isRed = checkRed(human,orderType),
    }
    -- 临时require 确保两个文件不会相互引用
    local newLogic = require "role.NewLogic"
    newLogic.PushClient(human,GC_WARORDER_CHANGE,data)
end

local function genBuyItem() 
    return {
        buyID = 0,
        region = "",
        cost = 0,
        icon = 0,
        name = "",
        desc = "",
        isFirst = 0,
        doubleCnt = 0,
        actDoubleCnt = 0,
        buyCnt = 0,
        vipExp = 0,
        zhekou = 0,
        yuanjia = 0,
    }
end

--某个战令奖励是否已经领完, 返回false表示没有,true表示已经领完
local function isGetAllAward(human,orderType)
    local warOrder = human.db.warOrder
    if not warOrder then
        return false
    end

    local orderName = orderNameMap[orderType]
    local cfg = OrderExcel[orderName]
    local orderData = warOrder[orderName]
    if not cfg or not orderData then
        return false
    end

    local allNum = #cfg
    local isGetAll = true

    --普通奖励
    local commonNum = 0
    local commonRecord = orderData.finish
    for k in pairs(commonRecord or {}) do
        commonNum = commonNum + 1
    end

    if commonNum < allNum then
        isGetAll = false
        return isGetAll
    end

    --进阶奖励
    local upgradeNum = 0
    local upgradeRecord = orderData.upgradeFinish
    for k in pairs(upgradeRecord or {}) do
        upgradeNum = upgradeNum + 1
    end
    if upgradeNum < allNum then
        isGetAll = false
    end

    return isGetAll
end

------------------------------------------------------
-- 对外暴露接口
------------------------------------------------------

function isDot(human)
    local isDot = false
    for orderType in pairs(orderNameMap) do 
        if checkRed(human,orderType) == 1 then 
            isDot = true
            break
        end
    end
    return isDot
end

--判断是否显示入口, 返回true表示显示, false表示不显示, 领完四个类型战令的奖励就关闭
function isOpen(human)
    for orderType in pairs(orderNameMap) do
        if not isGetAllAward(human,orderType) then
            return true
        end
    end
    return false
end


function warOrderInfo(human,orderType)
    local orderName = orderNameMap[orderType]
    local cfg = OrderExcel[orderName]
    local langCfg = OrderExcel.desc
    local orderData = human.db.warOrder[orderName]
    if not cfg or not orderData then
        return
    end
    -- 获取配置表相关数据， 发送给客户端
   
    local normal = {}
    for _,v in pairs(cfg) do 
        local cfgData  = {
            idx = v.idx,
            process = v.process,
        }
        local content = {}
        local upgradeContent = {}
        if #v.content ~= 0 then 
            for _,item in ipairs(v.content) do 
                local data = {
                    getway = {},
                    suipian = {},
                    equip = {},
                    fuwen = {},
                }
                if not ItemDefine.isEquip(item[1]) then
                    Grid.makeItem(data, item[1], item[2])
                end
                content[#content + 1] = data
            end
            
        end
        if #v.upgradeContent ~= 0 then   
            for _,item in ipairs(v.upgradeContent) do 
                local data = {
                    getway = {},
                    suipian = {},
                    equip = {},
                    fuwen = {},
                }
                if not ItemDefine.isEquip(item[1]) then
                    Grid.makeItem(data, item[1], item[2])
                end
                upgradeContent[#upgradeContent + 1] = data
            end
        end
        cfgData.content = content
        cfgData.upgradeContent = upgradeContent
        normal[#normal+1] = cfgData
    end
    local language = ""
    local buyItem = genBuyItem()
    local buyId
    for _,v in pairs(langCfg) do 
        if v.type == orderType then 
            language = v.desc
            buyId = v.buyId
            break
        end
    end
    if buyId then 
        BuyLogic.fontBuyItem(human,buyItem,buyId)
    end
    -------------------
    local finish = {}
    for lv in pairs(orderData.finish) do 
        finish[#finish+1] = lv
    end
    local upgradeFinish = {}
    for lv in pairs(orderData.upgradeFinish) do 
        upgradeFinish[#upgradeFinish+1] = lv
    end
    return {
        orderType = orderType,
        normal = normal,
        language = language,
        buyItem = buyItem,
        -- 自身的进度问题
        exp = orderData.exp,
        unlock = orderData.unlock,
        finish = finish,
        upgradeFinish = upgradeFinish,
    }
end

function warOrderReward(human,orderType)
    local orderName = orderNameMap[orderType]
    local cfg = OrderExcel[orderName]
    local orderData = human.db.warOrder[orderName]
    if not cfg or not orderData then 
        return
    end
   
    local process = orderData.exp
    local itemMap = {}
    --local finish_copy = table.copy(orderData.finish)
    --local upgrade_finish_copy = table.copy(orderData.upgradeFinish)
    local allAwardCnt = 0
    for _,v in pairs(cfg) do
        allAwardCnt = allAwardCnt + 1
        if  process >= v.process then
            local isOk,isUpgradeOk = checkRewardByIdx(human,orderType,v.idx)
            if isOk then 
                for _,item in ipairs(v.content) do 
                    itemMap[item[1]] = itemMap[item[1]] or 0
                    itemMap[item[1]] = itemMap[item[1]] + item[2]
                end
                orderData.finish[v.idx] = 0
            end
            if isUpgradeOk then 
                for _,item in ipairs(v.upgradeContent) do 
                    itemMap[item[1]] = itemMap[item[1]] or 0
                    itemMap[item[1]] = itemMap[item[1]] + item[2]
                end
                orderData.upgradeFinish[v.idx] = 0
            end
        end
    end
    -- 检查是否有可领取的item
    if not next(itemMap) then 
        return
    end
    local itemList = {}
    for id,count in pairs(itemMap) do 
        itemList[#itemList+1] = {
            id,count
        }
    end
    BagLogic.addItemList(human,itemList,"war_order_get")
    -- 同步数据
    --orderData.finish = finish_copy
    --orderData.upgradeFinish = upgrade_finish_copy

    ------------------------------------------------
    local finish = {}
    for lv in pairs(orderData.finish) do 
        finish[#finish+1] = lv
    end
    local upgradeFinish = {}
    for lv in pairs(orderData.upgradeFinish) do 
        upgradeFinish[#upgradeFinish+1] = lv
    end
    isRed[orderType] = nil
    -- 通知外层红点取消
    RoleSystemLogic.onDot(human, RoleSystemDefine.ROLE_SYS_ID_2005)

    --判断是否领完奖励要关闭入口显示了
    if #finish >= allAwardCnt and #upgradeFinish >= allAwardCnt then
        RoleSystemLogic.isClose(human, RoleSystemDefine.ROLE_SYS_ID_2005)
    end
    
    return {
        orderType = orderType,
        exp = orderData.exp,
        unlock = orderData.unlock,
        finish = finish,
        upgradeFinish = upgradeFinish,
        isRed = 0,
    }
end

-- 解锁战令
function warOrderUnlock(human,orderType)
    local orderName = orderNameMap[orderType]
    local orderData = human.db.warOrder[orderName]
    if not orderData then 
        print(" invalid orderType,not found data ")
        return
    end
    -- 已经解锁
    if orderData.unlock ~= 0 then 
        print(" invalid op, warOrder unlocked ")
        return 
    end
    orderData.unlock = 1
    push2Client(human,orderType)
    return true
end

-- 触发战令增加经验
function trigger(human,orderType,cnt)
    cnt = cnt or 1 --默认触发一次
    local orderName = orderNameMap[orderType]
    local orderData = human.db.warOrder[orderName]
    local exp = orderExpMap[orderType]
    orderData.exp =  orderData.exp + (exp * cnt)
    -- 是否需要推送？
    push2Client(human,orderType)
    -- 通知外层红点变更
    RoleSystemLogic.onDot(human, RoleSystemDefine.ROLE_SYS_ID_2005)
end

function getWarOrderInfo(human,orderType,net) 
    local orderName = orderNameMap[orderType]
    local orderData = human.db.warOrder[orderName]

    if orderType == dengjiOrder and not human.db.warSetLvOrder then
        human.db.warSetLvOrder = true
        local nNowLv = human.db.lv
        if nNowLv > 1 then
            orderData.exp = nNowLv * orderExpMap[orderType]
        end
    end

    if orderType == shenyuanOrder and not human.db.warSetshenyuanOrder then
        human.db.warSetshenyuanOrder = true
        if human.db.lianyu and human.db.lianyu.maxLv and human.db.lianyu.maxLv > 1 then
            orderData.exp = human.db.lianyu.maxLv * orderExpMap[orderType]
        end
    end

    net.type = orderType
    net.exp =  orderData.exp
    net.unlock = orderData.unlock
    net.isRed = checkRed(human,orderType)

    local finishIdx = 0
    for lv in pairs(orderData.finish) do 
        finishIdx = finishIdx + 1
        net.finish[finishIdx] = lv
    end
    net.finish[0] = finishIdx
    local upgradeFinishIdx = 0
    for lv in pairs(orderData.upgradeFinish) do 
        upgradeFinishIdx = upgradeFinishIdx + 1
        net.upgradeFinish[upgradeFinishIdx] = lv
    end
    net.upgradeFinish[0] = upgradeFinishIdx
end

-- function GetRemainNum(human, nBuyID)
--     local nType = nil
--     for _, v in ipairs(OrderExcel.desc) do
--         if v.buyId == nBuyID then
--             nType = v.type
--             break
--         end
--     end

--     if not nType then
--         return 0
--     end

--     local orderName = orderNameMap[nType]
--     local orderData = human.db.warOrder[orderName]
--     if not orderData then 
--         return 1
--     end
--     -- 已经解锁
--     if orderData.unlock ~= 0 then 
--         return 0
--     else 
--         return 1
--     end
-- end