
----- 次元魔珠


--[[
    db.mozhu = {
        time  =  1, 
        hurtMax = 1,
        hurt = 1,
        tzCnt = 1,
        restCnt = 1,

    }
]]
local InnerMsg = require("core.InnerMsg")
local Msg = require("core.Msg")
local ObjHuman = require("core.ObjHuman")
local Util = require("common.Util")
local Config = require("Config")
local Lang = require("common.Lang")
local Broadcast = require("broadcast.Broadcast")
local CombatLogic = require("combat.CombatLogic")
local CombatPosLogic = require("combat.CombatPosLogic")
local CombatDefine = require("combat.CombatDefine")
local Grid = require("bag.Grid")
local BagLogic = require("bag.BagLogic")
local MailDefine = require("mail.MailIdDefine")
local MailExcel = require("excel.mail")
local MailManager = require("mail.MailManager")
local MoZhuExcel = require("excel.mozhu")
local CombatImpl = require("combat.CombatImpl")
local BeSkill = require("combat.BeSkill")
local MonsterExcel = require("excel.monster")
local SkillExcel = require("excel.skill").skill
local UnionDBLogic = require("union.UnionDBLogic")
local RoleDefine = require("role.RoleDefine")
local RoleLogic = require("role.RoleLogic")
local UnionDefine = require("union.UnionDefine")
local ChatUnion = require("chat.ChatUnion")
local JjcActLogic = require("jjc.JjcActLogic")
local DragonNestLogic = require("copy.DragonNestLogic")
local HeroLogic = require("hero.HeroLogic")
local MozhuMiddleLogic = require("mozhu.MoZhuMiddleLogic")
local YunYingLogic = require("yunying.YunYingLogic")
local WeekTaskLogic = require("dailyTask.WeekTaskLogic")
local TriggerDefine = require("trigger.TriggerDefine")
local TriggerLogic = require("trigger.TriggerLogic")

MOZHU_OPEN_DAY = {[1]= 1,[2] = 1,[3] = 1,[4] = 1,[5] = 1,[6] = 1, [7] = 1}
MOZHU_OPEN_DAY_2 = {1, 7}
MOZHU_DAY_TIME = 24 * 60 * 60
MOZHU_END_TIME = 22 * 60 * 60
MOZHU_TIAOZHAN_CNT = 3   -- 魔蛛挑战次数
MOZHU_RESET_CNT = 3      -- 魔蛛最多重置次数
MOZHU_CITIAO = MOZHU_CITIAO or  nil
MOZHU_CITIAO_TIME = MOZHU_CITIAO_TIME or nil

MOZHU_ROLE_RANK_TYPE_1  = 1    --- 玩家排名
MOZHU_UNION_RANK_TYPE_2 = 2    --- 公会排名

function initHuman(human)
    if human.db.mozhu then return end
    human.db.mozhu = {}
    human.db.mozhu.time = os.time()
    human.db.mozhu.hurtMax = 0
    human.db.mozhu.hurt = 0
    human.db.mozhu.tzCnt = 0
    human.db.mozhu.restCnt = 0
end

function updateDaily(human)
    if not human.db.mozhu then return end
    if Util.isSameDay(human.db.mozhu.time) then
        return 
    end
    human.db.mozhu.time = os.time()
    human.db.mozhu.hurtMax = 0
    human.db.mozhu.hurt = 0
    human.db.mozhu.tzCnt = 0
    human.db.mozhu.restCnt = 0
    human.db.mozhu.unionGet = nil
    human.db.mozhu.onHero = nil
    human.db.mozhu.read  = nil

end

function isOpen()
    local week = Util.getWeekDay()
    if MOZHU_OPEN_DAY[week] then
        return true 
    end
    return false
end

function getActTime()
    local now = os.time()
    local nowWeek = Util.getWeekDay(now)

    if MOZHU_OPEN_DAY[nowWeek] then
        local startTime = Util.getDayStartTime(now)
        return startTime + 1,   startTime + MOZHU_END_TIME
    elseif nowWeek < MOZHU_OPEN_DAY_2[1] then
        local openTime = now + MOZHU_DAY_TIME * (MOZHU_OPEN_DAY_2[1] - nowWeek)
        local startTime = Util.getDayStartTime(openTime)
        return startTime + 1,   startTime + MOZHU_END_TIME
    elseif nowWeek < MOZHU_OPEN_DAY_2[2] then
        local openTime = now + MOZHU_DAY_TIME * (MOZHU_OPEN_DAY_2[2] - nowWeek)
        local startTime = Util.getDayStartTime(openTime)
        return startTime + 1,   startTime + MOZHU_END_TIME
    elseif nowWeek > MOZHU_OPEN_DAY_2[2] then
        -- 暂时不会发生 防止后续策划修改时间
        local surDay = 7 - nowWeek + MOZHU_OPEN_DAY_2[1]
        local openTime = now + MOZHU_DAY_TIME * surDay
        local startTime = Util.getDayStartTime(openTime)
        return startTime + 1,   startTime + MOZHU_END_TIME
    end
