----------------------
-- 创角相关逻辑
----------------------
local Config = require("Config")
local PlayerNamesExcel = require("excel.playerNames")
local CommonDB = require("common.CommonDB")
local Lang = require("common.Lang")
local FilterUtil = require("common.FilterUtil")
local Log = require("common.Log")
local LogDefine = require("common.LogDefine")
local CommonDefine = require("common.CommonDefine")
local Msg = require("core.Msg")
local ObjHuman = require("core.ObjHuman")
local RoleDBLogic = require("role.RoleDBLogic")
local RoleHeadLogic = require("role.RoleHeadLogic")
local Broadcast = require("broadcast.Broadcast")
local RoleExcel = require("excel.role") 
local ReportManager = require("platform.ReportManager")
local HeroLogic = require("hero.HeroLogic")
local RelationGiftLogic = require("present.RelationGiftLogic")
local CombatDefine = require("combat.CombatDefine")
local CombatPosLogic = require("combat.CombatPosLogic")
local SysParameter = require("common.SysParameter")
local ChatPaoMaLogic = require("chat.ChatPaoMaLogic")
local MailExcel = require("excel.mail")
local MailManager = require("mail.MailManager")
local TriggerLogic = require("trigger.TriggerLogic")
local TriggerDefine = require("trigger.TriggerDefine")
local RoleStorageBox = require("roleSystem.RoleStorageBox")
local DataCache = require("core.DataCache")

local ROLE_NAME_LEN_MAX = 21
local ROLE_NAME_LEN_MIN = 5
local OP_RET_SUCC = 1
local OP_RET_FAIL = 0

local GodsAreaNS
local AnotherWorldBattleNS

-- 特定渠道用户创角时发送的邮件ID
local NEW_ROLE_MAIL_ID = 7023
-- 特定渠道列表
local TARGET_CHANNEL_ARRAY = {1, 9}

-- 用于公会渠道创角时发送奖励邮件的邮件Id
local CHANNEL_GUILD_MAIL_ID = 7037

-- 公会渠道创角奖励
local channel_guild_createRole_rewards = {{102,8888}, {124,20}, {1208,2}, {111,1000000}, {112,1000}, {101,2000000}, {510,4}}


local function sendMail(human, mailId, items)
	local mailCfg = MailExcel.mail[mailId]
	if not mailCfg then
		return
	end

    MailManager.add(MailManager.SYSTEM, human.db._id, mailCfg.title, mailCfg.content, items, mailCfg.senderName or "GM")
end


-- 生成一个11位的全局不重复的数字组成的id 
-- 规则 前6位服务器index 后五位自增id
function genIdentity()
	local firstStr= Config.SVR_INDEX
	local nowMax = CommonDB.getIdentityMax()
	nowMax = nowMax + 1
	CommonDB.setIdentityMax(nowMax)
	return firstStr .. "" .. nowMax	
end

function getFakeIdentityMax()
	local firstStr= Config.SVR_INDEX
	local id = CommonDB.getFakeIdentityMax()
	return firstStr .. string.format("%05d", id)	
end

local function checkRoleName(roleName, default)
	--如果roleName是nil   游戏名不能为空
	if not roleName then 
		return false, Lang.CREATE_ROLE_FAIL_NAME_NIL
	end
	local nameLen = string.len(roleName)
	--如果游戏名长度小于游戏名最小长度  角色名过短
	if nameLen < ROLE_NAME_LEN_MIN then
		return false, Lang.CREATE_ROLE_FAIL_NAME_LEN1
    end

	--如果游戏名长度大于游戏名最小长度  角色名过长
	if nameLen > ROLE_NAME_LEN_MAX then
		return false, Lang.CREATE_ROLE_FAIL_NAME_LEN2
    end
    
	if default == nil then
		--如果游戏名中包含非法字符				角色名中有非法字符
		if roleName ~= FilterUtil.filterName(roleName) then
			return false, Lang.CREATE_ROLE_FAIL_NAME_SHIELD
		end
	end
	--角色名已经存在
	if RoleDBLogic.isNameExistInDB(roleName) then
		return false, Lang.CREATE_ROLE_FAIL_NAME_DUPLICATE
	end
	return true
