-- 英雄召唤+英雄置换
-- 每次抽奖会额外赠送卷轴和珠子

local Lang = require("common.Lang")
local Msg = require("core.Msg")
local XianzhiExcel = require("excel.xianzhi")
local HeroExcel = require("excel.hero")
local ItemDefine = require("bag.ItemDefine")
local BagLogic = require("bag.BagLogic")
local HeroLogic = require("hero.HeroLogic")
local Grid = require("bag.Grid")
local HeroGrid = require("hero.HeroGrid")
local HeroBook = require("hero.HeroBook")
local Broadcast = require("broadcast.Broadcast")
local HeroDefine = require("hero.HeroDefine")
local ChengjiuLogic = require("chengjiu.ChengjiuLogic")
local ChengjiuDefine = require("chengjiu.ChengjiuDefine")
local Util = require("common.Util")
local ChatPaoMaLogic = require("chat.ChatPaoMaLogic")
-- local DrawCardLogic = require("drawCard.DrawCardLogic")
local RoleSystemLogic = require("roleSystem.RoleSystemLogic")
local RoleSystemDefine = require("roleSystem.RoleSystemDefine")
local HeroGrowUp = require("absAct.HeroGrowUp")
local YunYingLogic = require("yunying.YunYingLogic")
local TriggerDefine = require("trigger.TriggerDefine")
local TriggerLogic = require("trigger.TriggerLogic")
local WeekTaskLogic = require("dailyTask.WeekTaskLogic")
local ClutterDataLogic = require("clutter.ClutterDataLogic")
local ClutterDataDefine = require("clutter.ClutterDataDefine")
local Log = require("common.Log")

local xianzhiOutPutId = 126
local xianzhiDelitem_Normal = 100
local xianzhiDelitem_Special = 300


local function makeShopElem(human,config)

end


function detail(human, camp)

	local xianzhiConfig = XianzhiExcel.xianzhi[camp]
	if not xianzhiConfig then return end

	local msgRet = Msg.gc.GC_XIANZHI_DETAIL
	local cnt = 0
	local bf = false
	local itemCnt = 0


	for heroID,heroConfig in pairs(HeroExcel.hero) do
		bf = false
		itemCnt = heroConfig.star == 5 and 50 or 30

		if camp == 4 then
			if (heroConfig.camp == 4 or heroConfig.camp == 5) and heroConfig.seerLv ~= 0 then
				bf =  true
			end
		else
			if heroConfig.camp == camp and heroConfig.seerLv ~= 0 then
				bf = true
			end
		end

		-- UR不显示
		if heroConfig.grade == 5 then
			bf = false
		end

		if bf then
			cnt = cnt + 1
			Grid.makeItem(msgRet.item[cnt], heroID, itemCnt)
		end
	end

	for j = 1, #xianzhiConfig.zhaohuan do
		local tempConfig = xianzhiConfig.zhaohuan[j]
		if cnt > 50 then
			break
		end

		if j == #xianzhiConfig.zhaohuan or j == #xianzhiConfig.zhaohuan - 1 then
		else
			for k, v in ipairs(tempConfig[1]) do
				cnt = cnt + 1
				local minCnt = tempConfig[2][1]
				local maxCnt = tempConfig[2][2]
				Grid.makeItem(msgRet.item[cnt], v[1], minCnt)
			end
		end

	end


	msgRet.item[0] = cnt
	Msg.send(msgRet, human.fd)
end

