local UnionDBLogic = require("union.UnionDBLogic")
local UnionExcel = require("excel.union")
local Msg = require("core.Msg")
local Util = require("common.Util")
local Lang = require("common.Lang")
local Grid = require("bag.Grid")
local BagLogic = require("bag.BagLogic")
local Broadcast = require("broadcast.Broadcast")
local UnionLogic = require("union.UnionLogic")
local DailyTaskLogic = require("dailyTask.DailyTaskLogic")
local ItemDefine = require("bag.ItemDefine")
local LiLianLogic = require("dailyTask.LiLianLogic")
local UnionLivenessLogic = require("union.UnionLivenessLogic")
local UnionDefine = require("union.UnionDefine")
local RoleSystemLogic = require("roleSystem.RoleSystemLogic")
local RoleSystemDefine = require("roleSystem.RoleSystemDefine")
local MengxinLogic = require("present.MengxinLogic")
local YunYingLogic = require("yunying.YunYingLogic")
local TriggerDefine = require("trigger.TriggerDefine")
local TriggerLogic = require("trigger.TriggerLogic")

function unionDonateQuery(human)
    -- 判断玩家是否有工会
    -- 判断玩家公会是否存在
    local union = UnionDBLogic.getUnion(human.db.unionUuid)
    if union == nil then
        return
    end

    local unionLv = math.min(union.lv, #UnionExcel.union)

    local nextLv = unionLv + 1
    local config = UnionExcel.union[nextLv]

    -- 写协议数据
    local msgRet = Msg.gc.GC_UNION_DONATE_QUERY
    msgRet.unionLv = unionLv
    msgRet.unionExp = union.exp
    msgRet.lvUpExp = UnionExcel.union[unionLv].exp
    msgRet.nextMemCnt = config and config.maxCnt or 0
    msgRet.todayExp = union.donate and union.donate[1] or 0
    
    -- 捐赠类型
    local len = #UnionExcel.donate
    for i = 1,len do
        local net = msgRet.donate[i]
        local v = UnionExcel.donate[i]
        net.unionExp = v.exp
        net.type = v.type

        Grid.makeItem(net.unionContr,v.contr[1][1],v.contr[1][2])
        Grid.makeItem(net.needCost,v.cost[1][1],v.cost[1][2])

        if human.db.unionDonate ~= nil and human.db.unionDonate[1] == v.type then
            net.state = 2
        else
            if human.db.unionDonate == nil then
                net.state = 1
            else
                net.state = 0
            end
        end
    end
    msgRet.donate[0] = len

    -- 捐赠奖励
    len = #UnionExcel.donateReward
    for i = 1,len do
        local net = msgRet.reach[i]
        local v = UnionExcel.donateReward[i]
        net.id = i
        net.needExp = v.needExp

        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
        
        if human.db.donateReward == nil or human.db.donateReward[i] == nil then
            if union.donate ~= nil and union.donate[1] >= v.needExp then
                net.state = 1
            else
                net.state = 0
            end
        else
            net.state = 2
        end
    end
    msgRet.reach[0] = len

    -- 发送协议
    Msg.send(msgRet,human.fd)
end

function donateDo(human,type)
    -- 判断玩家是否有工会
    -- 判断玩家公会是否存在
    local union = UnionDBLogic.getUnion(human.db.unionUuid)
    if union == nil then
        return
    end
    
    -- 验证是否可以捐赠
    if human.db.unionDonate ~= nil then
        return Broadcast.sendErr(human, Lang.UNION_DONATE_ERR_HAD)
    end

    -- 验证捐赠类型是否合法
    if type == nil then
        return
    end

    local config = UnionExcel.donate[type]
    if config == nil then
        return
    end

    -- 验证捐赠花费是否足够
    if not BagLogic.checkItemCnt(human, config.cost[1][1],config.cost[1][2]) then
        return
    end

    -- 扣除花费
    BagLogic.delItem(human, config.cost[1][1],config.cost[1][2], "union_donate")
    
    -- 写DB
    human.db.unionDonate = {}
    human.db.unionDonate[1] = config.type               -- 捐赠类型
    human.db.unionDonate[2] = config.exp                -- 当日获得经验
    human.db.unionDonate[3] = config.contr[1][2]        -- 当日捐赠

    human.db.dailyBanggong = human.db.dailyBanggong or 0
    human.db.dailyBanggong = human.db.dailyBanggong + config.contr[1][2] 
    human.db.totalBanggong = human.db.totalBanggong or 0
    human.db.totalBanggong = human.db.totalBanggong + config.contr[1][2] 
    -- 公会经验
    UnionLogic.addUnionExp(union,config.exp)

    -- 日清，当日公会获得经验
    union.donate = union.donate or {}
    union.donate[1] = union.donate[1] or 0 
    union.donate[1] = union.donate[1] + config.exp
    union.donate[2] = os.time()

    -- 公会总捐赠
    union.totalDonate = union.totalDonate or 0
    union.totalDonate = union.totalDonate + config.contr[1][2]

    -- 公会捐赠列表
    union.member[human.db._id].donate = union.member[human.db._id].donate or 0
    union.member[human.db._id].donate = union.member[human.db._id].donate + config.contr[1][2]
    union.member[human.db._id].lastDonateTime = os.time()
    UnionDBLogic.updateUnionData(union)
    
    UnionLogic.addUnionLog(union._id, 8, human.db.name,UnionDefine.UNION_LOG_CLASSIFY_DONATE,config.param)
    -- 给道具    
    BagLogic.cleanMomentItemList()
	BagLogic.updateMomentItem(1, config.contr[1][1], config.contr[1][2])
    BagLogic.addMomentItemList(human, "union_donate")
    DailyTaskLogic.recordDailyTaskFinishCnt(human, DailyTaskLogic.DAILY_TASK_ID_7, 1)
    if config.cost[1][2] == ItemDefine.ITEM_ZUANSHI_ID then
        LiLianLogic.onCallback(human,LiLianLogic.LILIAN_OUTID30,cnt)
    end
    MengxinLogic.onCallBack(human,MengxinLogic.MX_TASK_TYPE_10,1)
    
    YunYingLogic.onCallBack(human, "onUnionDonate",1)
    --荣耀历程，仅当至尊捐献时触发
    if  type ==3 then
         TriggerLogic.PublishEvent(TriggerDefine.UNION_DONATE, human.db._id, 1)
    end

    TriggerLogic.PublishEvent(TriggerDefine.UNIONS_ALL_TYPE_DONATE, human.db._id, 1)

    UnionLogic.sendUnionChange(union)
    unionDonateQuery(human)
    Broadcast.sendErr(human, Lang.UNION_DONATE_OK)
    if type == 1 then
        UnionLivenessLogic.touchLiveness(human,UnionDefine.UNION_LIVENESS_JB_DONATE,1)
    elseif type == 2 then
        UnionLivenessLogic.touchLiveness(human,UnionDefine.UNION_LIVENESS_ZS_DONATE,1)
    elseif type == 3 then
        UnionLivenessLogic.touchLiveness(human,UnionDefine.UNION_LIVENESS_ZZZS_DONATE,1)
    end
    RoleSystemLogic.onDot(human, RoleSystemDefine.ROLE_SYS_ID_1003)
    RoleSystemLogic.onDot(human, RoleSystemDefine.ROLE_SYS_ID_1001)
end

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

    -- 验证id是否合法
    if id == nil then
        return
    end

    local config = UnionExcel.donateReward[id]
    if config == nil then
        return
    end

    -- 验证公会当日是否获得足够的经验
    if union.donate == nil or union.donate[1] < config.needExp then
        return
    end

    -- 验证玩家是否已领奖励
    if human.db.donateReward ~= nil and human.db.donateReward[id] ~= nil then
        return
    end

    -- 领取奖励
    -- 写DB
    human.db.donateReward = human.db.donateReward or {}
    human.db.donateReward[id] = 1

    -- 发放物品
    BagLogic.addItemList(human, config.reward, "union_donate")
    unionDonateQuery(human)
    RoleSystemLogic.onDot(human, RoleSystemDefine.ROLE_SYS_ID_1003)
end

function updateDaily(human)
    -- 清理玩家公会当日捐赠
    human.db.unionDonate = nil
    human.db.donateReward = nil
    human.db.dailyBanggong = 0

    -- 判断玩家是否有工会
    -- 判断玩家公会是否存在
    local union = UnionDBLogic.getUnion(human.db.unionUuid)
    if union == nil then
        return
    end

    local now = os.time()
    -- 清理公会当日数据
    if union.donate == nil then
        return
    end
    
    local isSameDay = Util.isSameDayByTimes(now,union.donate[2])
   
    -- 不是同一天，清理
    if isSameDay ~= true then
        union.donate = nil
    end 
    UnionDBLogic.updateUnionData(union)
end

function cleanUnionDonateList(union,uuid)
    if union.donateList == nil or union.donateList[uuid] == nil then
        return
    end

    union.donateList[uuid] = nil
end

HUOYUE_TIME = 172800
function getHuoyueCnt(union)
    local now = os.time()
    local cnt = 0
    for k,v in pairs(union.member) do
        if v.lastDonateTime and now - v.lastDonateTime <= HUOYUE_TIME then
            cnt = cnt + 1
        end
    end
    return cnt
end

function isDot(human)
    -- 有可捐赠次数
    if human.db.unionDonate == nil then
        print("[isDot] 公会可捐赠直接返回")
        return true
    end

    local union = UnionDBLogic.getUnion(human.db.unionUuid)
    if union == nil then
        return
    end

    -- 有可领取奖励
    local len = #UnionExcel.donateReward
    for i = 1,len do
        local v = UnionExcel.donateReward[i]
        if human.db.donateReward == nil or human.db.donateReward[i] == nil then
            if union.donate ~= nil and union.donate[1] >= v.needExp then
                print("[isDot] 公会可捐赠直接返回 i = "..i.." union.donate[1] = "..union.donate[1].." needExp = "..v.needExp)
                return true
            end
        end
    end

    return false
end