end

function creatFakeDb(account, serverTag)
    local db = RoleDBLogic.createDefaultRole(account, serverTag)
    local identity = genIdentity()
	db.identity = identity	
    db.name = account
    return db
end

-- 创角时针对渠道的额外处理
local function channelHandle(human)
	-- 特定渠道用户创角时发送的邮件
	if table.find(TARGET_CHANNEL_ARRAY, human.phpChanelID) then
		sendMail(human, NEW_ROLE_MAIL_ID)
	end

	-- 公会渠道创角时发送奖励邮件
	if human.phpChanelID == CommonDefine.CHANNEL_TAG_GUILD1 or human.phpChanelID == CommonDefine.CHANNEL_TAG_GUILD2 then
		sendMail(human, CHANNEL_GUILD_MAIL_ID, channel_guild_createRole_rewards)
	end
end


function createNewRole(human)
	if _G.is_middle == true then
		return
	end
	
	-- if human.db or RoleDBLogic.isAccountExistInDB(human.account, human.serverTag) then
	-- 	assert(nil)
	-- 	return
	-- end


	if human.db or RoleDBLogic.isNewUniqueTagExistInDB(human.phpChanelID, human.account, human.serverTag) then
		assert(nil)
		return
	end
	
	human.db = RoleDBLogic.createDefaultRole(human.phpChanelID, human.account, human.serverTag)
	
	-- 保存数据
	human.db.name = human.account
	local identity = genIdentity()
	human.db.identity = identity

    -- 测试  临时增加，用于防沉迷测试
    human.db.age = 20
    ----------

	-- 给角色的月光包盒中添加一定数量的道具
	RoleStorageBox.FillStorageBox(human)

    RelationGiftLogic.relationCreate(human)
	ObjHuman.initHuman(human)

	ObjHuman.save(human)
	ObjHuman.onLogin(human, true)
    createRoleSettingUp(human)

	DataCache.Insert_PlayerUuidList(human.db._id, human.db.lv)

	channelHandle(human)

	ReportManager.register(human)
end

-- 改名操作结果
CHANGE_NAME_RET_FAIL = 0 	-- 失败
CHANGE_NAME_RET_OK = 1 		-- 成功，首次改名
CHANGE_NAME_RET_OK2 = 2 	-- 成功，非首次改名

CHANGE_NAME_COST = 200
function changeName(human, roleName)
	local msgRet = Msg.gc.GC_ROLE_CHANGE_NAME
	msgRet.ret = CHANGE_NAME_RET_FAIL
	local isOk, tip = checkRoleName(roleName)
	if not isOk then
		msgRet.tip = tip
		Msg.send(msgRet, human.fd)
		return
	end
	
	if not human.db.changeNameCnt then
		human.db.changeNameCnt = 1
	else
		if human.db.zuanshi < CHANGE_NAME_COST then
			msgRet.tip = Lang.COMMON_NO_ZUANSHI
			Msg.send(msgRet, human.fd)
			return
		end
		human.db.changeNameCnt = human.db.changeNameCnt + 1
		ObjHuman.decZuanshi(human, -CHANGE_NAME_COST, "change_name")
	end
    ObjHuman.onlineHuman[human.db.name] = nil
    ObjHuman.onlineHuman[roleName] = human

	human.db.name = roleName
	ObjHuman.save(human)

	msgRet.ret = CHANGE_NAME_RET_OK
	if human.db.changeNameCnt > 1 then
		msgRet.ret = CHANGE_NAME_RET_OK2
	end
	msgRet.tip = "ok"
	Msg.send(msgRet, human.fd)

	TriggerLogic.PublishEvent(TriggerDefine.CHANGE_NAME, human.db._id, 1)

	GodsAreaNS = GodsAreaNS or require("godsArea.GodsAreaNS")
	GodsAreaNS.UpdateShowData(human, 1)

	local BaiZhanChengShenNS = require("baiZhanChengShen.BaiZhanChengShenNS")
	local BaiZhanChengShenDefine = require("baiZhanChengShen.BaiZhanChengShenDefine")
	BaiZhanChengShenNS.UpdateShowInfo(human, BaiZhanChengShenDefine.BZCS_UPDATE_SHOW_NAME)

	AnotherWorldBattleNS = AnotherWorldBattleNS or require("anotherWorldBattle.AnotherWorldBattleNS")
	AnotherWorldBattleNS.PlayerChangeName(human)

	if human.db.changeNameCnt == 1 then
		-- Log.write(Log.LOGID_OSS_REGISTER, human.db._id, human.db.account, human.db.name, human.ip,human.pf or "",human.appid, human.db.changeNameCnt)
		-- Log.write(Log.LOGID_OSS_CREATELOSS,human.db.account, human.db.name, LogDefine.HUMAN_LOST.CREATE_NAME_FINISH, human.db.ip,human.pf or "",human.appid, human.phpChanelID)
		-- ReportManager.create(human)
		-- Log.write(Log.LOGID_OSS_LOGIN, human.db._id, human.db.account, human.db.name, human.db.lv, human.db.ip)

		Log.write(Log.LOGID_OSS_REGISTER, human.db._id, human.db.newUniqueTag, human.db.name, human.ip,human.pf or "",human.appid, human.db.changeNameCnt)
		Log.write(Log.LOGID_OSS_CREATELOSS,human.db.newUniqueTag, human.db.name, LogDefine.HUMAN_LOST.CREATE_NAME_FINISH, human.db.ip,human.pf or "",human.appid, human.phpChanelID)
		ReportManager.create(human)
		Log.write(Log.LOGID_OSS_LOGIN, human.db._id, human.db.newUniqueTag, human.db.name, human.db.lv, human.db.ip)
	end
