AdvAction.lua 31.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
local ipairs = ipairs
local table = table
local math = math
local next = next
local string = string
local redisproxy = redisproxy
local MsgPack = MsgPack
local getRandomName = getRandomName
local mcast_util = mcast_util
local string_format = string.format
local tonumber = tonumber
local require = require
local table_insert = table.insert
local tconcat = table.concat
local table_unpack = table.unpack

local AdvCommon = require "adv.AdvCommon"

local _M = {}

-- 无尽模式是否开放
local function isOpenEndless(role)
	if role.advOverTime ~= 0 and skynet.timex() >= role.advOverTime then
		return false
	end
	return true
end
-- 冒险内的操作是否可以继续
local function isCanContinue(role)
	local adv = role:getAdvData()
	if not adv:isRunning() then return false end
	if adv:isEndless() then
		if not isOpenEndless(role) then return false end
	end
	return true
end


local function checkFormat(role, format, checkAdvTeam)
	local advHang = role:getProperty("advHang")
	local hadHero = {}
	for chapterId, info in pairs(advHang) do
		if info.format then
			for _, heroId in pairs(info.format.heros) do
				hadHero[heroId] = true
			end
		end
	end

	if not format then
		format = role:getProperty("advTeam")
	end

	if checkAdvTeam then
		for _, heroId in pairs(role:getProperty("advTeam").heros or {}) do
			hadHero[heroId] = true
		end
	end

	if not format.leader then return end
	if format.leader2 == format.leader then return end
	local hadLeader = false
	local hadLeader2 = false
	local heroCount = 0
	for slot, heroId in pairs(format.heros) do
		if not role.heros[heroId] or hadHero[heroId] then
			return
		end
		if heroId == format.leader then
			hadLeader = true
		end
		if heroId == format.leader2 then
			hadLeader2 = true
		end
		heroCount = heroCount + 1
	end
	if not hadLeader2 and heroCount >= 2 then
		return
	end
	if not hadLeader then return end
	return true
end

--开始一个新的关卡
function _M.startAdvRpc( agent, data )
	local role = agent.role
	local msg = MsgPack.unpack(data)
	local chapterId = msg.chapterId --关卡id
	local actid = msg.actid	--活动id
	local layer = msg.layer or 1	--选择层数
	--local format = msg.format 		--编队
	local supportIdx = msg.supportIdx --选择的支援效果
	if not role:isFuncUnlock(FuncUnlock.Adv) then return end
	
	--上一个关卡结束才可以开始新的关卡
	if role:getAdvData():isRunning() then return 8 end
	local advHang = role:getProperty("advHang")
	-- if advHang[chapterId] then return 9 end --正在挂机

	-- 检查活动正确性
	if actid then
		if not role.activity:isOpenById(actid, "AdvLevel") then 
			return 20
		end
		local actCfg = csvdb["activity_adv_chapterCsv"][actid]
		if not actCfg then return 21 end
		actCfg = actCfg[chapterId]
		if not actCfg then return 22 end

		local st = toUnixtime(actCfg["unlockTime"]..string_format("%02x", RESET_TIME))
		if st > skynet.timex() then return 23 end

		if actCfg["prepose"] ~= "" then
			local type, cid = actCfg["prepose"]:toArray(true, "=")
			if type == 1 then
				local actData = role.activity:getActData("ChallengeLevel")
				local battleInfo = actData[cid] or {}
				if (battleInfo["star"] or 0) == 0 then
					return 24
				end
			elseif type == 2 then
				local actData = role.activity:getActData("AdvLevel")
				local advInfo = actData[cid] or {}
				if not advInfo["pass"] then
					return 25
				end
			end
		end
	end

	local chapterData = csvdb["adv_chapterCsv"][chapterId]
	if not chapterData or layer < 1 then return  1 end

	local advPass = role:getProperty("advPass")

	if AdvCommon.isEndless(chapterId) then -- 无尽模式判断

		if chapterId ~= role.advElChapter then return end -- 不是当前进行的章节
		if not isOpenEndless(role) then return end

		if role.dailyData:getProperty("advElC") >= role:getAdvElLimit() then return 2 end -- 是否有体力
		if not role:isFuncOpen(FuncOpenType.AdvEndless) then return 11 end -- 无尽模式 才可以玩儿无尽模式

		local advElM = role:getProperty("advElM")  --最高通关的层数
		if not role:advChapterIsOpen(chapterId) then return 13 end

		if layer ~= 1 then
			local relayData = role:getAdvData():isHaveRelay(layer, chapterId) 
			if not relayData then return 14 end  -- 不是中继层
			if advElM < relayData.unlockfloor then return 15 end --未解锁
		end 
	else   -- 普通模式判断
		if not role:checkAdvCount(chapterData.limitlevel) then return 2 end -- 是否有体力
		if layer >= chapterData.limitlevel  then return 4 end
		-- 关卡开放判断
		if not role:advChapterIsOpen(chapterId) then return 5 end

		if layer ~= 1 then
			local relayData = role:getAdvData():isHaveRelay(layer, chapterId) 
			if not relayData then return 6 end  -- 不是中继层
			if (advPass[chapterId] or 0) < relayData.floor then return 21 end
		end
	end
	
	if not checkFormat(role) then return 7 end

	--local advTeam = role:getProperty("advTeam")
	--table.clear(advTeam)

	--advTeam.heros = {}
	--for slot, heroId in pairs(format.heros) do
	--	advTeam.heros[slot] = heroId
	--end
	--advTeam.leader = format.leader
	--advTeam.leader2 = format.leader2
	--role:updateProperty({field = "advTeam", value = advTeam})
	if AdvCommon.isEndless(chapterId) then
		role.dailyData:updateProperty({field = "advElC", delta = 1})
	else
		role:changeAdvCount(chapterData.limitlevel)
	end

	local support = {}  -- 支援效果
	if AdvCommon.isEndless(chapterId) then
		-- 选择的支援效果
		local advSup = role:getProperty("advSup")
		if supportIdx then
			if advSup[supportIdx] then
				table.insert(support, advSup[supportIdx])
			end
			role:advRandomSupportEffect() -- 选完就重新随机
		end
		-- 增加 默认增加的支援效果
		local active = role:getAdvActiveSupportEffect()
		for aId, _ in pairs(active) do
			local curData = csvdb["adv_supportCsv"][aId]
			if curData.type == 2 then
				table.insert(support, aId)
			end
		end
	end
	role:getAdvData():initByChapter({
		chapterId = chapterId, 
		level = layer, 
		isRelay = layer ~= 1, 
		isEnter = true, 
		support = support,
		actid = actid
	})
	role:checkTaskEnter("AdvStart", {id = chapterId})
	role:checkTaskEnter("AdvStartSelf", {id = chapterId})
	role:getAdvData():popBackEvents() -- 清一下事件
	role:getAdvData():mylog({desc = "start", int1 = supportIdx})

	SendPacket(actionCodes.Adv_startAdvRpc, '')
	return true