end

function getActState(human)
 --   if not human.db.unionUuid or human.db.unionUuid == "" then
 --       return  JjcActLogic.STATE_NOOPEN, 0
 --   end
    local now = os.time()
    local startTime, endTime = getActTime()
    if now < startTime then
        return JjcActLogic.STATE_READY, startTime - now
    elseif now >= startTime and now < endTime then
        return JjcActLogic.STATE_START, endTime - now
    end
    return JjcActLogic.STATE_NOOPEN, 0
end
-----------------------font  net -----------------


local function fontRoleNet(msgRet, msg)
    
    local len = 0
    for rank, db in ipairs(msg.roleRank) do
        len = len + 1
        local net =  msgRet.roleList[len]
        net.rank = rank
        net.hurt = db.hurt
        RoleLogic.makeRoleBase(db.roleBase, net.roleBase)
        net.roleBase.name = net.roleBase.name or ""
        net.roleBase.serverName = db.roleBase.svrName
    end
    msgRet.roleList[0] = len

end

local function fontUnionNet(msgRet, msg)
    local len = 0
    for rank, db in ipairs(msg.unionRank) do
        len = len + 1
        local net =  msgRet.unionList[len]
        net.rank = rank
        net.unionUuid = db.unionUuid
        net.name = db.unionBase.unionName or ""
        net.bannerID = db.unionBase.bannerID or 0
        net.hurt = db.hurt
        net.svrName = db.unionBase.svrName or "S0"
       
    end
    msgRet.unionList[0] = len
end

local function fontMyRole(msgRet, msg)
    msgRet.myRole[0] = 0
    if msg.info and msg.info.myRank and msg.info.myRank.hurt then
        local net =  msgRet.myRole[1]
        net.rank = msg.info.myRank.rank
        net.hurt = msg.info.myRank.hurt
        RoleLogic.makeRoleBase(msg.info.myRank.roleBase, net.roleBase)
        msgRet.myRole[0] = 1
    end
end

local function fontMyUnion(msgRet, msg)
    msgRet.myUnion[0] = 0
    if msg.info and msg.info.myUnion and msg.info.myUnion.hurt then
        local net =  msgRet.myUnion[1]
        net.rank = msg.info.myUnion.rank
        net.unionUuid = msg.info.myUnion.unionUuid
        net.name = msg.info.myUnion.unionBase.unionName or ""
        net.bannerID = msg.info.myUnion.unionBase.bannerID or 0
        net.hurt = msg.info.myUnion.hurt
        net.svrName = msg.info.myUnion.unionBase.svrName
        msgRet.myUnion[0] = 1
    end
end

local function fontCiTiao(msgRet, list)
    local len = 0
    for id in pairs(list.citiao) do
        len = len + 1
        local config = MoZhuExcel.citiao[id]
        local net = msgRet.ciTiao[len]
        net.id   = id
        net.name = config.citiao or ""
        net.desc = config.miaoshu
    end
    msgRet.ciTiao[0] = len

    if not MOZHU_CITIAO_TIME or MOZHU_CITIAO_TIME ~= list.citiaoTime then
        MOZHU_CITIAO = {}
        MOZHU_CITIAO = Util.copyTable(list.citiao)
        MOZHU_CITIAO_TIME = list.citiaoTime
    end
    
end

local function fontBuff(union, msgRet)
    local lv = union.mozhuBufLv or 0
    local mozhuBufTime = union.mozhuBufTime or 0
    local now = os.time()
    local endTime = mozhuBufTime - now
    if now >= mozhuBufTime then
        lv = 0
        endTime = 0 
    end
    local config = MoZhuExcel.buff[lv]
    local nextConfig = MoZhuExcel.buff[lv + 1]
    msgRet.buffEndTime = endTime
    msgRet.upBuffNeed = nextConfig and nextConfig.need or 0
    msgRet.buffLv = lv
    msgRet.buff[0] = 0
    msgRet.nextBuff[0] = 0
    if config and config.attrs then
        for k, v in ipairs(config.attrs) do
            msgRet.buff[k].key = v[1]
            msgRet.buff[k].value = v[2]
        end
        msgRet.buff[0] = #config.attrs
    end

    if nextConfig and nextConfig.attrs then
        for k, v in ipairs(nextConfig.attrs) do
            msgRet.nextBuff[k].key = v[1]
            msgRet.nextBuff[k].value = v[2]
        end
        msgRet.nextBuff[0] = #nextConfig.attrs        
    end
   
end

local function unionRewardDot(human, msg)
    if msg.info and msg.info.myUnion and msg.info.myUnion.hurt then
        local hurt = msg.info.myUnion.hurt
        local canID = 0
        for k, config in ipairs(MoZhuExcel.hurt) do
            if config and config.unionHurt <= hurt then
                canID = k
            end
        end
        local getId = human.db.mozhu and human.db.mozhu.unionGet or 0
        if canID > 0 then
            return getId < canID and 1 or 0
        else
            return 0
        end
    else
        return 0 
    end