-- 召唤
function zhaohuanDo(human, camp, cnt, skip)
	local flag = RoleSystemLogic.isOpen(human,RoleSystemDefine.ROLE_SYS_ID_402)
	if flag ~= true then
		return Broadcast.sendErr(human, Lang.XIANZHI_OPEN_NEED_LV)
	end
	if cnt < 1 then return end
	local xianzhiConfig = XianzhiExcel.xianzhi[camp]
	if not xianzhiConfig then return end

	local getID = nil
	local getCnt = nil

	-- 判断消耗
	local needItemID = ItemDefine.ITEM_XIANZHI_BAOZHU_ID
	local needItemCnt = cnt
	local nowItemCnt = BagLogic.getItemCnt(human, needItemID)
	if nowItemCnt < needItemCnt then
		return Broadcast.sendErr(human, Util.format(Lang.XIANZHI_NO_ITEM,ItemDefine.getValue(needItemID,"name")))
	end

	getID,getCnt = zhaohuanHero(human,camp, cnt)
	if getID == nil or getCnt == nil then
		return
	end

	human.db.drawCard.skip = skip or 0
	-- 扣消耗
	BagLogic.delItem(human, needItemID, needItemCnt, "xianzhi_zhaohuan")


	ClutterDataLogic.UpdateDiffLotteryTimes(human, ClutterDataDefine.CLUTTER_TYPE4, cnt, ClutterDataDefine.CLUTTER_TYPE4)

	-- 增加物品
	local msgRet = Msg.gc.GC_XIANZHI_ZHAOHUAN_DO
	msgRet.camp = camp
	BagLogic.cleanMomentItemList()
	
	-- 合并相同ID的数据
	local mergedData = {}  -- {id = {cnt, isNew, heroConfig}}
	for i = 1, #getID do
		local heroID = getID[i]
		local heroCnt = getCnt[i]
		local heroConfig = HeroExcel.hero[heroID]
		
		-- 添加到背包临时列表
		BagLogic.updateMomentItem(2, heroID, heroCnt)
		
		-- 合并数据
		if not mergedData[heroID] then
			local isNew = nil
			if heroConfig then
				isNew = not HeroBook.isGet(human, heroConfig.id, heroConfig.star)
				-- 广播只发送一次
				ChatPaoMaLogic.broadcast(human, ChatPaoMaLogic.PAOMA_TYPE_BROAD_TYPE7, heroConfig.seerLv, heroID)
			end
			mergedData[heroID] = {
				cnt = heroCnt,
				isNew = isNew,
				heroConfig = heroConfig
			}
		else
			-- 相同ID，累加数量
			mergedData[heroID].cnt = mergedData[heroID].cnt + heroCnt
		end
	end
	
	-- 填充协议数据（协议最大支持30个）
	local listIndex = 0
	local maxListCount = 30
	for id, data in pairs(mergedData) do
		if listIndex >= maxListCount then
			break
		end
		listIndex = listIndex + 1
		HeroGrid.makeHeroNice(msgRet.list[listIndex], id, data.cnt, data.isNew)
		-- 日志：添加到协议显示列表
		local heroConfig = HeroExcel.hero[id]
		-- if heroConfig then
		-- 	Log.write(Log.LOGID_DEBUG, "[zhaohuanDo] 添加到协议显示列表(英雄): uuid="..human.db._id..", heroID="..id..", cnt="..data.cnt..", isNew="..(data.isNew and 1 or 0))
		-- else
		-- 	Log.write(Log.LOGID_DEBUG, "[zhaohuanDo] 添加到协议显示列表(物品): uuid="..human.db._id..", itemID="..id..", cnt="..data.cnt)
		-- end
	end
	
	BagLogic.updateMomentItem(2, xianzhiOutPutId, cnt * 1) --每次召唤获得精华1个
	-- 额外增加的物品 30珠子 1转轴
	local exItemCnt1 = cnt * 100
	BagLogic.updateMomentItem(2, ItemDefine.ITEM_XIANZHI_ZHUFU_ID,  exItemCnt1)
	BagLogic.addMomentItemList(human, "xianzhi_zhaohuan")
	
	-- 注意：召唤只给碎片，不给完整英雄
	-- 英雄碎片已经通过 BagLogic.updateMomentItem 和 BagLogic.addMomentItemList 添加到背包

	-- 添加天命结晶到协议（如果还有空间）
	if listIndex < maxListCount then
		listIndex = listIndex + 1
		HeroGrid.makeHeroNice(msgRet.list[listIndex], ItemDefine.ITEM_XIANZHI_ZHUFU_ID, exItemCnt1, nil)
		--Log.write(Log.LOGID_DEBUG, "[zhaohuanDo] 添加到协议显示列表(天命结晶): uuid="..human.db._id..", itemID="..ItemDefine.ITEM_XIANZHI_ZHUFU_ID..", cnt="..exItemCnt1)
	else
		--Log.write(Log.LOGID_DEBUG, "[zhaohuanDo] 协议已满，天命结晶未添加到显示列表: uuid="..human.db._id..", itemID="..ItemDefine.ITEM_XIANZHI_ZHUFU_ID..", cnt="..exItemCnt1..", listIndex="..listIndex)
	end
	
	-- 添加珠子到协议（如果还有空间）
	if listIndex < maxListCount then
		listIndex = listIndex + 1
		HeroGrid.makeHeroNice(msgRet.list[listIndex], xianzhiOutPutId, cnt * 1, nil)
		--Log.write(Log.LOGID_DEBUG, "[zhaohuanDo] 添加到协议显示列表(珠子): uuid="..human.db._id..", itemID="..xianzhiOutPutId..", cnt="..(cnt * 1))
	else
		--Log.write(Log.LOGID_DEBUG, "[zhaohuanDo] 协议已满，珠子未添加到显示列表: uuid="..human.db._id..", itemID="..xianzhiOutPutId..", cnt="..(cnt * 1)..", listIndex="..listIndex)
	end
	
	msgRet.list[0] = listIndex
	--Log.write(Log.LOGID_DEBUG, "[zhaohuanDo] 协议填充完成: uuid="..human.db._id..", 最终listIndex="..listIndex..", 协议list[0]="..msgRet.list[0])

	Msg.send(msgRet, human.fd)

	ChengjiuLogic.onCallback(human,ChengjiuDefine.CJ_TASK_TYPE_14,cnt)

	HeroGrowUp.onCallback(human, HeroGrowUp.TASKTYPE2, cnt)
	YunYingLogic.onCallBack(human, "onTMDrawCard", cnt)
	WeekTaskLogic.recordWeekTaskFinishCnt(human, WeekTaskLogic.WEEK_TASK_ID_3, cnt)

	TriggerLogic.PublishEvent(TriggerDefine.EVENT_TYPE_FATESUMMON, human.db._id, cnt)