end

function _M.startHangRpc(agent, data)
	local role = agent.role
	local msg = MsgPack.unpack(data)
	local chapterId = msg.chapterId --关卡id
	local campId = msg.campId or 2 --营地id
	local format = msg.format --编队
	local index = msg.index or 1--时间索引id

	local chapterData = csvdb["adv_chapter_campsiteCsv"][chapterId]
	if not chapterData then return 1 end
	local campSiteData = chapterData[campId]
	if not campSiteData then return 1 end
	if campSiteData.idleReward_1 == "" and campSiteData.idleReward_2 == "" then return 2 end --没有奖励 没有挂机

	local adv_idle_time = globalCsv.adv_idle_time[index]
	local adv_idle_energy = globalCsv.adv_idle_energy[index]
	local adv_idle_reward_coef = globalCsv.adv_idle_reward[index]
	if not adv_idle_time or not adv_idle_energy or not adv_idle_reward_coef then
		return 2
	end
	adv_idle_time = adv_idle_time * 60

	local advHang = role:getProperty("advHang")
	if advHang[chapterId] then return 3 end --正在挂机

	-- if role:getAdvData():isRunning() and role:getAdvData().chapterId == chapterId then return 4 end

	if AdvCommon.isEndless(chapterId) then return 5 end -- 无尽没有代理

	local advRelay = role:getProperty("advRelay") 
	if not next(advRelay[chapterId] or {}) then return 6 end -- 没有开放


	if not role:checkAdvCount(adv_idle_energy) then return 7 end -- 是否有体力

	if not checkFormat(role, format, role:getAdvData():isRunning()) then return 8 end --编队是否正确

	local player = {}
	local attrs = role:getTeamBattleInfo(format).heros
	for attrName, _ in pairs(AdvAttsEnum) do
		for _, hero in pairs(attrs) do
			player[attrName] = (player[attrName] or 0) + hero[attrName]
		end
		player[attrName] = player[attrName] * (globalCsv.adv_battle_attr_ratio[attrName] or 1)
	end

	local battleV = 1 * player["hp"]
		+ 2 * player["atk"]
		+ 1.25 * player["def"]
		+ 0.226 * player["hit"]
		+ 0.26 * player["miss"]

	if battleV < campSiteData.idleValue then return 9 end -- 战斗力是否满足

	local info = {}
	info.format = {}
	info.format.leader = format.leader
	info.format.leader2 = format.leader2
	info.format.heros  = {}
	for slot, heroId in pairs(format.heros) do
		info.format.heros[slot] = heroId
	end
	info.time = skynet.timex() + adv_idle_time --挂机时间
	info.duration = adv_idle_time
	info.campId = campId
	info.index = index

	-- 没有在战斗  用team来挂机了  把team清掉
	--if not role:getAdvData():isRunning() then
	--	role:updateProperty({field = "advTeam", value = {}})
	--end
	role:pushMsg({type = "adv", slot = chapterId, time = adv_idle_time})
	role:changeUpdates({{type = "advHang", field = chapterId, value = info}})

	role:changeAdvCount(adv_idle_energy)
	role:checkTaskEnter("AdvStart", {id = chapterId})
	role:mylog("adv_action", {desc = "startHang", int1 = chapterId})

	SendPacket(actionCodes.Adv_startHangRpc, '')
	return true
