-----------------------------------------
-- 直购
-----------------------------------------

local BuyExcel = require("excel.buy").buy
local TopupExcel = require("excel.buy").topup
local presentExcel = require("excel.present")
local Log = require("common.Log")
local Lang = require("common.Lang")
local Msg = require("core.Msg")
local ObjHuman = require("core.ObjHuman")
local BagLogic = require("bag.BagLogic") 
local FcmLogic = require("fcm.FcmLogic")
local PfLogic = require("platform.PfLogic")
local FundLogic = require("present.FundLogic")
local DailyLibaoLogic = require("present.DailyLibaoLogic")
local RichangLibaoLogic = require("present.RichangLibaoLogic")
local TequanShopLogic = require("present.TequanShopLogic")
local TopupLogic = require("topup.TopupLogic")
local VipLogic = require("vip.VipLogic")
local SceneHandler = require("scene.Handler")
local UnionRedBagLogic = require("union.UnionRedBagLogic")
local LimitBuy = require("present.LimitBuy")
local ActCustomizeLogic = require("present.ActCustomizeLogic")
local OpenServerGiftLogic = require("present.OpenServerGiftLogic")
local MonthCard = require("present.MonthCard")
local GiftPackLogic = require("present.GiftPackLogic")
local PremiumGiftLogic = require("absAct.PremiumGiftLogic")
local LimitMangHeLogic = require("present.LimitMangHeLogic")
local Broadcast = require("broadcast.Broadcast")
local MangHeLogic = require("absAct.MangHeLogic")
local HeroGrowUp = require("absAct.HeroGrowUp")
local ItemDefine = require("bag.ItemDefine")
local OverflowFundLogic = require("present.OverflowFundLogic")
local AbsWeeklyCardLogic = require("absAct.AbsWeeklyCardLogic")
local YunYingLogic = require("yunying.YunYingLogic")
local DoubleChargeLogic = require("absAct.DoubleChargeLogic")
local MoshouLogic = require("moshou.MoshouLogic")
local HeroSkinLogic = require("present.HeroSkinLogic")
local OrderExcel = require("excel.warOrder")
local WarOrderLogic = require("shop.WarOrder")
local GiftExcel = require("excel.buy").gift
local GiftLogic = require("topup.GiftLogic")
local VoucherShopLogic = require("voucher.VoucherShopLogic")
local MaiDianDefine = require("MaiDian.MaiDianDefine")
local MainDianLogic = require("MaiDian.MaiDianLogic")
local NewFirstCharge = require("present.NewFirstChargeLogic")
local OneKillGiftLogic = require("present.OneKillGift")
local OpenServerGiftPackage = require("present.OpenServerGiftPackage")
local CommonDefine = require("common.CommonDefine")
local ZhuanpanGift = require("zhuanpan.ZhuanpanGift")
local VoucherInvest = require("voucher.VoucherInvest")
local CommonActLoginGift = require("absAct.CommonActLoginGift")

BUY_CODE_NORMAL = 0   -- 正常调平台的充值接口
BUY_CODE_WX_KEFU = 1  -- 微信小程序客服充值接口

cmd = {}

function initAfterHot()
	BuyExcel = require("excel.buy").buy
	TopupExcel = require("excel.buy").topup
end

local function GetFirstMark(human)
	if not human.db.nFirstBuy then
		human.db.nFirstBuy = 0
		return false
	end

	return human.db.nFirstBuy == 0 and false or true
end

local function SetFirstMark(human, nValue)
	human.db.nFirstBuy = nValue
end

-- 是否充值过
function isChange(human)
    if not human.db.topupAcount or human.db.topupAcount <= 0 then
        return false
    end

    return true
end

-- 是否首次购买
function getIsFirst(human,id)
	if not human.db.buy or 
		not human.db.buy[id] then
		return true
	end
end

-- 购买次数
function getBuyCnt(human,id)
	if not human.db.buy or 
		not human.db.buy[id] then
		return 0
	end

    local cnt = human.db.buy[id].cnt or 0
    return cnt
end

-- 双倍购买次数
function getDoubleBuyCnt(human,id)
	if not human.db.buy or 
		not human.db.buy[id] then
		return 0
	end

    local cnt = human.db.buy[id].doubleCnt or 0
    return cnt
end