end

-- 置换查询
function zhihuanQuery(human, heroID, heroIndex)
	local flag = RoleSystemLogic.isOpen(human,RoleSystemDefine.ROLE_SYS_ID_402)
	if flag ~= true then
		return Broadcast.sendErr(human, Lang.XIANZHI_OPEN_NEED_LV)
	end

	local heroGrid = HeroLogic.getHeroGrid(human, heroID, heroIndex)
	if not heroGrid then return end

	-- 判断是否被锁
	if heroGrid.isLock then
		return
	end

	-- 阵营，星级判断
	local heroConfig = HeroExcel.hero[heroGrid.id]
	local camp = heroConfig.camp
	local star = heroConfig.star
	if heroConfig.grade ~= 4 or star ~= 5 then return end

	local needItemCnt = xianzhiDelitem_Normal
	if camp == 4 or camp == 5 then
		needItemCnt = xianzhiDelitem_Special
	end

	-- 判断消耗
	local needItemID = ItemDefine.ITEM_XIANZHI_ZHUFU_ID
	local nowItemCnt = BagLogic.getItemCnt(human, needItemID)
	if nowItemCnt < needItemCnt then
		return Broadcast.sendErr(human, Util.format(Lang.XIANZHI_NO_ITEM,ItemDefine.getValue(needItemID,"name")))
	end

	-- 扣消耗
	BagLogic.delItem(human, needItemID, needItemCnt, "xianzhi_zhihuan")

	-- 生成新ID
	local nextHero = zhihuanHero(star, camp,heroGrid.id)
	if not nextHero then
		-- 没有置换目标
		print("[zhihuanQuery] 没有获取到置换目标 star = "..star.." camp = "..camp.." id = "..heroGrid.id)
		return
	end
	-- 新ID不等于旧ID

	human.tempZhihuanID = nextHero
	human.tempZhihuanHeroID = heroID
	human.tempZhihuanHeroIndex = heroIndex

	-- 通知客户端
	local msgRet = Msg.gc.GC_XIANZHI_ZHIHUAN_QUERY
	msgRet.heroID = heroID
	msgRet.heroIndex = heroIndex
	msgRet.skip = human.db.drawCard.skip or 0
	HeroGrid.makeHeroSimpleByID(msgRet.heroSimple, nextHero)
	HeroGrid.makeHeroStatic(msgRet.heroStatic,nextHero)
	Msg.send(msgRet, human.fd)
end