end

local function addHeroFaith(role, heroId, exp)
	local hero = role.heros[heroId]
	if not hero then
		return
	end

	hero:addHeroFaith(exp)
	return hero:getProperty("faith")
end

function _M.quickHangRpc(agent, data)
	local role = agent.role
	local msg = MsgPack.unpack(data)

	local chapterId = msg.chapterId --关卡id
	
	local advHang = role:getProperty("advHang")
	local info = advHang[chapterId]
	if not info then return end 

	local index = info.index
	local chapterData = csvdb["adv_chapter_campsiteCsv"][chapterId]
	if not chapterData then return end

	local campSiteData = chapterData[info.campId]
	if not campSiteData then return 1 end
	if campSiteData.idleReward_1 == "" and campSiteData.idleReward_2 == "" then return 2 end --没有奖励 没有挂机

	local adv_idle_time = globalCsv.adv_idle_time[index]
	if not adv_idle_time then
		return 2
	end
	adv_idle_time = adv_idle_time * 60
	
	local reward, isFull
	if skynet.timex() >= info.time then return end  -- 已经完成了

	local cost = math.ceil((info.time - skynet.timex()) / 3600 * globalCsv.adv_idle_quicken)

	if not role:checkItemEnough({[ItemId.Diamond] = cost}) then return end
	role:costItems({[ItemId.Diamond] = cost}, {log = {desc = "advQuickHang", int1 = chapterId}})
	info.time = 0
	role:changeUpdates({{type = "advHang", field = chapterId, value = info}})

	role:pushCancel({type = "adv", slot = chapterId})
	role:mylog("adv_action", {desc = "advQuickHang", int1 = chapterId})

	SendPacket(actionCodes.Adv_quickHangRpc, '')
	return true
end

function _M.endHangRpc(agent, data)
	local role = agent.role
	local msg = MsgPack.unpack(data)

	local chapterId = msg.chapterId --关卡id
	local cancel = msg.cancel  --是否是取消
	
	local advHang = role:getProperty("advHang")
	local info = advHang[chapterId]
	if not info then return end 

	local index = info.index or 1
	local chapterData = csvdb["adv_chapter_campsiteCsv"][chapterId]
	if not chapterData then return end
	local campSiteData = chapterData[info.campId or 2]
	if not campSiteData then return 1 end
	if campSiteData.idleReward_1 == "" and campSiteData.idleReward_2 == "" then return 2 end --没有奖励 没有挂机

	local adv_idle_time = globalCsv.adv_idle_time[index]
	local adv_idle_energy = globalCsv.adv_idle_energy[index]
	local adv_idle_reward_coef = globalCsv.adv_idle_reward[index]
	if not adv_idle_time or not adv_idle_energy or not adv_idle_reward_coef then
		return 2
	end
	adv_idle_time = adv_idle_time * 60
	
	local reward, isFull, change, heroFaithMap
	local heroCnt = 0
	if skynet.timex() >= info.time then
		-- 最新需求加成取消
		--[[
		-- 英雄加成
		local idleUnit = chapterData.idleUnit:toNumMap()
		local upUnit = 0
		for slot, heroId in pairs((info.format or {}).heros or {}) do
			local hero = role.heros[heroId]
			if hero then
				if idleUnit[hero:getProperty("type")] then
					upUnit = upUnit + idleUnit[hero:getProperty("type")]
				end
			end
		end
		-- 中继加成
		local advPass = role:getProperty("advPass")
		local maxCampsite = nil
		local campsiteCsv = csvdb["adv_chapter_campsiteCsv"][chapterId]
		for _, campsite in ipairs(campsiteCsv) do
			if campsite.floor <= advPass[chapterId] then
				maxCampsite = campsite
			else
				break
			end
		end

		if not maxCampsite then return end
		]]
		-- 增加英雄信赖
		local exp = info.duration / 60
		heroFaithMap = {}
		for _, heroId in pairs(info.format.heros) do
			local curFaith = addHeroFaith(role, heroId, exp)
			heroFaithMap[heroId] = curFaith
			heroCnt = heroCnt + 1
		end

		local totalReward = campSiteData.idleReward_1 .. " " .. campSiteData.idleReward_2

		local idleReward = totalReward:toNumMap()
		for itemId, count in pairs(idleReward) do
			idleReward[itemId] = count * adv_idle_reward_coef
		end
		reward, change = role:award(idleReward, {log = {desc = "advHang", int1 = chapterId}})
	else
		if cancel then
			--role:changeAdvCount(-chapterData.limitlevel)
			-- if role:getProperty("advC") <= 0 then 
			-- 	isFull = true
			-- else
			-- 	role:updateProperty({field = "advC", delta = -chapterData.limitlevel})
			-- end
			role:pushCancel({type = "adv", slot = chapterId})
		else
			return
		end
	end
	
	role:changeUpdates({{type = "advHang", field = chapterId, value = nil}})

	role:mylog("adv_action", {desc = "endHang", int1 = chapterId, short1 = cancel and 1 or 0})

	role:checkTaskEnter("AdvHang", {})
	role:checkTaskEnter("AdvHangHeroCnt", {count = heroCnt})

	SendPacket(actionCodes.Adv_endHangRpc, MsgPack.pack({reward = reward, change = change, isFull = isFull, heroFaith = heroFaithMap}))
	return true