-- 真实价格 某些商品首次购买比较便宜
function getRealPrice(human, buyID, region)
	region = human.region or "CN"
	local buyConf = BuyExcel[buyID]
	if not buyConf then return 0 end
	return buyConf[region]
end


local function getRealName(human, buyID, region)
	region = human.region or "CN"
	local buyConf = BuyExcel[buyID]
	if not buyConf then return "" end

	if region == "US" then
		return buyConf.nameEn
	elseif region == "VN" then
		return buyConf.nameEn
	else
		return buyConf.name
	end
end


local function getRealProductId(human, buyID, region)
	region = human.region or "CN"
	local buyConf = BuyExcel[buyID]
	if not buyConf then return "" end

	if region == "US" and human.phpChanelID == CommonDefine.CHANNEL_TAG_FT then
		if human.version == "ios" or human.version == "iostishen" then
			return buyConf.productidIos
		else
			return buyConf.productidEn
		end
	end

	if region == "US" then
		return buyConf.productidEn
	elseif region == "VN" then
		return buyConf.productidEn
	else
		return buyConf.productid
	end
end


-- 封装BuyItem结构体
function fontBuyItem(human, net, buyID)
	net.nCanBuyNum = 0
	if buyID == 0 then
		net.buyID = buyID
		net.region = "zuanshi"
		net.cost = 0
		net.icon = 0
		net.name = ""
		net.isFirst = 0
		net.desc = ""
		net.doubleCnt = 0
		net.actDoubleCnt = 0
		net.useDoubleCnt = 0
		net.buyCnt = 0
		net.vipExp = 0
		net.yuanjia = 0
		net.zhekou = 0
		net.voucher = 0
		net.productId = ""
	else
		local conf = BuyExcel[buyID]
		net.buyID = buyID
		local region = human.region or "CN"
		net.region = region
		net.cost = getRealPrice(human, buyID, region)
		net.icon = conf.icon
		-- net.name = conf.name
		net.name = getRealName(human, buyID, region)
		net.isFirst = getIsFirst(human, buyID) and 1 or 0
		local giveZuanshi = tonumber(conf.desc)
		if giveZuanshi then
			if net.isFirst == 1 then
				net.desc = tostring(giveZuanshi * 3)
			else
				net.desc = tostring(giveZuanshi)
			end
		else
			net.desc = conf.desc
		end
		net.doubleCnt = conf.doubleCnt
		local actDouble = YunYingLogic.onCallBack(human,"getDoubleCnt", buyID, true)
		net.actDoubleCnt = actDouble or 0
		net.useDoubleCnt = getDoubleBuyCnt(human, buyID)
		net.buyCnt = getBuyCnt(human, buyID)
		net.vipExp = conf.vipExp
		net.yuanjia = conf.oCN
		net.zhekou = conf.zhekou
		net.voucher = conf.Voucher
		-- net.productId = conf.productid
		net.productId = getRealProductId(human, buyID, region)
		if conf.module and conf.module ~= "" then
			local tModule = load("return require(\"" .. conf.module .. "\")")()
			if tModule and tModule.GetRemainNum then
				net.nCanBuyNum = tModule.GetRemainNum(human, buyID)
			end
		end
	end
end

-------------------------------- cmd开始 ----------------------------------
-- 充值-元宝
function cmd.topup(human, buyConf, isFirst, buyCnt, buyNum)
	local args = buyConf.args
	local id = args[1]
	local config = TopupExcel[id]
	local cnt = config.cnt * 2
    local doubleCnt = buyConf.doubleCnt

	local actDouble = YunYingLogic.onCallBack(human,"getDoubleCnt", config.buyID, true)
    if actDouble > 0 then
        YunYingLogic.onCallBack(human,"buyCall",config.buyID)
        cnt = cnt * 2
    else
        YunYingLogic.onCallBack(human,"touchSingleReach",config.buyID)
	    --首冲双倍
	    if buyCnt < doubleCnt then
	    	cnt = cnt * 2
            human.db.buy[config.buyID].doubleCnt = human.db.buy[config.buyID].doubleCnt + 1
	    end
	end
	ObjHuman.addZuanshi(human, cnt, "buyTopup")
	BagLogic.sendItemGetList(human, {{ItemDefine.ITEM_ZUANSHI_ID, cnt}}, "buyTopup")
	TopupLogic.query(human)