end

local function fontQueryNet(msgRet, msg)
    local startTime, endTime = getActTime()
    local now = os.time()
    if now >= startTime and now <= endTime then
        msgRet.isOpen = 1
        msgRet.endTime = endTime - now
    else
        msgRet.isOpen = 0
        msgRet.endTime = startTime - now
    end
    msgRet.isRead = 0 
    msgRet.tzCnt = MOZHU_TIAOZHAN_CNT
    msgRet.restCnt = MOZHU_RESET_CNT
    msgRet.jijieTime = 0
    msgRet.buffLv = 0
    msgRet.buffEndTime = 0
    msgRet.upBuffNeed = 100
    msgRet.restNeed = 100
    msgRet.useHero[0] = 0
    msgRet.buff[0] = 0
    fontCiTiao(msgRet, msg.info)
    fontRoleNet(msgRet, msg)
    fontUnionNet(msgRet, msg)    
    fontMyRole(msgRet, msg)
    fontMyUnion(msgRet, msg)
end

local function fontRankReward(type, msgRet)
    local len = 0 
    for k, config in ipairs(MoZhuExcel.rank) do
        if type == 1 and config.roleMin > 0 then
            len = len + 1
            local net = msgRet.rewardList[len]
            net.id = k
            net.minRank = config.roleMin 
            net.maxRank = config.roleMax
            for j, h in ipairs(config.reward) do
                Grid.makeItem(net.reward[j], h[1], h[2])
            end
            net.reward[0] = #config.reward
        elseif type == 2 and config.unionMin > 0  then
            len = len + 1
            local net = msgRet.rewardList[len]
            net.id = k
            net.minRank = config.unionMin 
            net.maxRank = config.unionMax
            for j, h in ipairs(config.unionReward) do
                Grid.makeItem(net.reward[j], h[1], h[2])
            end
            net.reward[0] = #config.unionReward
        end
    end
    msgRet.rewardList[0] = len 
end

----------------- font  net  --------------------------

function getJijieEndTime(union)
    if not union then return 0 end
    local mozhuTime = union.mozhuJijie or 0
    local now = os.time()
    local config = MoZhuExcel.mozhu[1]
    if now - mozhuTime >= config.jijie then
        return 0
    else
        return config.jijie - (now - mozhuTime)
    end
end

function query(human)
    if not human.db.unionUuid or human.db.unionUuid == "" then return end    
    local starTime, endTime = getActTime()
    local now = os.time()
    if now < starTime or now >= endTime then
        if now < starTime  and starTime - now <= MOZHU_DAY_TIME then
        else
            local msgRet = Msg.gc.GC_MOZHU_ACT_OVER
            Msg.send(msgRet, human.fd)
            Broadcast.sendErr(human, Lang.ACT_WAS_OVER)
            return
        end       
    end
    initHuman(human)
    local msgInner = {}
    msgInner.uuid = human.db._id
    msgInner.unionUuid = human.db.unionUuid
    --[[local msgInner =  InnerMsg.lw.LW_MOZHU_QUERY
    msgInner.uuid = human.db._id
    msgInner.unionUuid = human.db.unionUuid
    InnerMsg.sendMsg(0, msgInner)]]
    MozhuMiddleLogic.LW_MOZHU_QUERY(human,msgInner)
end

function WLQuery(human, msg)
    --Util.printTable(msg)    
    updateDaily(human)
    local union = UnionDBLogic.getUnion(human.db.unionUuid)    
    local member = UnionDBLogic.getUnionMember(union, human.db._id)
    local config = MoZhuExcel.mozhu[1]
    local msgRet = Msg.gc.GC_MOZHU_QUERY
    msgRet.rank = msg.rank
    msgRet.myHurt = msg.hurt
    msgRet.time = os.time()
    fontQueryNet(msgRet, msg)
    fontBuff(union, msgRet)
    msgRet.tzCnt = MOZHU_TIAOZHAN_CNT - human.db.mozhu.tzCnt
    msgRet.restCnt = MOZHU_RESET_CNT - human.db.mozhu.restCnt
    msgRet.restNeed =  config.rest[human.db.mozhu.restCnt + 1] or 0
    msgRet.jijieTime = getJijieEndTime(union)
    msgRet.isRead = human.db.mozhu.read or 0
    msgRet.post = member and member.post or 0                
    if human.db.mozhu.onHero then
        for uuid, _ in pairs(human.db.mozhu.onHero) do
            msgRet.useHero[0] = msgRet.useHero[0] + 1
            msgRet.useHero[msgRet.useHero[0]].uuid = uuid 
        end
    end
    msgRet.unionDot = unionRewardDot(human, msg)
 --   Msg.trace(msgRet)
    Msg.send(msgRet, human.fd)
    human.db.mozhu.read = 1
end