end

function _M.buyAdvCountRpc(agent , data)
	local role = agent.role
	local msg = MsgPack.unpack(data)
	
	local count = msg.count --购买次数
	local isEl = msg.isEl -- 是否是无尽模式
	local cost
	if isEl then
		if math.illegalNum(count, 1, globalCsv.adv_endless_daily_buy_count - role.dailyData:getProperty("advElBC")) then return end
		cost = {[ItemId.Diamond] = count * globalCsv.adv_endless_daily_buy_cost}
	else
		if math.illegalNum(count, 1, globalCsv.adv_daily_buy_count - role.dailyData:getProperty("advBC")) then return end
		cost = {[ItemId.Diamond] = count * globalCsv.adv_daily_buy_cost}
	end
	
	
	if not role:checkItemEnough(cost) then return end
	role:costItems(cost, {log = {desc = "buyAdvCount", int1 = isEl and 1 or 0, int2 = count}})
	if isEl then
		role.dailyData:updateProperty({field = "advElC", delta = -count})
		role.dailyData:updateProperty({field = "advElBC", delta = count})
	else
		role:changeAdvCount(-count * globalCsv.adv_daily_buy_num)
		role.dailyData:updateProperty({field = "advBC", delta = count})
	end
	role:mylog("adv_action", {desc = "buyAdvCount", short1 = isEl and 1 or 0, int1 = count})
	
	SendPacket(actionCodes.Adv_buyAdvCountRpc, '')
	return true
end

function _M.finishTaskRpc(agent, data)
	local role = agent.role
	local msg = MsgPack.unpack(data)

	if not isCanContinue(role) then return end
	local adv = role:getAdvData()
	local taskId = msg.taskId  -- -1 则是主线任务
	local status, reward, change
	if taskId == -1 then
		status, reward, change = adv:finishMTask()
	else
		status, reward = adv:finishTask(taskId)
		adv:checkAchievement(adv.AchievType.TaskLayer, 1, taskId)
		adv:updateAchievement()
	end
	adv:updateTask()
	if not status then return end
	role:checkTaskEnter("AdvOverTask", {id = taskId})

	adv:mylog({desc = "finishTask", int1 = taskId})
	
	role:log("mission_pick_achiev", {
		mission_threadid = adv.chapterId, -- 大地图ID
		mission_threadname = (csvdb["adv_chapterCsv"][adv.chapterId] or {})["chapter"] or "auto", -- 大地图名称
		mission_id = adv.level, -- 关卡ID
		mission_sequenceid = adv.logid, -- 本次拾荒ID,用于关联一次拾荒产生多条不同类型的日志
		mission_pick_achiev_id = taskId, -- 任务ID
		mission_pick_achiev_reward = reward, -- 任务奖励,[{"id":101,"num":10},{"id":102,"num":20},{"id":103,"num":30}]
	})


	SendPacket(actionCodes.Adv_finishTaskRpc, MsgPack.pack(role:packReward(reward, change)))
	return true
end

-- 点击地块(解锁)(触发事件)
function _M.clickBlockRpc(agent, data)
	local role = agent.role
	local msg = MsgPack.unpack(data)

	local function returnFail(status)
		SendPacket(actionCodes.Adv_clickBlockRpc, MsgPack.pack({events = {}}))
		return true or status -- 调试使用 status
	end

	if not isCanContinue(role) then
		return returnFail()
	end
	local adv = role:getAdvData()

	if adv:isWaitChooseArtifact() then return returnFail() end

	adv:mylog({desc = "clickBlock", int1 = msg.roomId, int2 = msg.blockId})

	local status, errorCode = adv:clickBlock(msg.roomId, msg.blockId, msg)
	if not status then return returnFail(errorCode) end

	SendPacket(actionCodes.Adv_clickBlockRpc, MsgPack.pack({events = adv:popBackEvents()}))
	return true