function zhihuanDo(human, heroID, heroIndex)
	local heroGrid = HeroLogic.getHeroGrid(human, heroID, heroIndex)
	if not heroGrid then return end

	-- 判断是否被锁
	if heroGrid.isLock then
		return
	end

	if human.tempZhihuanHeroID ~= heroID then return end
	if human.tempZhihuanHeroIndex ~= heroIndex then return end

	local tempGrid = heroGrid
	tempGrid.id = human.tempZhihuanID

	-- 先删
	HeroLogic.delHeroByIndex(human, heroIndex, "xianzhi_zhihuan")
	human.tempZhihuanID = nil
	human.tempZhihuanHeroID = nil
	human.tempZhihuanHeroIndex = nil

	-- 改db
	local newIndex = HeroLogic.addHeroByGrid(human, tempGrid, "xianzhi_zhihuan")

	-- 通知客户端
	local msgRet = Msg.gc.GC_XIANZHI_ZHIHUAN_DO
	HeroGrid.makeHeroSimple(msgRet.heroSimple, tempGrid, newIndex, human)

	Msg.send(msgRet, human.fd)
end
--------------------------功能函数---------------------------------
function zhaohuanHero(human,camp, cnt)
	local xianzhiConfig = Util.copyTable(XianzhiExcel.xianzhi[camp])
	if not xianzhiConfig then return end

	local totalWeight = 0
	local totalWeight1 = 0
	for i = 1, #xianzhiConfig.zhaohuan do
		totalWeight = totalWeight + xianzhiConfig.zhaohuan[i][3]
	end

	for i = 1, #xianzhiConfig.zhaohuan1 do
		totalWeight1 = totalWeight1 + xianzhiConfig.zhaohuan1[i][3]
	end

	cnt = cnt * 5
	local cjPrivilege = ChengjiuLogic.checkPrivilege(human,ChengjiuDefine.PRIVILEGE_TYPE_4)
	if cjPrivilege then
		local randNum = math.random(1,100)
		if randNum == 1 then
			cnt = cnt + 1
		end
	end


	local getID = {}
	local getCnt = {}
	for i = 1, cnt do
		if camp == 4 or camp == 5 then
			camp = math.random(4,5)
		end

		local tWeight = totalWeight
		local zhaohuan = xianzhiConfig.zhaohuan
		if i % 5 == 0 then
			zhaohuan = xianzhiConfig.zhaohuan1
			tWeight = totalWeight1
		end

		local randNum = math.random(1, tWeight)
		for j = 1, #zhaohuan do
			local tempConfig = zhaohuan[j]
			local tempWeight = tempConfig[3]
			if randNum <= tempWeight then  --抽中
				if j == #zhaohuan or j == #zhaohuan - 1 then    --抽中五星英雄
					local allWeight = 0
					for k,v in ipairs(tempConfig[1]) do
						allWeight = allWeight + v[2]
					end
					local nowNum = math.random(1, allWeight)
					for k, v in ipairs(tempConfig[1]) do
						local nowWeight = v[2]
						if nowNum <= nowWeight then
							local rate = v[1]
							local chipId = {}
							local index = 1
							for heroID,heroConfig in pairs(HeroExcel.hero) do
								if heroConfig.camp == camp and heroConfig.seerLv == rate then
									chipId[index] = heroID
									index = index + 1
								end
							end
							local randomNum = 0
							if index == 1 then
								return
							else
								randomNum =  math.random(1,index -1)
							end
							getID[i] = chipId[randomNum]
							local minCnt = tempConfig[2][1]
							local maxCnt = tempConfig[2][2]
							getCnt[i] = math.random(minCnt,maxCnt)
							break
						end
						nowNum = nowNum - nowWeight
					end
					break
				else        -- 抽到其他物品
					local allWeight = 0
					for k, v in ipairs(tempConfig[1]) do
						allWeight = allWeight + v[2]
					end
					local nowNum = math.random(1, allWeight)
					for k, v in ipairs(tempConfig[1]) do
						local nowWeight = v[2]
						if nowNum <= nowWeight then
							getID[i] = v[1]
							local minCnt = tempConfig[2][1]
							local maxCnt = tempConfig[2][2]
							getCnt[i] = math.random(minCnt,maxCnt)
							break
						end
						nowNum = nowNum - nowWeight
					end
					break
				end
			end
			randNum = randNum - tempWeight
		end
	end
	return getID, getCnt