function queryRank(human, type)
    --local msgInner = InnerMsg.lw.LW_MOZHU_RANK_QUERY
    local msgInner = {}
    msgInner.uuid = human.db._id
    msgInner.type = type 
    --InnerMsg.sendMsg(0, msgInner)
    MozhuMiddleLogic.LW_MOZHU_RANK_QUERY(0,msgInner)
end

function rankQueryWL(human, msg)
 --   Util.printTable(msg)

    local msgRet = Msg.gc.GC_MOZHU_RANK_QUERY
    msgRet.type = msg.type
    fontRoleNet(msgRet, msg)
    fontUnionNet(msgRet, msg)
    fontRankReward(msg.type, msgRet)
 --   Util.printTable(msgRet.roleList)
    Msg.send(msgRet, human.fd)
end


function unionHurtRewardQuery(human)
    local getId = human.db.mozhu and human.db.mozhu.unionGet or 0
    local msgRet = Msg.gc.GC_MOZHU_UNION_HURT_REWARD 
    msgRet.isEnd = 0
    msgRet.getId = getId
    local len = 0
    for k, config in ipairs(MoZhuExcel.hurt) do
        len = len + 1 
        local net = msgRet.list[len]
        net.id = k
        net.hurt = config.unionHurt
        for j, h in ipairs(config.reward) do
            Grid.makeItem(net.reward[j], h[1], h[2])
        end
        net.reward[0] = #config.reward
        if len >= 10 then
            msgRet.list[0] = len
            Msg.send(msgRet, human.fd)
            len = 0
        end
    end
    msgRet.list[0] = len
    msgRet.isEnd = 1
    Msg.send(msgRet, human.fd)
end

function unionHurtGet(human, id)
    if not human.db.unionUuid or human.db.unionUuid == "" then
        return
    end

    if not human.db.mozhu then return end 
    -- local oldId = human.db.mozhu.unionGet or 0
    -- if id ~= oldId + 1 then return end

    -- local msgInner = {} -- InnerMsg.lw.LW_MOZHU_UNION_GET
    -- msgInner.uuid = human.db._id
    -- msgInner.unionUuid = human.db.unionUuid
    -- msgInner.id = id 
    -- --InnerMsg.sendMsg(0, msgInner)
    -- MozhuMiddleLogic.LW_MOZHU_UNION_GET(0,msgInner)

    -- 新修改：一键领取所有可领取奖励
    local msgInner = {} -- InnerMsg.lw.LW_MOZHU_UNION_GET
    msgInner.uuid = human.db._id
    msgInner.unionUuid = human.db.unionUuid
    -- msgInner.id = id 
    --InnerMsg.sendMsg(0, msgInner)
    MozhuMiddleLogic.LW_MOZHU_UNION_GET(0,msgInner)
end

function unionGetWL(human, msg)

  --  Util.printTable(msg)
    if msg.ret == 0 then
        return
    end

    -- local config = MoZhuExcel.hurt[msg.id]
    -- if not config then return end

    -- BagLogic.addItemList(human, config.reward,  "ciYuanMozhu")

    -- human.db.mozhu.unionGet = msg.id

    local len = 0
    local itemVec = {}
    local getIdx = human.db.mozhu.unionGet or 0

    for _, idx in ipairs(msg.rewardIdxList) do
        local config = MoZhuExcel.hurt[idx]
        if config and idx > getIdx then
            for _, item in ipairs(config.reward) do
                len = len + 1
                itemVec[len] = item

                getIdx = idx
                -- human.db.mozhu.unionGet = idx
            end
        end
    end

    if len == 0 then
        return
    end

    human.db.mozhu.unionGet = getIdx

    BagLogic.addItemList(human, itemVec,  "ciYuanMozhu")

    local msgRet = Msg.gc.GC_MOZHU_REWARD_GET
    -- msgRet.id = msg.id
    msgRet.id = human.db.mozhu.unionGet
    Msg.send(msgRet, human.fd)
end


function jijie(human, str)
    if not human.db.unionUuid or human.db.unionUuid == "" then return end
    local union = UnionDBLogic.getUnion(human.db.unionUuid)    
    if not union then return end

    -- 检测官职 能否满足要求
    local member = UnionDBLogic.getUnionMember(union, human.db._id)
    if not member 
       or (member.post ~= UnionDefine.POST_PRESIDENT and member.post ~= UnionDefine.POST_OFFICIAL) then
        return Broadcast.sendErr(human, Lang.UNION_HAVE_NO_POWER)
    end 
    local mozhuTime = union.mozhuJijie or 0
    local now = os.time()
    local config = MoZhuExcel.mozhu[1]
    if now - mozhuTime <= config.jijie then
        return 
    end
    
    union.mozhuJijie = now
    UnionDBLogic.updateUnionData(union)

    -- 发送 聊天 到公会
    if ChatUnion.chatUnionEctype(human, str) == 1 then
        return
    end 

    local msgRet = Msg.gc.GC_MOZHU_JIJIE_DO
    msgRet.jijieTime = config.jijie
    Msg.send(msgRet, human.fd)
   
    Broadcast.sendErr(human, Lang.UNION_ECTYPE_JIJIE_SUCCESS) 