end

--use item 使用背包道具
function _M.useItemRpc(agent, data)
	local role = agent.role
	local msg = MsgPack.unpack(data)

	local itemId = msg.itemId -- 道具Id
	local count = msg.count or 1 --数量
	local target = msg.target -- {roomId = 1, blockId = 1} 选择的目标

	local itemData = csvdb["adv_itemCsv"][itemId] 
	if not itemData then return end

	if not isCanContinue(role) then return end
	local adv = role:getAdvData()
	if adv:isWaitChooseArtifact() then return end
	--重置数量 
	if itemData["function"] == 0 or itemData["function"] == 2 then count = 1 end
	if not adv:cost({[itemId] = count}, {}, true) then return true end

	--消耗
	if itemData["function"] == 0 or itemData["function"] == 1 then 
		adv:cost({[itemId] = count}, {log = {desc = "useItem", int1 = itemId, int2 = count}})
		adv:backUse({[itemId] = count})
	end
	
	adv:useItem(itemId, count, target)
	
	adv:afterRound()
	adv:saveDB()

	SendPacket(actionCodes.Adv_useItemRpc, MsgPack.pack({events = adv:popBackEvents()}))
	return true
end

--使用营养技能
function _M.usePotionRpc(agent, data)
	local role = agent.role
	local msg = MsgPack.unpack(data)
	local potionId = msg.potionId -- 营养剂Id
	local target = msg.target -- {roomId = 1, blockId = 1} 选择的目标
	local potionLv = role.dinerData:getProperty("dishTree"):getv(potionId, 1)
	if potionLv < 1 then return 1 end

	local potionSet = csvdb["adv_potionCsv"][potionId]
	if not potionSet then return 2 end

	local potionData = potionSet[potionLv]
	if not potionData then return 3 end

	if not isCanContinue(role) then return end
	local adv = role:getAdvData()
	if not adv:cost({[potionId] = 1}, {}, true) then return 4 end
	if adv:isWaitChooseArtifact() then return end

	adv:mylog({desc = "usePotion", int1 = potionId})

	local status = adv:doActive(potionData.effect, target) -- target
	if not status then return end

	adv:cost({[potionId] = 1}, {log = {desc = "usePotion", int1 = potionId}})
	adv:pushBackEvent(AdvBackEventType.Potion, {id = potionId})
	adv:afterRound()
	adv:saveDB()
	role:checkTaskEnter("AdvUsePotion")

	role:finishGuide(61)

	SendPacket(actionCodes.Adv_usePotionRpc, MsgPack.pack({events = adv:popBackEvents()}))
	return true
end

-- 选择神器
function _M.chooseArtifactRpc(agent, data)
	local role = agent.role
	local msg = MsgPack.unpack(data)

	if not isCanContinue(role) then return 1 end

	local adv = role:getAdvData()
	if not msg.idx then return 2 end
	if not adv:isWaitChooseArtifact() then return 3 end
	local status = adv:chooseArtifact(msg.idx)
	if not status then return 4 end
	adv:saveDB()
	
	SendPacket(actionCodes.Adv_chooseArtifactRpc, '')
	return true
end

-- 穿戴神器
function _M.wearArtifactRpc(agent, data)
	local role = agent.role
	local msg = MsgPack.unpack(data)
	local slot = msg.slot
	local id = msg.id

	if not isCanContinue(role) then return end

	local adv = role:getAdvData()

	if math.illegalNum(slot, 1, 5) then return 1 end
	if adv:isWaitChooseArtifact() then return 2 end

	local status = adv:wearArtifact(slot, id)
	if not status then return 3 end

	adv:saveDB()

	role:finishGuide(55)

	SendPacket(actionCodes.Adv_wearArtifactRpc, '')
	return true
end