end

-- 充值-每日礼包
function cmd.dailyLibao(human, buyConf, isFirst, buyCnt, buyNum)
	local id = buyConf.args[1]
	DailyLibaoLogic.buyLibao(human, id, buyNum)
end

-- 充值-每周礼包
function cmd.weekLibao(human, buyConf, isFirst, buyCnt, buyNum)
	local id = buyConf.args[1]
	RichangLibaoLogic.buyLibao(human, RichangLibaoLogic.LIBAOTYPE_WEEK, id, RichangLibaoLogic.RMB_BUY, buyNum)
end

-- 充值-每月礼包
function cmd.monthLibao(human, buyConf, isFirst, buyCnt, buyNum)
	local id = buyConf.args[1]
	RichangLibaoLogic.buyLibao(human, RichangLibaoLogic.LIBAOTYPE_MONTH, id, RichangLibaoLogic.RMB_BUY, buyNum)
end

-- 成长礼包
function cmd.giftPack(human, buyConf, isFirst, buyCnt, buyNum)
    local id = buyConf.args[1]
	GiftPackLogic.buyLibao(human, id, buyNum)
end

-- 充值-特权商店
function cmd.tequanShop(human, buyConf, isFirst, buyCnt, buyNum)
	local id = buyConf.args[1]
	TequanShopLogic.buyLibao(human, id, TequanShopLogic.COST_RMB, buyNum)
end

-- 发公会红包
function cmd.unionRedbag(human,buyConf, isFirst, buyCnt, buyNum)
	UnionRedBagLogic.sendRedBagCallBack(human,buyConf.args[1], buyNum)
end

-- 限时抢购
function cmd.limitBuy(human, buyConf, isFirst, buyCnt, buyNum)
	LimitBuy.buy(human, buyConf.args[1], buyNum)
end

function cmd.customize(human,buyConf, isFirst, buyCnt, buyNum)
    ActCustomizeLogic.onBuyCustomize(human,buyConf.args[1], buyNum)
end

-- 开服好礼
function cmd.openServer(human,buyConf, isFirst, buyCnt, buyNum)
    OpenServerGiftLogic.buyGift(human,buyConf.args[1], buyNum)
end

-- 月卡
function cmd.monthCard(human,buyConf, isFirst, buyCnt, buyNum)
    MonthCard.buyMonthCard(human,buyConf.args[1], buyNum)
end

-- 
function cmd.heroGrowUp(human, buyConf, isFirst, buyCnt, buyNum)
	HeroGrowUp.buyKing(human, buyNum)
end

function cmd.limitMangHe(human, buyConf, isFirst, buyCnt, buyNum)
	LimitMangHeLogic.buy(human, buyConf.id, buyNum)
end

function cmd.overflowFund(human,buyConf, isFirst, buyCnt, buyNum)
    OverflowFundLogic.onBuy(human,buyConf.args[1], buyNum)
end

function cmd.xiLianGift(human, buyConf, isFirst, buyCnt, buyNum)
	MoshouLogic.xlianGiftBuy(human, buyConf.id, buyNum)
end

function cmd.heroSkin(human,buyConf, isFirst, buyCnt, buyNum)
	local buyId = buyConf.id
	return HeroSkinLogic.buy(human,buyId, buyNum)
end

function cmd.gift(human,buyConf, isFirst, buyCnt, buyNum)
	local buyId = buyConf.id
	for id,cfg in pairs(GiftExcel) do
		if cfg.buyID == buyId then 
			GiftLogic.buy(human,id, buyNum)
			break
		end
	end
end

function cmd.warOrder(human,buyConf, isFirst, buyCnt, buyNum)
	local buyId = buyConf.id
	for _,cfg in pairs(OrderExcel.desc) do 
		if cfg.buyId == buyId then 
			WarOrderLogic.warOrderUnlock(human,cfg.type, buyNum)
			break
		end
	end
end

function cmd.voucherbuy(human, buyConf, isFirst, buyCnt, buyNum)
	local nBuyID = buyConf.id
	VoucherShopLogic.VoucherShop_OnBuyVoucher(human, nBuyID, buyNum)
end