end

function rest(human)
    if human.db.mozhu.tzCnt < 3 then
        return
    end
    local retstCnt = human.db.mozhu.restCnt + 1 
    local config = MoZhuExcel.mozhu[1]

    if retstCnt > #config.rest then
        return
    end
    if not ObjHuman.checkRMB(human, config.rest[retstCnt]) then
        return
    end

    ObjHuman.decZuanshi(human,-config.rest[retstCnt],"ciYuanMozhu")

    human.db.mozhu.restCnt = human.db.mozhu.restCnt + 1
    human.db.mozhu.tzCnt = 0
    human.db.mozhu.hurt = 0
    human.db.mozhu.onHero = nil

    local msgRet = Msg.gc.GC_MOZHU_RESET
    msgRet.tzCnt = MOZHU_TIAOZHAN_CNT - human.db.mozhu.tzCnt 
    msgRet.restCnt = #config.rest - human.db.mozhu.restCnt
    msgRet.restNeed = config.rest[retstCnt + 1] or 0
    Msg.send(msgRet, human.fd)
end


function buffUp(human)
    if not human.db.unionUuid or human.db.unionUuid == "" then return end
    local union = UnionDBLogic.getUnion(human.db.unionUuid)    
    if not union then return end

    local now = os.time()
    local lv = union.mozhuBufLv or 0
    local endTime = union.mozhuBufTime or now

    if endTime ~= 0 and now >= endTime then
        lv = 0
        endTime = now 
    end

    if lv + 1 > #MoZhuExcel.buff then
        return
    end
    local config = MoZhuExcel.buff[lv + 1]
    if not ObjHuman.checkRMB(human, config.need) then
        return
    end
    
    ObjHuman.decZuanshi(human,-config.need,"ciYuanMozhu")
    union.mozhuBufLv = lv + 1
    union.mozhuBufTime = endTime + config.time
    UnionDBLogic.updateUnionData(union)

    local msgRet = Msg.gc.GC_MOZHU_BUFF_UP
    fontBuff(union, msgRet)
    Msg.send(msgRet, human.fd)
end


function ciTiaoQuery(human)

    if MOZHU_CITIAO then
        local msgRet = Msg.gc.GC_MOZHU_CITIAO_QUERY 
        msgRet.time = MOZHU_CITIAO_TIME
        local len = 0
        for id in pairs(MOZHU_CITIAO) do
            len = len + 1
            local config = MoZhuExcel.citiao[id]
            local net = msgRet.list[len]
            net.id   = id
            net.name = config.citiao
            net.desc = config.miaoshu
        end
        msgRet.list[0] = len
        Msg.send(msgRet, human.fd)
    end   
end

-- 封装 BOSS 技能详情
function fontDragonSkill(msgRet, monsterOutID)
    
    local monsterID 
    for _, v in ipairs(MonsterExcel.monsterOut[monsterOutID].member) do
        if v and v[1] ~= 0 then
            monsterID = v[1]
            break
        end
    end
    local monsterConfig = MonsterExcel.monster[monsterID]

    local len = 1
    HeroLogic.makeSkillNet(msgRet.skillList[len], monsterConfig.normalAtkID) 
    for k, v in ipairs(monsterConfig.skillList) do
        len = len + 1
        HeroLogic.makeSkillNet(msgRet.skillList[len], v)
    end

    for k , v in ipairs(monsterConfig.beSkillList) do
        if len < 4 then
            len = len + 1
            HeroLogic.makeSkillNet(msgRet.skillList[len], v)
        end
    end       
    msgRet.skillList[0] = len 
end


-- BOSS查询    
function bossQuery(human)
    local msgRet = Msg.gc.GC_MOZHU_BOSS_QUERY
    local config = MoZhuExcel.mozhu[1]
    msgRet.id = 1
    msgRet.desc = config.desc
    fontDragonSkill(msgRet, config.monsterOutID)
    Msg.send(msgRet, human.fd)
end
-----------------------------------  combat  ------------------------------------------------------------------------
function getCombatMonsterOutID(human, side, args)
	if side ~= CombatDefine.DEFEND_SIDE then return end
    local config = MoZhuExcel.mozhu[1]
	return config.monsterOutID
end

function getMapID()
    local config = MoZhuExcel.mozhu[1]
    return config.mapID
end

function getCombatObjList(human, side, args)
	if side ~= CombatDefine.DEFEND_SIDE then return end
    local monsterOutID = getCombatMonsterOutID(human, side)
    local objList, _, _,formation,jiban, elfList = CombatLogic.getMonsterObjList(monsterOutID, CombatDefine.COMBAT_OBJ_TYPE3 , args)
    local rolebase = CombatLogic.createRoleBaseDefault()
    local monsterConfig = MonsterExcel.monster[monsterOutID]
    if monsterConfig then
        rolebase.name = monsterConfig.name 
		rolebase.lv = monsterLv or 1
		rolebase.head = monsterConfig.head
		rolebase.zhandouli = zhandouli or 0
    end
    return objList, nil, rolebase,formation,jiban, elfList