-- 升级神器
function _M.upArtifactRpc(agent, data)
	local role = agent.role
	local msg = MsgPack.unpack(data)
	local id = msg.id

	if not isCanContinue(role) then return end

	local adv = role:getAdvData()
	if adv:isWaitChooseArtifact() then return 1 end
	local curLevel = adv:isHaveArtifact(id)
	if not curLevel then return 2 end
	if not role:isArtifactOpen(id, adv:isEndless(), curLevel + 1) then return 3 end
	local cost = csvdb["adv_artifactCsv"][id][curLevel].exp:toNumMap()
	if not adv:cost(cost, {}, true) then return 4 end

	local status = adv:artifactLevelUp(id)
	if not status then 
		return 5 
	else
		role:log("mission_pick_reform", {
			mission_threadid = adv.chapterId, -- 大地图ID
			mission_threadname = (csvdb["adv_chapterCsv"][adv.chapterId] or {})["chapter"] or "auto", -- 大地图名称
			mission_id = adv.level, -- 关卡ID
			mission_pick_equip_id = id, -- 神器ID
			mission_pick_reform_beflv = curLevel, -- 神器原等级
			mission_pick_reform_aftlv = curLevel + 1, -- 神器现等级
			mission_pick_reform_cost = cost[ItemId.AdvPoint], -- 消耗探险点数
			mission_sequenceid = adv.logid, -- 本次拾荒ID,用于关联一次拾荒产生多条不同类型的日志
		})
	end
	adv:cost(cost, {log = {desc = "upArtifact", int1 = id}})
	adv:backCost(cost)
	if status == 1 then -- 现在穿着呢。更新下
		adv:saveDB()
	else
		adv:updateAchievement()
	end

	SendPacket(actionCodes.Adv_upArtifactRpc, '')
	return true
end

--退出
function _M.exitAdvRpc(agent, data)
	local role = agent.role
	-- local msg = MsgPack.unpack(data)
	if not isCanContinue(role) then return end
	-- 冒险中途退出的时候要把引导步骤设定到成就引导
	if not role:checkOverGuide(57) then
		role:saveGuide(57,1,true)
	end
	local adv = role:getAdvData()
	adv:mylog({desc = "exit"})
	local status = adv:exit() -- target {roomId = 1, blockId = 1} 选择的目标
	SendPacket(actionCodes.Adv_exitAdvRpc, MsgPack.pack({events = adv:popBackEvents()}))
	return true
end 

--开始战斗
function _M.startBattleRpc(agent, data)
	local role = agent.role
	local msg = MsgPack.unpack(data)

	-- 校验一下信息
	local roomId = msg.roomId
	local blockId = msg.blockId
	local monsterId = msg.monsterId
	local enemyId = msg.enemyId
	if not enemyId then return end
	if not isCanContinue(role) then return end

	local adv = role:getAdvData()

	if adv:isWaitChooseArtifact() then return end
	local enemy = adv.battle:getEnemyById(enemyId)

	if not enemy or enemy.monsterId ~= monsterId or enemy.roomId ~= roomId or enemy.blockId ~= blockId or enemy.lock or enemy.isDead then return end

	local key = tostring(math.random())
	adv.__battleCache = {
		enemyId = enemyId,
		key = key
	}
	SendPacket(actionCodes.Adv_startBattleRpc, MsgPack.pack({key = key}))
	return true
end

-- 结束战斗
function _M.endBattleRpc(agent, data)
	local role = agent.role
	local msg = MsgPack.unpack(data)
	local roomId = msg.roomId
	local blockId = msg.blockId
	local monsterId = msg.monsterId
	local enemyId = msg.enemyId
	local key =  msg.key
	local player = msg.player
	local bySkill = msg.bySkill --死于 技能

	if not player or not player.hp or not player.sp or not enemyId or not key then return end
	if not isCanContinue(role) then return end
	
	local adv = role:getAdvData()
	if adv:isWaitChooseArtifact() then return end
	-- 校验
	if not adv.__battleCache then return end
	if adv.__battleCache.enemyId ~= enemyId then return end
	local enemy = adv.battle:getEnemyById(enemyId)
	if not enemy or enemy.monsterId ~= monsterId or enemy.roomId ~= roomId or enemy.blockId ~= blockId then return end
	adv.__battleCache = nil

	-- 打完野猪怪
	role:finishGuide(52)
	-- 调理剂使用引导(生命药剂)
	if not role:checkOverGuide(61) then
		local potionBag = role:getProperty("advItems"):toNumMap()
		local own = potionBag[10] or 0
		if own > 0 then
			-- 造假
			player.hp = player.hp * 0.8
			role:saveGuide(61,1,true)
		end
	end
	adv:mylog({desc = "endBattle"})
	local status = adv:clickBlock(roomId, blockId, {player = player, enemy = msg.enemy, bySkill = bySkill})

	if not status then return end
	SendPacket(actionCodes.Adv_endBattleRpc, MsgPack.pack({events = adv:popBackEvents()}))
	return true
end

-- function _M.workshopRpc(agent, data)
-- 	local role = agent.role
-- 	local msg = MsgPack.unpack(data)

-- 	local id = msg.id 
-- 	local count = msg.count or 1
-- 	local mergeData = csvdb["adv_mergeCsv"][id]
-- 	if not mergeData then return 1 end