end

function zhihuanHero(star, camp,heroId)
	local xianzhiConfig = XianzhiExcel.xianzhi[camp]
	if not xianzhiConfig then return end

	local nextHero = nil
	local preStarConfig = xianzhiConfig.preStarFive
	if not preStarConfig then return end

	local totalWeight = 0
	for k, v in ipairs(preStarConfig) do
		totalWeight = totalWeight + v[2]
	end

	local randNum = math.random(1, totalWeight)
	for k, v in ipairs(preStarConfig) do
		tempWeight = v[2]
		if randNum <= tempWeight then
			local rate = v[1]
			local chipId = { }
			local index = 0
			for heroID, heroConfig in pairs(HeroExcel.hero) do
				if heroID ~= heroId and  heroConfig.camp == camp and heroConfig.zhihuanLv == rate then
					index = index + 1
					chipId[index] = heroID
				end
			end
			if index == 0 then
				return
			end
			local randomNum = math.random(1, index)
			nextHero = chipId[randomNum]
			break
		end
		randNum = randNum - tempWeight
	end

	return nextHero
end


function preview(human, camp, star)
	local msgRet = Msg.gc.GC_XIANZHI_ZHIHUAN_PREVIEW

	if star < 5 then return end

	local xianzhiConfig = XianzhiExcel.xianzhi[camp]
	if not xianzhiConfig then return end
	local nextHero = nil
	local len = 0
	for k, v in ipairs (xianzhiConfig.preStarFive) do
		if len >= 50 then
			break
		end
		local rate = v[1]
		for heroID,heroConfig in pairs(HeroExcel.hero) do
			if heroConfig.camp == camp and heroConfig.zhihuanLv == rate then
				len = len + 1
				HeroGrid.makeHeroSimpleByID(msgRet.heroSimple[len], heroID)
			end
		end
	end

	msgRet.heroSimple[0] = len
	Msg.send(msgRet, human.fd)
end

function shopQuery(human)
	local xianzhiShopCfg = XianzhiExcel.xianzhiShop
	local msgRet = Msg.gc.GC_XIANZHI_SHOP_QUERY

	--配置错误需要通知策划 或者分段传输
	local maxLength = 100
	if maxLength < #xianzhiShopCfg then
		Broadcast.sendErr(human, Lang.SKIN_CONF_ERR)
		return
	end
	msgRet.currency[0] = 1
	local totalCoin = BagLogic.getItemCnt(human,xianzhiOutPutId)
	Grid.makeItem(msgRet.currency[1],xianzhiOutPutId,totalCoin)
	local length = 0
	for id,cfg in pairs(xianzhiShopCfg) do
		length = length + 1
		--local goods = {}
		msgRet.production[length].id = id
		msgRet.production[length].price = cfg.price
		msgRet.production[length].goods[0] = 1
		Grid.makeItem(msgRet.production[length].goods[1],cfg.goods[1],cfg.goods[2])
	end
	msgRet.production[0] = length
	Msg.send(msgRet, human.fd)
end

function shopBuy(human,id,count)
	-- 判断道具是否足够
	local goodsCfg = XianzhiExcel.xianzhiShop[id]
	-- 
	if not goodsCfg then
		return Broadcast.sendErr(human, Util.format(Lang.XIANZHI_GOODS_NOT_FOUND,id))
	end
	local  cnt = BagLogic.getItemCnt(human,xianzhiOutPutId)
	local needCnt = goodsCfg.price * count
	if cnt < needCnt then
		return Broadcast.sendErr(human, Util.format(Lang.XIANZHI_NO_ITEM,ItemDefine.getValue(xianzhiOutPutId,"name")))
	end
	-- 先扣款 再发道具
	BagLogic.delItem(human,xianzhiOutPutId,needCnt,"xianzhi_buy")
	BagLogic.addItemList(human,{{goodsCfg.goods[1],goodsCfg.goods[2] * count}},"xianzhi_buy")
	-- 同步客户端最新先知精华数量
	local msgRet = Msg.gc.GC_XIANZHI_SHOP_BUY
	msgRet.xianzhiCoin = BagLogic.getItemCnt(human,xianzhiOutPutId)
	Msg.send(msgRet, human.fd)
end