end
 
function onFightBegin(human)
    local union = UnionDBLogic.getUnion(human.db.unionUuid)
    if not union then
        return Broadcast.sendErr(human, Lang.UNION_PLAYER_IN_NO)
    end
    local lv = union.mozhuBufLv
    local endTime = union.mozhuBufTime
    if not lv  or not endTime then return end
    local now = os.time()

    if now < endTime then
        local bufConfig = MoZhuExcel.buff[lv]
        if not bufConfig then return end
        for index = 1, CombatDefine.COMBAT_HERO_CNT do
            local atkPos = CombatLogic.getPos(CombatDefine.ATTACK_SIDE, index)
            local atkObj = CombatImpl.objList[atkPos]
            if atkObj then
                for k, v in ipairs(bufConfig.attrs) do
                    local key = v[1]
                    local value = v[2]
                    atkObj.sysAttr[key] = atkObj.sysAttr[key] + value
                    atkObj.isSysAttrChange = true
                end
            end
        end
    end
end
-- 不合适的下阵
function updateCombatPosCheck(human)
    if human.db.mozhu and human.db.mozhu.onHero then
        local combatHero = CombatPosLogic.getCombatHeros(human, CombatDefine.COMABT_TYPE23)
        if not combatHero then return false end
        
        human.db.mozhu.onHero = human.db.mozhu.onHero or {}
        for pos, uuid in pairs(combatHero) do
            if human.db.mozhu.onHero[uuid] then
                combatHero[pos] = nil
            end
        end
        
        local len = 0
        for pos, uuid in pairs(combatHero) do
            len = len + 1
        end

        if len == 0 then
            return false
        end
    end
	return true
end

function fight(human, uuid)
    local startTime, endTime = getActTime()
    local now  = os.time()
    if now < startTime or now >= endTime then
        Broadcast.sendErr(human, Lang.ACT_WAS_OVER)
        local msgRet = Msg.gc.GC_MOZHU_ACT_OVER
        Msg.send(msgRet, human.fd)
        return
    end
    local union = UnionDBLogic.getUnion(human.db.unionUuid)
    if not union then
        return Broadcast.sendErr(human, Lang.UNION_PLAYER_IN_NO)
    end

    if human.db.mozhu and human.db.mozhu.tzCnt >= MOZHU_TIAOZHAN_CNT then
        return
    end

    --已经阵亡的英雄不能下阵
    if human.db.mozhu and human.db.mozhu.onHero then
        for it_uuid, _ in pairs(human.db.mozhu.onHero) do
            if uuid == it_uuid then
                Broadcast.sendErr(human, Lang.YJTREASURE_YAOJI_CURE_ERR2)
                return
            end
        end
    end
    
    local state = updateCombatPosCheck(human)
    if not state then
        return
    end
    local config = MoZhuExcel.mozhu[1]
    CombatLogic.combatBegin(human, config.mapID, 1 , CombatDefine.COMABT_TYPE23)
end