-- 	if not role:isFuncOpen(FuncOpenType.AdvWS) or role:getFuncLv(FuncOpenType.AdvWS) < mergeData.unlock then return 2 end

-- 	local advWs = role.dailyData:getProperty("advWs")
-- 	if math.illegalNum(count, 1, mergeData.limit - (advWs[id] or 0)) then return 3 end

-- 	local cost = mergeData.formula:toNumMap()
-- 	for k, v in pairs(cost) do
-- 		cost[k] = v * count
-- 	end
-- 	if not role:checkItemEnough(cost) then return 4 end

-- 	role:costItems(cost)
-- 	advWs[id] = (advWs[id] or 0) + count
-- 	role.dailyData:updateProperty({field = "advWs", value = advWs})
-- 	local reward = role:award({[id] = count})
-- 	SendPacket(actionCodes.Adv_workshopRpc, MsgPack.pack({reward = reward}))
-- 	return true
-- end

function _M.wheelSurfRpc(agent, data)
	local role = agent.role
	-- if not role:isFuncOpen(FuncOpenType.AdvWheelSurf) then return end -- 默认解锁

	local msg = MsgPack.unpack(data)

	local ptype = msg.ptype  -- 池子类型 1, 2
	local ctype = msg.ctype  -- 抽取次数  1 1次,2 10次

	local countPool = {
		[1] = 1,
		[2] = 10
	}
	local count = countPool[ctype]
	if not count then return 1 end

	if ptype == 2 and not role:isFuncOpen(FuncOpenType.AdvEndless) then
		return 2
	end

	local drawTypeData = csvdb["adv_wheelsurfCsv"][ptype]
	if not drawTypeData then return 3 end
	local drawData = drawTypeData[role:getAdvWheelSurfLv(ptype)]
	if not drawData then return 4 end

	local cost = drawData.cost:toArray(true, "=")
	local costs = {[ItemId.OldCoin] = cost[ctype]}
	if not next(costs) then return 6 end


	if not role:checkItemEnough(costs) then return 5 end
	role:costItems(costs, {log = {desc = "advWheelSurf", int1 = ptype}})
	local oldLv, lv = role:addAdvLvExp(costs[ItemId.OldCoin] or 0)
	local advDrawB = role:getProperty("advDrawB")
	advDrawB[ptype] = (advDrawB[ptype] or 0) + count
	role:updateProperty({field = "advDrawB", value = advDrawB})
	-- 随机池子
	local reward = {}
	local backReward = {}
	for i = 1, count do
		local pool = drawData.weight:randWeight()
		local gift = drawData["pool" .. pool]:randWeight(true)
		reward[gift[1]] = (reward[gift[1]] or 0) + gift[2]
		table.insert(backReward, gift)
	end
	role:award(reward, {log = {desc = "advWheelSurf", int1 = ptype}})
	role:finishGuide(58)

	role:checkTaskEnter("AdvDraw", {count = count, ptype = ptype})
	role:mylog("adv_action", {desc = "advWheelSurf", int1 = ptype, int2 = count})

	role:log("mission_pick_fund", {
		item_id = ItemId.OldCoin, -- 资助花费道具ID
		mission_pick_fund_amount = costs[ItemId.OldCoin], -- 资助花费道具数量
		mission_pick_fund_cnt = count, -- 资助花费道具次数,1或者10
		mission_pick_fund_reward = reward, -- 资助获得奖励,[{"id":100,"num":10},{"id":101,"num":20},{"id":102,"num":30}]
		mission_pick_fund_stagereward = {}, -- 资助阶段奖励
		mission_pick_fund_beflv = oldLv, -- 资助前资助等级
		mission_pick_fund_aftlv = lv, -- 资助后资助等级
	})

	SendPacket(actionCodes.Adv_wheelSurfRpc, MsgPack.pack({reward = backReward}))
	return true
end
function _M.repayWheelSurfRpc(agent, data)
	local role = agent.role
	local msg = MsgPack.unpack(data)

	local ptype = msg.ptype

	if ptype == 2 and not role:isFuncOpen(FuncOpenType.AdvEndless) then
		return
	end

	local drawTypeData = csvdb["adv_wheelsurfCsv"][ptype]
	if not drawTypeData then return end
	local drawData = drawTypeData[role:getAdvWheelSurfLv(ptype)]
	if not drawData then return end

	local advDrawB = role:getProperty("advDrawB")
	if (advDrawB[ptype] or 0) < globalCsv.adv_draw_back_cond then
		return
	end
	advDrawB[ptype] = advDrawB[ptype] - globalCsv.adv_draw_back_cond
	role:updateProperty({field = "advDrawB", value = advDrawB})
	local gift = drawData["pool3"]:randWeight(true)
	local reward, change = {[gift[1]] = gift[2]}
	reward, change = role:award(reward, {log = {desc = "advRepayWheelSurf", int1 = ptype}})
	role:mylog("adv_action", {desc = "advRepayWheelSurf", int1 = ptype})

	SendPacket(actionCodes.Adv_repayWheelSurfRpc, MsgPack.pack(role:packReward(reward, change)))
	return true