function cmd.newfirstcharge(human, buyConf, isFirst, buyCnt, buyNum)
	local nBuyID = buyConf.id
	-- print("[cmd.newfirstcharge] nBuyID = "..nBuyID)
	NewFirstCharge.onCharge(human, nBuyID, buyNum)
end

function cmd.onekillgift(human, buyConf, isFirst, buyCnt, buyNum)
	local nBuyID = buyConf.id
	-- print("[cmd.onekillgift] nBuyID = "..nBuyID)
	OneKillGiftLogic.onCharge(human, nBuyID, buyNum)
end

function cmd.openServergiftpackage(human, buyConf, isFirst, buyCnt, buyNum)
	local nBuyID = buyConf.id
	-- print("[cmd.openservergiftpackage] nBuyID = "..nBuyID)
	OpenServerGiftPackage.onCharge(human, nBuyID, buyNum)
end

function cmd.zhuanpanGift(human, buyConf, isFirst, buyCnt, buyNum)
	local nBuyID = buyConf.id
	ZhuanpanGift.onCharge(human, nBuyID, buyNum)
end


function cmd.VoucherInvest(human, buyConf, isFirst, buyCnt, buyNum)
	local nBuyID = buyConf.id
	VoucherInvest.onCharge(human, nBuyID, buyNum)
end

function cmd.CommonActLoginGift(human, buyConf, isFirst, buyCnt, buyNum)
	local nBuyID = buyConf.id
	CommonActLoginGift.onCharge(human, nBuyID, buyNum)
end


-------------------------------- cmd结束 ----------------------------------

function checkBuy(human, ret)
	local buyID = ret.id
	local buyConf = BuyExcel[buyID]
	if buyConf then
		--临时处理,后续应该要根据web传的货币类型来判断
		-- if not buyConf.CN or buyConf.CN ~= ret.money then
		-- 	return false
		-- end

		local currencyType = "CN"
		if ret.channelID and table.find(CommonDefine.SEA_CHANNEL_ARR, ret.channelID) then
			currencyType = "US"
		end
		if not buyConf[currencyType] or buyConf[currencyType] ~= ret.money then
			return false
		end

		return true
	end
	ret.result = 8
	ret.err = buyID..":buy config not exist"
end

function isArgOK(human,buyID,region,money)
	local buyConf = BuyExcel[buyID]
    if not (buyConf and buyConf[region]) then
    	return
    end
    --海外微端统计，会传转换后的美元值，增加多一层判断
    if PfLogic.isHaiwaiWeiduan(human) then
		if money == buyConf["US"] then
			return true
		end
    end
    
	local checkMoney = getRealPrice(human, buyID, region)
    if money ~= checkMoney then
    	return
    end
    
    return true
end