function setSkillAndBeskill(human,combatInfo)    
    local myList = {}
    local bossList = {}

    for k in pairs(MOZHU_CITIAO) do
        local config = MoZhuExcel.citiao[k]
        if config.shengxiao == DragonNestLogic.CITIAO_BY_ATTACK then
            myList[#myList+1] = config.skillID
        elseif config.shengxiao == DragonNestLogic.CITIAO_BY_DEFEND then
            bossList[#bossList+1] = config.skillID
        end
    end

    if #myList > 0 then
        for _,pos in ipairs(CombatDefine.SIDE2POS[CombatDefine.ATTACK_SIDE]) do
            local obj = CombatImpl.objList[pos]
            if obj then
                for _, skillID in ipairs(myList) do      
                    local skillConfig = SkillExcel[skillID]
                    if skillConfig.beSkillType == BeSkill.BESKILL_TYPE24 then
                        for _,skillID in ipairs(skillConfig.args) do
                            local skillConfig = SkillExcel[skillID]
                            obj.beSkillList[skillConfig.beSkillType] = obj.beSkillList[skillConfig.beSkillType] or {}
                            obj.beSkillList[skillConfig.beSkillType][#obj.beSkillList[skillConfig.beSkillType] + 1] = {
                            skillID,
                            skillConfig.beSkillLimit > 0 and skillConfig.beSkillLimit,skillConfig.cd[1] or 0,
                            skillConfig.cd[2] or 0, 0}                                   
                        end
                    else
                        obj.beSkillList[skillConfig.beSkillType] = obj.beSkillList[skillConfig.beSkillType] or {}
                        obj.beSkillList[skillConfig.beSkillType][#obj.beSkillList[skillConfig.beSkillType] + 1] = {
                        skillID,
                        skillConfig.beSkillLimit > 0 and skillConfig.beSkillLimit,skillConfig.cd[1] or 0,
                        skillConfig.cd[2] or 0, 0}        
                    end
                end
            end
        end
    end

    if #bossList > 0  then
        for _,pos in ipairs(CombatDefine.SIDE2POS[CombatDefine.DEFEND_SIDE]) do
            local obj = CombatImpl.objList[pos]
            if obj then
                for _, skillID in ipairs(bossList) do        
                    local skillConfig = SkillExcel[skillID]
                    if skillConfig.beSkillType == BeSkill.BESKILL_TYPE24 then              
                        for _,skillID in ipairs(skillConfig.args) do
                            local skillConfig = SkillExcel[skillID]
                            obj.beSkillList[skillConfig.beSkillType] = obj.beSkillList[skillConfig.beSkillType] or {}
                            obj.beSkillList[skillConfig.beSkillType][#obj.beSkillList[skillConfig.beSkillType] + 1] = {
                            skillID,
                            skillConfig.beSkillLimit > 0 and skillConfig.beSkillLimit,skillConfig.cd[1] or 0,
                            skillConfig.cd[2] or 0, 0}
                        end
                    else
                        obj.beSkillList[skillConfig.beSkillType] = obj.beSkillList[skillConfig.beSkillType] or {}
                        obj.beSkillList[skillConfig.beSkillType][#obj.beSkillList[skillConfig.beSkillType] + 1] = {
                        skillID,
                        skillConfig.beSkillLimit > 0 and skillConfig.beSkillLimit,skillConfig.cd[1] or 0,
                        skillConfig.cd[2] or 0, 0}        
                    end 
                end
            end
        end
    end	
end

function makeBaseInfo(human, roleBase, unionBase)
    roleBase.uuid = human.db._id
    roleBase.name = human.db.name
    roleBase.lv = human.db.lv
    roleBase.unionUuid = human.db.unionUuid or ""
    roleBase.head = human.db.head or 0
    roleBase.headFrame = human.db.headFrame or RoleDefine.DEFAULT_HEAD_FRAME
    roleBase.bannerID = 0
    roleBase.svrName =  Config.SVR_NAME
    roleBase.svrIndex = Config.SVR_INDEX
    if human.db.unionUuid then
        local union = UnionDBLogic.getUnion(human.db.unionUuid)
        if union then
            roleBase.bannerID = union.bannerID

            unionBase.unionName = union.name
            unionBase.lv        = union.lv
            unionBase.bannerID  = union.bannerID
            unionBase.svrName =  Config.SVR_NAME
            unionBase.svrIndex = Config.SVR_INDEX
        end
    end    
end

function onFightEnd(human,result, combatType, cbParam , combatInfo)
    local atkHurt = 0
	for pos = 1, CombatDefine.COMBAT_HERO_CNT do
		local obj = combatInfo.objList and combatInfo.objList[pos]
		if obj then
			atkHurt = atkHurt + obj.result[1]

      --      local hero = human.db.heroBag[obj.bagIndex]
      --      Util.printTable(obj)
		end
	end

    -- 魔兽 造成伤害
    for _,pos in ipairs(CombatDefine.SIDE2HELPPOS[CombatDefine.ATTACK_SIDE]) do
		local pet = combatInfo.helpList and combatInfo.helpList[pos]
		if pet and pet.isPet then
            atkHurt = atkHurt + pet.result[1]
		end
	end

    -- 精灵 造成伤害
    for _,pos in ipairs(CombatDefine.SIDE2ELFPOS[CombatDefine.ATTACK_SIDE]) do
		local elf = combatInfo.elfList and combatInfo.elfList[pos]
		if elf then
            atkHurt = atkHurt + elf.result[1]
		end
	end

    if atkHurt <= 0 then
        atkHurt = 0
    end
    human.db.mozhu.hurt = human.db.mozhu.hurt or 0
    human.db.mozhu.hurt = human.db.mozhu.hurt + atkHurt
    --local msgInner =  InnerMsg.lw.LW_MOZHU_FIGHT_END
    local msgInner = {}
    msgInner.uuid = human.db._id
    msgInner.unionUuid = human.db.unionUuid or ""
    msgInner.maxHurt =  human.db.mozhu.hurt
    msgInner.combatInfo = {}
    msgInner.roleBase = {}
    msgInner.unionBase = {}    
    msgInner.combatInfo = combatInfo
    makeBaseInfo(human, msgInner.roleBase, msgInner.unionBase)
    --InnerMsg.sendMsg(0, msgInner)
    MozhuMiddleLogic.LW_MOZHU_FIGHT_END(0,msgInner)

    YunYingLogic.onCallBack(human, "MoZhuCombat", 1)
    
    WeekTaskLogic.recordWeekTaskFinishCnt(human, WeekTaskLogic.WEEK_TASK_ID_10, 1)
    TriggerLogic.PublishEvent(TriggerDefine.MOZHU_CHALLENGE, human.db._id, 1)
end




function onfightEndWL(human, msg)
    initHuman(human)

 --   Util.printTable(msg)
  -- 

    if msg.maxHurt ~= human.db.mozhu.maxHurt then
        human.db.mozhu.maxHurt = msg.maxHurt
    end           
  
    local combatInfo = msg.combatInfo    

    if msg.backType == 0 then
        -- 战斗完 活动已经过期
    else
        human.db.mozhu.tzCnt = human.db.mozhu.tzCnt + 1
        if msg.maxHurt ~= human.db.mozhu.maxHurt then
            human.db.mozhu.maxHurt = msg.maxHurt
        end       
        
        human.db.mozhu.onHero = human.db.mozhu.onHero or {}
        for pos = 1, CombatDefine.COMBAT_HERO_CNT do
            local obj = combatInfo.objList and combatInfo.objList[pos]
            if obj and obj.bagIndex then
                local hero = human.db.heroBag[obj.bagIndex]
                if hero then
                    human.db.mozhu.onHero[hero.uuid] = 1
                end
                
          --      Util.printTable(obj)
            end
        end

        if human.db.mozhu.restCnt == 0 then
            local hurtConfig = MoZhuExcel.hurt[human.db.mozhu.tzCnt]
            if hurtConfig and #hurtConfig.attackAct > 0 then
                combatInfo.rewardItem =  combatInfo.rewardItem  or {}
                for i = 1, #hurtConfig.attackAct do
                    local itemID = hurtConfig.attackAct[i][1]
                    local itemCnt = hurtConfig.attackAct[i][2]
                    combatInfo.rewardItem[i] = combatInfo.rewardItem[i] or {}
                    combatInfo.rewardItem[i] = {itemID, itemCnt}
                    BagLogic.addItem(human, itemID, itemCnt, "ciYuanMozhu")
                end
            end
        end
    end
  
    local msgRet = Msg.gc.GC_MOZHU_FIGHT_END
    msgRet.hurt = msg.thisHurt
    msgRet.rank = msg.rank
    msgRet.oldRank = msg.oldRank
    msgRet.unionRank = msg.unionRank
    msgRet.oldUnionRank = msg.unionRanked

    CombatLogic.fontCombatFinish(msgRet.data, combatInfo)
   -- Msg.trace(msgRet)
    Msg.send(msgRet, human.fd)
    
    local combatType = CombatDefine.COMABT_TYPE23
    local teamType = CombatPosLogic.getTeamType(combatType)
    if human.db.combatHero[teamType] then
        -- 策划需求 需要保留  魔兽技能 
        human.db.combatHero[teamType].list = {}
  --      human.db.combatHero[teamType].jiban = {}
    end
  --  CombatPosLogic.cleanCombatHeros(human, CombatDefine.COMABT_TYPE23)
    updateDaily(human)
    if msg.backType == 0 then
        -- 战斗完 活动已经过期
        Broadcast.sendErr(human, Lang.ACT_WAS_OVER)
        local msgRet = Msg.gc.GC_MOZHU_ACT_OVER
        Msg.send(msgRet, human.fd)
    end
end

-----------------------------------------fight    end - ------------------------

----------------------------------------- Act   Over  -------------------------------
local function getRewardByRank(type, rank)
    for k, config in ipairs(MoZhuExcel.rank) do
        if type == MOZHU_ROLE_RANK_TYPE_1 and config.roleMin <= rank and config.roleMax >= rank then
            return k
        elseif type == MOZHU_UNION_RANK_TYPE_2 and config.unionMin <= rank and config.unionMax >= rank then
            return k
        end
    end
end

function actOverRank(msg)
    if msg.type == 1 then
        roleRankOver(msg)
    elseif msg.type == 2 then
        unionRankOver(msg)
    end
end

function roleRankOver(msg)
  --  Util.printTable(msg)
    local mailConfig = MailExcel.mail[MailDefine.MAIL_ID_MOZHU_ROLE_RANK]
	local title = mailConfig.title
	local senderName = mailConfig.senderName	

    for uuid, rank in pairs(msg.list) do
        local id = getRewardByRank(msg.type, rank)
        local config = MoZhuExcel.rank[id]
        if config then
            local content = Util.format(mailConfig.content, rank)
            MailManager.add(MailManager.SYSTEM, uuid, title, content, config.reward, senderName)

        end
    end
end

function unionRankOver(msg)
  --  Util.printTable(msg)
    local mailConfig = MailExcel.mail[MailDefine.MAIL_ID_MOZHU_UNION_RANK]
	local title = mailConfig.title
	local senderName = mailConfig.senderName	


    for unionUuid, rank in pairs(msg.list) do
        local id = getRewardByRank(msg.type, rank)
        local config = MoZhuExcel.rank[id]
        local union = UnionDBLogic.getUnion(unionUuid)    
        if config and union and union.member then
             -- 每个工会随机延迟发放奖励,避免服务器卡顿
             local r = math.random(60)
             require("core.Timer").addLater(r,function()
                 local content = Util.format(mailConfig.content, rank)
                 for uuid in pairs(union.member) do          
                     MailManager.add(MailManager.SYSTEM, uuid, title, content, config.unionReward, senderName)
                 end 
             end)
        end
    end
end