end

function _M.finishAchievRpc(agent, data)
	local role = agent.role
	local msg = MsgPack.unpack(data)
	local ctype = msg.ctype or 2 -- 领取类型 1 成就  2 pt累计奖励
	local chapterId = msg.chapterId --章节id
	local taskId = msg.taskId  -- 领取id

	local adv = role:getAdvData()

	local status, reward, change
	if ctype == 1 then
		status, reward, change = adv:finishAchievement(chapterId, taskId)
	elseif ctype == 2 then
		status, reward, change = adv:getAchievementReward(chapterId, taskId)
	end
	if not status then return end
	adv:updateAchievement()
	role:finishGuide(57)
	role:mylog("adv_action", {desc = "finishAchiev", short1 = ctype, int1 = chapterId, int2 = taskId})

	SendPacket(actionCodes.Adv_finishAchievRpc, MsgPack.pack(role:packReward(reward, change)))
	return true
end

function _M.rankRpc(agent, data)
	local role = agent.role

	local list = {}
	local ids = redisproxy:zrevrange(role:getAdvRankKey(), 0 , 99, "WITHSCORES")
	local redret = {}
	if ids and next(ids) then
		redret = redisproxy:pipelining(function (red)
			for i = 1, #ids, 2 do
				local roleId = ids[i]
				local score = tonum(ids[i + 1])
				table.insert(list, {roleId = tonumber(roleId), score = score})
				red:hget(RANK_ADV_INFO, roleId)
			end
		end)
	end
	for i = 1, #redret do
		local player = MsgPack.unpack(redret[i])
		player.format = nil
		list[i].player = player
	end
	local redret = redisproxy:pipelining(function(red)
		red:ZREVRANK(role:getAdvRankKey(), role:getProperty("id"))
		red:zscore(role:getAdvRankKey(), role:getProperty("id"))
	end)
	local rank = redret[1]
	if not rank then
		rank = -1
	else
		rank = redret[1] + 1
	end
	local score = tonum(redret[2], 0)

	SendPacket(actionCodes.Adv_rankRpc, MsgPack.pack({list = list, rank = rank, score = score}))
	return true
end

function _M.refreshSupportRpc(agent, data)
	local role = agent.role

	local cr = role.dailyData:getProperty("advSupRe")	
	local al = role:getAdvSupportFreeCount()

	if cr < al then  --免费
		role.dailyData:updateProperty({field = "advSupRe", delta = 1})
	else -- 付费
		if not role:checkItemEnough({[ItemId.Diamond] = globalCsv.adv_support_refresh_cost}) then return end
		role:costItems({[ItemId.Diamond] = globalCsv.adv_support_refresh_cost}, {log = {desc = "advReSupport"}})
	end

	role:advRandomSupportEffect()
	role:mylog("adv_action", {desc = "advSupRe", short1 = cr < al and 0 or 1})

	SendPacket(actionCodes.Adv_refreshSupportRpc, '')
	return true
end

function _M.roleFormatRpc(agent , data)
	local role = agent.role
	local msg = MsgPack.unpack(data)
	local index = msg.index	-- 阵容索引
	local title = msg.title -- 阵容名称
	local team = {}
	for slot, heroId in pairs(msg.heros) do
		if not role.heros[heroId] then
			return 1
		end
	end

	if index > 10 then
		return 2
	end

	team.heros = {}
	for slot, heroId in pairs(msg.heros) do
		team.heros[slot] = heroId
	end
	team.leader = msg.leader
	team.leader2 = msg.leader2
	team.title = title
	role:setAdvTeamFormat(index, team)

	local advTeam = role:getProperty("advTeam")
	local curIndex = advTeam.index
	if curIndex == index then
		table.clear(advTeam)

		advTeam.heros = {}
		for slot, heroId in pairs(msg.heros) do
			advTeam.heros[slot] = heroId
		end
		advTeam.leader = msg.leader
		advTeam.leader2 = msg.leader2
		advTeam.index = index
		role:updateProperty({field = "advTeam", value = advTeam})
	end

	SendPacket(actionCodes.Adv_roleFormatRpc, '')
	return true
end

function _M.selectTeamRpc(agent, data)
	local role = agent.role
	local msg = MsgPack.unpack(data)
	local index = msg.index	-- 阵容索引
	local team = role:getAdvTeamFormat(index)
	if not next(team) then return end
	team["index"] = index
	role:updateProperty({field = "advTeam", value = team})

	SendPacket(actionCodes.Adv_selectTeamRpc, '')
	return true
end

return _M