--直购
function buy(human, arg, nolog)
	local buyID, buyNum
	if type(arg) == "table" then
		buyID = arg.buyID
		buyNum = arg.buyNum or 1
	else
		buyID = arg
		buyNum = 1
	end
    local buyConf = BuyExcel[buyID]	
	local isFirst = getIsFirst(human, buyID)
    local cnt = getBuyCnt(human, buyID)
    local buyDB = human.db.buy
	buyDB[buyID] = buyDB[buyID] or {upTime = {}, cnt=0}
	buyDB[buyID].upTime[#buyDB[buyID].upTime + 1] = os.time()
    buyDB[buyID].cnt = buyDB[buyID].cnt or 0
    buyDB[buyID].cnt = buyDB[buyID].cnt + 1
    buyDB[buyID].doubleCnt = buyDB[buyID].doubleCnt or 0

    if cmd[buyConf.cmd] then 
	    cmd[buyConf.cmd](human, buyConf, isFirst, buyDB[buyID].doubleCnt, buyNum)
    else
        YunYingLogic.onBuy(human, buyConf, isFirst, cnt, buyNum)
    end
	-- 增加VIP经验
	if buyConf.vipExp > 0 then
		VipLogic.addExp(human, buyConf.vipExp)
	end

	if not nolog and type(arg) == "table" and arg.order ~= "transaction_id1"then
		--Log.write(Log.LOGID_OSS_PAY, human.db._id, human.db.account, human.db.name, human.db.lv,arg.order or "" ,buyID or 0,arg.amt or arg.money or 0,arg.gold or 0,2,arg.region or "")
		Log.write(Log.LOGID_OSS_PAY, human.db._id, human.db.newUniqueTag, human.db.name, human.db.lv,arg.order or "" ,buyID or 0,arg.amt or arg.money or 0,arg.gold or 0,2,arg.region or "")
	end

	if type(arg) == "table" then
		afterCharge(human, arg, buyID, buyConf, buyNum)
	end

	if false == GetFirstMark(human) then
		MainDianLogic.MaiDian_Begin(human, MaiDianDefine.MAIDIAN_TYPE_BUY, {nValue = buyID})
		SetFirstMark(human, 1)
		local RoleLogic = require("role.RoleLogic")
		RoleLogic.RoleLogic_QueryHumanInfo(human)

		DailyLibaoLogic.ShowAct(human)
		RichangLibaoLogic.ShowAct(human)
	end
end


-- 临时处理，不加入累充的购买项
local notAddTopupList = {
	[90501] = true,
	[90502] = true,
	[90503] = true,
	[90504] = true,
	[90511] = true,
	[90512] = true,
	[90513] = true,
	[90514] = true,
	[90515] = true,
	[90516] = true,
	[90517] = true,
	[90518] = true,
}


function afterCharge(human,oJsonInput, buyID, buyConf, buyNum)
	--local price = oJsonInput.topupMoney
	local buyConf = BuyExcel[buyID]
	local price = oJsonInput.price or buyConf.CN
	if price and price > 0 and buyConf.cmd ~= "voucherbuy" and not notAddTopupList[buyID] then
		TopupLogic.clacTopupAcount(human, price, buyID, buyNum)
		
		local msgRet = Msg.gc.GC_NOTICE_DADIAN
		msgRet.type = 1
		msgRet.param = oJsonInput.price * 100
		msgRet.param2 = tonumber(oJsonInput.buyID)
		Msg.send(msgRet,human.fd)
	end
end

--直充
function charge(human,oJsonInput)
	local gold = oJsonInput.gold
	local money = oJsonInput.money
	local region = oJsonInput.region
	local buyID = oJsonInput.buyID
	if buyID and BuyExcel[buyID] then
		oJsonInput.id = buyID
		buy(human,oJsonInput,true)
	else
		--直充档次表没有对应配置的话直接给请求中要求的元宝
		ObjHuman.addZuanshi(human, gold, "buyTopup")
	end
    if oJsonInput.order ~= 'transaction_id1' then
        --Log.write(Log.LOGID_OSS_PAY, human.db._id, human.db.account, human.db.name, human.db.lv,oJsonInput.order,buyID or 0,oJsonInput.amt or oJsonInput.money,oJsonInput.gold,2,oJsonInput.region)
		Log.write(Log.LOGID_OSS_PAY, human.db._id, human.db.newUniqueTag, human.db.name, human.db.lv,oJsonInput.order,buyID or 0,oJsonInput.amt or oJsonInput.money,oJsonInput.gold,2,oJsonInput.region)
    end
end

function onLogin(human)
	if not human.db.buyOrder then return end
	for k,v in ipairs(human.db.buyOrder) do
		if v.cmd == "charge" then
			buy(human,v)
		elseif v.cmd == "deliver" then
			charge(human,v)
		end
	end
	human.db.buyOrder = nil
end

-- 判断能不能直购 
function checkCanBuy(human, buyID)
	local buyConf = BuyExcel[buyID]
	if not buyConf then return end

	local price = getRealPrice(human, buyID, "CN")
	if price and not FcmLogic.checkCanBuy(human, price) then
		return
	end

	if SceneHandler.canCharge(human) ~= true then
		return Broadcast.sendErr(human, Lang.CHARGE_CLOSE_TIP)
	end

	local msgRet = Msg.gc.GC_BUY_CHECK
	msgRet.buyCode = BUY_CODE_NORMAL
	
	if PfLogic.isFKW(human) then
		-- 方块玩微信小程序的正式服 ios下走客服充值
		if human.isIOS == 1 then
			msgRet.buyCode = BUY_CODE_WX_KEFU
		end
	elseif PfLogic.isKunTang(human) then 
		-- 坤堂微信小程序的正式服 ios和安卓都走客服充值
		msgRet.buyCode = BUY_CODE_WX_KEFU
	end
	
	fontBuyItem(human, msgRet.buyItem, buyID)
	Msg.send(msgRet, human.fd)	
end