end

-- 改名查询
function changeNameQuery(human)
	local msgRet = Msg.gc.GC_ROLE_CHANGE_NAME_QUERY
	if human.db.changeNameCnt == nil then
		msgRet.price = 0
		--Log.write(Log.LOGID_OSS_CREATELOSS,human.db.account, human.db.name, LogDefine.HUMAN_LOST.SHOW_NAME_PANEL, human.db.ip,human.pf or "",human.appid, human.phpChanelID)
		
		Log.write(Log.LOGID_OSS_CREATELOSS,human.db.newUniqueTag, human.db.name, LogDefine.HUMAN_LOST.SHOW_NAME_PANEL, human.db.ip,human.pf or "",human.appid, human.phpChanelID)		
	else
		msgRet.price = CHANGE_NAME_COST
	end
	Msg.send(msgRet,human.fd)
end

function randomName(human, sex)
	local msgRet = Msg.gc.GC_ROLE_RANDOM_NAME
	msgRet.sex = sex
	msgRet.name = getRandomName(sex)
	Msg.send(msgRet, human.fd)
end

function getRandomName(sex)
	if not sex then
		sex = math.random(1, 2)
	end
	local random1 = math.random(1, #PlayerNamesExcel.xing) 
	if sex == 1 then
		local random2 = math.random(1, #PlayerNamesExcel.name)
		return PlayerNamesExcel.xing[random1].xing..PlayerNamesExcel.name[random2].name
	else
		local random2 = math.random(1, #PlayerNamesExcel.name2)
		return PlayerNamesExcel.xing[random1].xing..PlayerNamesExcel.name2[random2].name
	end
end

-- 创角时修改角色信息
function createRoleChangeInfo(human,name,sex,firendCode)
    local msgRet = Msg.gc.GC_ROLE_CREATE_ROLE_CHANGE_MSG

	local isOk = checkRoleName(name)
    if isOk == false then
        msgRet.ret = 1
        Msg.send(msgRet,human.fd)
        return
    end

    -- 创角
    if not human.db.changeNameCnt then
		human.db.changeNameCnt = 0
	else
		if human.db.zuanshi < CHANGE_NAME_COST then
			msgRet.ret = 1
			Msg.send(msgRet, human.fd)
			return
		end
		human.db.changeNameCnt = human.db.changeNameCnt + 1
		ObjHuman.decZuanshi(human, -CHANGE_NAME_COST, "change_name")
	end

    ObjHuman.onlineHuman[human.db.name] = nil
    ObjHuman.onlineHuman[name] = human

	human.db.name = name
    human.db.sex = sex
    
    RoleHeadLogic.setHead(human, sex, RoleHeadLogic.HEAD_TYPE_1)
	ObjHuman.save(human)
    
    ChatPaoMaLogic.loginTips(human)

    -- 好友推荐  todo
    RelationGiftLogic.relationBind(human, firendCode)
    msgRet.ret = 0
    Msg.send(msgRet,human.fd)

    -- 记录流失日志
    if human.db.changeNameCnt == 0 then
		-- Log.write(Log.LOGID_OSS_REGISTER, human.db._id, human.db.account, human.db.name, human.ip,human.pf or "",human.appid, human.db.changeNameCnt)
		-- Log.write(Log.LOGID_OSS_CREATELOSS,human.db.account, human.db.name, LogDefine.HUMAN_LOST.CREATE_NAME_FINISH, human.db.ip,human.pf or "",human.appid, human.phpChanelID)
		-- ReportManager.create(human)
		-- Log.write(Log.LOGID_OSS_LOGIN, human.db._id, human.db.account, human.db.name, human.db.lv, human.db.ip)

		Log.write(Log.LOGID_OSS_REGISTER, human.db._id, human.db.newUniqueTag, human.db.name, human.ip,human.pf or "",human.appid, human.db.changeNameCnt)
		Log.write(Log.LOGID_OSS_CREATELOSS,human.db.newUniqueTag, human.db.name, LogDefine.HUMAN_LOST.CREATE_NAME_FINISH, human.db.ip,human.pf or "",human.appid, human.phpChanelID)
		ReportManager.create(human)
		Log.write(Log.LOGID_OSS_LOGIN, human.db._id, human.db.newUniqueTag, human.db.name, human.db.lv, human.db.ip)
	end
end


function createRoleSettingUp(human)
   -- 赠送新英雄 上阵
   local heroId = SysParameter.getSysParameter(SysParameter.PARAMETER_8)
   if heroId and heroId ~= 0 then
      local bagIndex, uuid = HeroLogic.addHero(human, heroId,nil, 1, "create_role")
      if bagIndex and uuid and type(uuid) == "string" then
         local msg = {}
         msg.type = CombatDefine.COMBAT_TYPE1
         msg.formation = 1
         msg.heroList = "0,"..uuid
         msg.helpList = ""
         msg.jibanList = ""
         CombatPosLogic.updatePos(human, msg)
      end
   end
end



RANDOM_HEAD_ID_TABLE = nil
function getRandomHead()
	if RANDOM_HEAD_ID_TABLE == nil then
		RANDOM_HEAD_ID_TABLE = {}
		for k, v in pairs(RoleExcel.head) do
			RANDOM_HEAD_ID_TABLE[#RANDOM_HEAD_ID_TABLE + 1] = k
		end
	end

	local index = math.random(1, #RANDOM_HEAD_ID_TABLE)
	return RANDOM_HEAD_ID_TABLE[index]
end



RANDOM_HEADFRAME_ID_TABLE = nil
function getRandomHeadFrame()
	if RANDOM_HEADFRAME_ID_TABLE == nil then
		RANDOM_HEADFRAME_ID_TABLE = {}
		for k, v in pairs(RoleExcel.headFrame) do
			RANDOM_HEADFRAME_ID_TABLE[#RANDOM_HEADFRAME_ID_TABLE + 1] = k
		end
	end

	local index = math.random(1, #RANDOM_HEADFRAME_ID_TABLE)
	return RANDOM_HEADFRAME_ID_TABLE[index]
end



RANDOM_BODY_ID_TABLE = nil
function getRandomBody()
	if RANDOM_BODY_ID_TABLE == nil then
		RANDOM_BODY_ID_TABLE = {}
		for k, v in pairs(RoleExcel.body) do
			RANDOM_BODY_ID_TABLE[#RANDOM_BODY_ID_TABLE + 1] = k
		end
	end

	local index = math.random(1, #RANDOM_BODY_ID_TABLE)
	return RANDOM_BODY_ID_TABLE[index]
end