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

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")

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

cmd = {}

-- 是否首次购买
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

-- 封装BuyItem结构体
function fontBuyItem(human, net, buyID)
	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.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
end

-------------------------------- cmd开始 ----------------------------------
-- 充值-元宝
function cmd.topup(human, buyConf, isFirst, buyCnt)
	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)
	local id = buyConf.args[1]
	DailyLibaoLogic.buyLibao(human, id)
end

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

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

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

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

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

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

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

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

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

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

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

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

function cmd.xiLianGift(human, buyConf)
	MoshouLogic.xlianGiftBuy(human, buyConf.id)
end
-------------------------------- cmd结束 ----------------------------------

function checkBuy(human, ret)
	local buyID = ret.id
	local buyConf = BuyExcel[buyID]
	if buyConf then
		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 
	if type(arg) == "table" then
		buyID = arg.buyID
	else
		buyID = arg
	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)
    else
        YunYingLogic.onBuy(human, buyConf, isFirst, cnt)
    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 "")
	end

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


function afterCharge(human,oJsonInput, buyID, buyConf)
	--local price = oJsonInput.topupMoney
	local buyConf = BuyExcel[buyID]
	local price = buyConf.CN
	
	if price and price > 0 then
		TopupLogic.clacTopupAcount(human, price, buyID)
		
		local msgRet = Msg.gc.GC_NOTICE_DADIAN
		msgRet.type = 1
		msgRet.param = oJsonInput.money * 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)
    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