local LuaMongo = _G.lua_mongo
local Config = require("Config")
local Log = require("common.Log")
local Util = require("common.Util")
local Log = require("common.Log") 
local ObjHuman = require("core.ObjHuman")
local BuyLogic = require("topup.BuyLogic")
local RoleDBLogic = require("role.RoleDBLogic")
local ReportManager = require("platform.ReportManager")
local Lang = require("common.Lang")
local Broadcast = require("broadcast.Broadcast")
local BuyExcel = require("excel.buy").buy
local Msg = require("core.Msg")

--[[
result:
1：充值成功
2：用户不存在
3：验证错误
4：订单号已存在
5：参数有错
6：参数不全
7：请求过时
8：其他原因
--]]

DAY_PAY_NONAGE_1 = 50
DAY_PAY_NONAGE_2 = 100
MONTH_PAY_NONAGE_1 = 200
MONTH_PAY_NONAGE_2 = 400

DELIVER_CODE_HIS = DELIVER_CODE_HIS or {} -- 防重复订单，Timer.doZhengDian(0) 每天清理 24h 前的记录
function deliver(oJsonInput,ret)
	--oJsonInput.type = tonumber(oJsonInput.type)
	oJsonInput.id = tonumber(oJsonInput.id)
	oJsonInput.buyID = oJsonInput.buyID or oJsonInput.id
	oJsonInput.cnt = tonumber(oJsonInput.cnt)
	oJsonInput.money = tonumber(oJsonInput.money)
	oJsonInput.price = oJsonInput.money
	ret.account = oJsonInput.account
	ret.serverTag = oJsonInput.serverTag
	ret.order = oJsonInput.order
	--ret.type = oJsonInput.type
	ret.id = oJsonInput.id
	ret.buyID = ret.buyID or ret.id
	ret.cnt = oJsonInput.cnt
	ret.money = oJsonInput.money
	ret.price = oJsonInput.price
	--ret.region = oJsonInput.region
	ret.channelID = oJsonInput.channelID
	ret.err = ""
	if not (ret.account and ret.order  and ret.id and ret.cnt and ret.serverTag and oJsonInput.channelID) then -- and ret.type and ret.region
		ret.result = 6
		ret.err = "param empty"
		return ret
	end

	if DELIVER_CODE_HIS[oJsonInput.order] then
		ret.result = 4
		ret.err = "order double"
		return ret
	end
	DELIVER_CODE_HIS[oJsonInput.order] = os.time()

	-- local human = ObjHuman.onlineAccount[ret.account]

	local uTag = RoleDBLogic.Generateuuid(oJsonInput.channelID, ret.account, ret.serverTag)
	local human = ObjHuman.onlineNewUniqueTag[uTag]

	local online = true
	if not human then
		local humanDb = RoleDBLogic.loadRole(uTag)
		human = {}
		human.db = humanDb
		online = false
		if not humanDb then
			ret.result = 2
			ret.err = "account not exist"
			return ret
		end
	end

	if not BuyLogic.checkBuy(human,ret) then
		ret.result = 8
		ret.err = "check buy fail"
		return ret
	end

	oJsonInput.cmd = "deliver"
	if online and human.db.middleFlag == nil then
		if Config.IS_DEBUG then
			BuyLogic.buy(human,ret)
		else
			local pcallRet, pcallErr = pcall(BuyLogic.buy, human,ret)
			if not pcallRet then
				--Log.write(Log.LOGID_ERR_PCALL, "BuyLogic.buy err=" .. human.db.account, pcallErr)
				Log.write(Log.LOGID_ERR_PCALL, "BuyLogic.buy err=" .. human.db.newUniqueTag, pcallErr)
				ret.result = -1
				ret.err = pcallErr
				return Broadcast.sendErr(human, "BuyLogic.buy "..Lang.PCALL_ERR) 
			end
		end
	else
		human.db.buyOrder = human.db.buyOrder or {}
		human.db.buyOrder[#human.db.buyOrder + 1] = Util.copyTable(oJsonInput)
	end

	RoleDBLogic.saveRole(human.db)
	ret.result = 1
	--Log.write(Log.LOGID_OSS_DELIVER, human.db._id, human.db.account, human.db.name, human.db.lv,oJsonInput.order,oJsonInput.money,oJsonInput.type,oJsonInput.id,oJsonInput.cnt,online and 1 or 0,oJsonInput.region)
	Log.write(Log.LOGID_OSS_DELIVER, human.db._id, human.db.newUniqueTag, human.db.name, human.db.lv,oJsonInput.order,oJsonInput.money,oJsonInput.type,oJsonInput.id,oJsonInput.cnt,online and 1 or 0,oJsonInput.region)
	return ret
end


--[[
1：充值成功
2：用户不存在
3：验证错误
4：订单号已存在
5：充值元宝数量有错
6：参数不全
7：请求过时
8：参数错误
-1：未知错误
--]]
CHARGE_CODE_HIS = CHARGE_CODE_HIS or {} -- 防重复充值，Timer.doZhengDian(0) 每天清理 24h 前的记录
--如果后续用到该接口时，需要参照deliver修改用到account的地方
function charge(oJsonInput,ret)
	oJsonInput.gold = tonumber(oJsonInput.gold)
	oJsonInput.money = tonumber(oJsonInput.money)
	oJsonInput.buyID = tonumber(oJsonInput.buyID)
	ret.account = oJsonInput.account
	ret.order = oJsonInput.order
	ret.gold = oJsonInput.gold
	ret.money = oJsonInput.money
	ret.region = oJsonInput.region
	ret.appid = oJsonInput.appid or ""
	ret.err = ""
	if not (ret.account and ret.order and ret.gold and ret.money and ret.region) then
		ret.result = 6
		ret.err = "param empty"
		return
	end
	
	if CHARGE_CODE_HIS[oJsonInput.order] then
		ret.result = 4
		ret.err = "order double"
		return
	end

	local human = ObjHuman.onlineAccount[ret.account]
	local online = true
	if not human then
		local humanDb = RoleDBLogic.loadRole(oJsonInput.account)
		human = {}
		human.db = humanDb
		online = false
		if not humanDb then
			ret.result = 2
			ret.err = "account not exist"
			return
		end
	end

    local topupMoney = 0
	local buyConf = oJsonInput.buyID and BuyExcel[oJsonInput.buyID]

    if oJsonInput.buyID == 3 then
        if human.db.fundFlag ~= nil then
            ret.result = 5
		    ret.err = "funds cannot be bought multiple times"
		    return
        end
    end
    if not BuyLogic.isArgOK(human,oJsonInput.buyID,ret.region,ret.money) then
		ret.result = 5
		ret.err = "money not fix config"
		return
	end

	CHARGE_CODE_HIS[oJsonInput.order] = os.time()
	oJsonInput.cmd = "charge"
	
    local price = 0
    if ret.money ~= 0 then
        price = ret.money
    else
        price = buyConf["CN"][1]
    end
    oJsonInput.topupMoney = price
	
	human.db.buyHis = human.db.buyHis or {}
	human.db.buyHis[#human.db.buyHis + 1] = {buyID = oJsonInput.buyID or 0,money = ret.money,gold = ret.gold,upTime = os.time()}
	
	if online and human.db.middleFlag == nil then
		if Config.IS_DEBUG then
			BuyLogic.charge(human,oJsonInput)
		else
			local pcallRet, pcallErr = pcall(BuyLogic.charge, human,oJsonInput)
			if not pcallRet then
				Log.write(Log.LOGID_ERR_PCALL, "BuyLogic.charge err=" .. human.db.account, pcallErr)
				ret.result = -1
				ret.err = pcallErr
				return Broadcast.sendErr(human, "BuyLogic.charge "..Lang.PCALL_ERR) 
			end
		end
	else
		human.db.buyOrder = human.db.buyOrder or {}
		human.db.buyOrder[#human.db.buyOrder + 1] = Util.copyTable(oJsonInput)
    end
	
    RoleDBLogic.saveRole(human.db)
    ret.result = 1
    if ret.order ~= 'transaction_id1' then
        Log.write(Log.LOGID_OSS_PAY, human.db._id, human.db.account, human.db.name, human.db.lv,ret.order,oJsonInput.buyID or 0,oJsonInput.amt or ret.money,ret.gold,online and 1 or 0,ret.region)
    end

    local orderExt = {['orderID'] = oJsonInput.order, ['amount'] = oJsonInput.money}
    if oJsonInput.ext then
        local extData = Json.Decode(oJsonInput.ext)
        orderExt.OrderNO = extData.OrderNO
        orderExt.GoodsCode = extData.GoodsCode
    end
    
    orderExt.PayPurchaseType = buyConf.cmd == "topup" and 0 or 3
    orderExt.ItemCode = oJsonInput.buyID
    orderExt.ItemName = buyConf.name
    orderExt.Amount = 1
    orderExt.CurrencyCode = "KRW"
    orderExt.TotalPrice = oJsonInput.money
    orderExt.PayToolCode = 1
    orderExt.ReceiveMemberID = oJsonInput.account
    orderExt.Balance = human.db.zuanshi
    orderExt.PayResultType = 1
    orderExt.PayResultMessage = "success"

    ReportManager.charge(human, orderExt)
end