local uiCtrlProvider = XLGetGlobal("xunlei.UIControlProvider")
local timerManager = XLGetObject("Xunlei.UIEngine.TimerManager")
local osShell = XLGetObject('Xunlei.UIEngine.OSShell')
local addinmanager = XLGetObject( "Xunlei.Thunder.AddinManager" )
local category = uiCtrlProvider.GetCategory()
local tabCtrl = uiCtrlProvider:GetMainWndTab()
local mallCategory = nil
local mallCategoryId = "Category.Mall.Id"
local mallItemId = "mall.term.id"
local IsXarAndDllLoad = false
local IsCategoryLCLK = false
-- 创建插件的临时文件夹
local tempfilepath = addinmanager:GetAddinsTempPath("MallAddin")
if not osShell:QueryFileExists(tempfilepath) then
	osShell:CreateDir(tempfilepath)
end
--/////////////////////////////////////
-- 在迅雷入口
--/////////////////////////////////////
-- 左侧面板入口
function mallCategoryLCLK()
	if IsXarAndDllLoad == false then
		LoadXarAndDll(1)
		return
	end
	
	local objXLUser = XLGetObject("Xunlei.XLUser.Factory")
	local classUser = objXLUser:CreateInstance()
	if classUser then
		local bLogin = classUser:IsLogIn()
		if bLogin == true then
			--还需要判断userid是否已经取到，如果没有则按照未登陆处理
			local userinfo = classUser:GetUserInfo()
			local userId = userinfo:GetUserID()
			if userId == nil or userId == 0 then
				OpenXLFXTab("http://shop.xunlei.com/thunder/index.html?fref=xl_0002", "")
			else
				HanlderMallUeTab(21,"LCLK")
				IsCategoryLCLK = true
			end
		else
			OpenXLFXTab("http://shop.xunlei.com/thunder/index.html?fref=xl_0002", "taskBarInit")
		end
	end
end
function IsCategoryLOnClick()
	return IsCategoryLCLK
end
XLSetGlobal("Fx.IsCategoryLOnClick",IsCategoryLOnClick)

function SetCategoryLOnClick(flag)
	IsCategoryLCLK = flag
end
XLSetGlobal("Fx.SetCategoryLOnClick",SetCategoryLOnClick)

--Toolbar入口
function InsertToolBarMallButton()
	local toolBar = uiCtrlProvider:GetToolbar()
	local function OnToolbarClickMallButton(toolbar,eventName,buttonID)
		if buttonID == "Fx.Toolbar.Button.Mall" then
			MallOnClick(nil,nil,nil,true,"http://shop.xunlei.com/thunder/index.html?fref=xl_0003")
		end
	end
	toolBar:AddToolbarButton("Fx.Toolbar.Button.Mall", "", false, true, "数字商城", "数字商城", "malladdin.toolbar.button.icon.normal", "malladdin.toolbar.button.icon.small", "malladdin.toolbar.ani", nil,nil,99)
	toolBar:AttachListener("OnToolBarButtonClick",true,OnToolbarClickMallButton)
end

-- 刷新数字商城的Web页面
function RefreshMallPage(refreshType, jumpKey)
	local fxmallpage = tabCtrl:GetTabObject("数字商城")
	if fxmallpage then
		fxmallpage:RefreshWebPage(nil,refreshType)
	end
end
XLSetGlobal("Fx.RefreshMallPage", RefreshMallPage)

-- 添加数字商城页，如果已经存在就返回1，否则返回0
local function AppendFxUeItem(title)
	local objFactory = XLGetObject("Xunlei.UIEngine.ObjectFactory")
    local index = tabCtrl:GetItemPosByTitle(title)
    if index ~= -1 then
		local tab = tabCtrl:GetItem(index)
		if tab ~= nil then
			local attr = tab:GetAttribute()
			local obj = attr.Object
			if obj ~= nil and obj:GetClass() == "Thunder.FxMallPage" then
				tabCtrl:SelectItem(index)
				return 1
			end
		end
    end
	local mallpage = objFactory:CreateUIObject("maintab.Fx."..title, "Thunder.FxMallPage")
	--mallpage:SetUrl(url)
	tabCtrl:AppendItem(title, mallpage, mallItemId)
	mallpage:SetTabHeight(0) 
	local index = tabCtrl:GetItemPosByTitle(title)
	if index~=-1 then
		tabCtrl:SelectItem(index)
	end
	return 0
end
-- 标签或插件管理入口点击处理函数
function MallOnClick(self,eventname,param1,isRefresh,url)
	if IsXarAndDllLoad == false then
		LoadXarAndDll(4,nil,nil,url,nil,nil,isRefresh)
		return
	end
	local ret = AppendFxUeItem("数字商城")
	local fxmallpage = tabCtrl:GetTabObject("数字商城")
	if fxmallpage then
		if ret == 0 then
			fxmallpage:WebPageSetExternal()
			if isRefresh ~= false then
				if url ~= nil and url ~= "" then
					fxmallpage:RefreshWebPage(url,"")
				else
					fxmallpage:RefreshWebPage(nil,"")
				end
			end
		end
	end
end

-- 提供接口供其他模块在必要的时候打开数字商城Web页面tab并进行刷新
function OpenXLFXTab(url,refreshType,from)
	if IsXarAndDllLoad == false then
		LoadXarAndDll(3,nil,nil,url,refreshType,from)
		return
	end
	if tabCtrl == nil then return end
	MallOnClick(nil,nil,nil,false,nil)
	local fxmallpage = tabCtrl:GetTabObject("数字商城")
	if fxmallpage then
		fxmallpage:RefreshWebPage(url,refreshType)
		local panel_obj = fxmallpage:GetControlObject("thunder.fxmallpagepanel")
		panel_obj:SelectTable("数字商城")
	end
end
XLSetGlobal("FX_OpenXLFXTab", OpenXLFXTab)

-- 提供接口供其他模块在必要的时候打开数字商城UE页面tab
-- _type = 0 关闭"发行管理"页面
-- _type = 1 打开管理页面并定位到先前的页面 11 定位到付费订单 12 定位到免费订单
-- _type = 2 打开管理页面并定位到"任务管理页面" 21 定位到正在下载 22 定位到已下载
-- _type = 3 加载
function DoMallTabChange(_type,reason)
	if _type then
		local fxmallpage = tabCtrl:GetTabObject("数字商城")
		if fxmallpage then
			fxmallpage:HandleTabChange(_type,reason)
		end
	end
end
function HanlderMallUeTab(_type,reason)
	if IsXarAndDllLoad == false then
		LoadXarAndDll(2,_type,reason,nil,nil,nil)
		return
	end
	if _type ~= 0 then
		if reason == "LCLK" then
			MallOnClick(nil,nil,nil,true,"http://shop.xunlei.com/thunder/index.html?fref=xl_0002")
		else
			MallOnClick(nil,nil,nil,true,nil)
		end
	end
	DoMallTabChange(_type,reason)
end
XLSetGlobal("Fx.HanlderMallUeTab",HanlderMallUeTab)

function OnTabClose(title, tabobj)
	if title == "数字商城" then
		local xlConfig = XLGetObject("Xunlei.Thunder.Config")
		local activetasknum = 0
		local retvalue = true
		function OnMsgInit(hostWndTemplate, objectTree)
			local textObj = objectTree:GetUIObject("msgboxdlg.message")
			local checkObj = objectTree:GetUIObject("msgboxdlg.checkbox")
			if textObj then
				textObj:SetVAlign("top")
				textObj:SetEndEllipsis(false)
				textObj:SetWordEllipsis(false)
				textObj:SetMultiline(true)
				textObj:SetText("数字商城中有" .. activetasknum .. "个任务正在下载。\n\t你确定退出吗？")
				local left, top, right, bottom = textObj:GetObjPos()
				textObj:SetObjPos(left, top, right, top + 100)
			end
			if checkObj then
				checkObj:SetText("下次不再提示")
			end
		end
		function OnMsgDlgDes(hostWndTemplate, objectTree, ret)
			if ret == 1 or ret == 2 then
				retvalue = true
				if ret == 2 then
					xlConfig:SetValue("malladdininfo", "showclosetabtip", 1)
				end
			else
				retvalue = false
			end
		end
		local mallFactory = XLGetObject("MallAddin.MallFactory")
		if mallFactory then
			local mall = mallFactory:GetMall()
			if mall ~= nil then
				local ret = mall:Invoke("GetAllActiveTaskTotalNum")
				if ret and ret["ret"] then
					activetasknum = ret["ret"]
				end
			end
		end
		if activetasknum < 1 then
			return true
		end
		local showclosetabtip = xlConfig:GetValue("malladdininfo", "showclosetabtip", 0)
		if showclosetabtip == 1 then
			return true
		end		
		local hostWndHelper = XLGetGlobal("xunlei.LuaHostWndHelper")
		hostWndHelper:DoModal("MsgBoxDlg", "MsgBoxDlgTree", nil,OnMsgInit, OnMsgDlgDes,true)
		return retvalue
	end
end
function OnPreLogoutEventFunc()
	local activetasknum = 0
	local mallFactory = XLGetObject("MallAddin.MallFactory")
	if mallFactory then
		local mall = mallFactory:GetMall()
		if mall ~= nil then
			local ret = mall:Invoke("GetAllActiveTaskTotalNum")
			if ret and ret["ret"] then
				activetasknum = ret["ret"]
			end
		end
	end
	if activetasknum < 1 then
		return false
	else
		return true,"数字商城中有" .. activetasknum .. "个任务正在下载。"
	end
end
-- 与迅雷7入口交互
local helper = XLGetGlobal( "xunlei.AddinManagerHelper" )
helper.RegisterServiceEx( "MallAddin", "数字商城", "logo.png", "提供正版高质的影视、游戏等数字产品高速送达服务，让迅雷用户体验更美好的数字生活。", MallOnClick, nil, true)
tabCtrl:AddPlugin("", "", "数字商城", MallOnClick, nil , mallItemId)
-- 注册tab Pre关闭事件
tabCtrl:SetPreCloseFunc("数字商城",OnTabClose)
-- 注册Pre注销事件
local eventId = helper.AttachThunderLogoutEvent(OnPreLogoutEventFunc)

-- 添加迅雷7左侧面板入口
if category and false == category:IsCategoryItemExist(mallCategoryId) then
	mallCategory = category:AddCategoryItem("商城任务", mallCategoryId, "malladdin.icon.category", mallCategoryLCLK, mallCategoryLCLK, mallItemId, 1)
end
local OldText = "商城任务"
function UpdateCategoryText(text)
	if text == OldText then return end
	OldText = text
	if category:IsCategoryItemExist(mallCategoryId) then
		category:UpdateCategoryItem(mallCategoryId,nil,nil,nil,text)
	end
end
XLSetGlobal("Fx.UpdateCategoryText",UpdateCategoryText)
InsertToolBarMallButton()
 
-- from参数用来指明是哪个函数调用该函数,from = 1 mallCategoryLCLK;from = 2 HanlderMallUeTab;from = 3 OpenXLFXTab; from = 4 MallOnClick
function LoadXarAndDll(from,_type,reason,url,refreshType,from1,IsRefresh)
	local addinManager = XLGetObject("Xunlei.Thunder.AddinManager")
	addinManager:LoadAddinMainDll("MallAddin")
	local theManager = XLGetObject("Xunlei.UIEngine.XARManager")
	theManager:AsynLoadXAR("MallAddin", 
						function (xarName, ret)
							if ret then
								IsXarAndDllLoad = true
								if from == 1 then
									mallCategoryLCLK()
								elseif from == 2 then
									HanlderMallUeTab(_type,reason)
								elseif from == 3 then
									OpenXLFXTab(url,refreshType,from1)
								elseif from == 4 then
									MallOnClick(nil,nil,nil,IsRefresh,url)
								elseif from == 5 then
									XLAddBhoTask()
								end
							end
						end
						)
end

-- 图片标签的按需加载
local g_fxImageAddinTimer = 0
local g_ImageAddinHaveAppend = false
local function AddFxPluginToAddin(addinlayout)
	if g_ImageAddinHaveAppend == true then
		timerManager:KillTimer(g_fxImageAddinTimer)
		return
	end
	function OnExpand(obj, eventName, bExpand)
		local objAddin = XLGetGlobal(addinlayout)
		if objAddin == nil then
			return false
		end
		local objLayout = objAddin:GetExtendLayoutDigitalShopObj()
		if objLayout == nil then
			return false
		end
		local left, top, right, bottom = objLayout:GetObjPos()
					
		if bExpand then
			objLayout:SetObjPos(left, top, right-left, top+225)
		else
			objLayout:SetObjPos(left, top, right-left, top+25)
		end
	end
	
	local objAddin = XLGetGlobal(addinlayout)
	if objAddin == nil then return end
	local objLayout = objAddin:GetExtendLayoutDigitalShopObj()
	if objLayout == nil then return end
	g_ImageAddinHaveAppend = true
	-- 加载FxImageAddin Xar
	local theManager = XLGetObject("Xunlei.UIEngine.XARManager")
	theManager:AsynLoadXAR("FxImageAddin", 
				function (xarName, ret)
					if ret then
						local name = addinlayout..".FxAddinPanel"	
						local objFactory = XLGetObject("Xunlei.UIEngine.ObjectFactory")	
						local fxobj = objFactory:CreateUIObject(name, "Fx.ImageAddin")
						local left, top, right, bottom = objLayout:GetObjPos()
						objLayout:AddChild(fxobj)	
						fxobj:SetObjPos(0, 0, right-left, 225)
						fxobj:AttachListener("OnExpand", true, OnExpand)
					end
				end
				)
	timerManager:KillTimer(g_fxImageAddinTimer)
end
local function AddFxPlugins()
	AddFxPluginToAddin("xunlei.ImageInfoAddin")
end
g_fxImageAddinTimer = timerManager:SetTimer( AddFxPlugins, 1000 )

-- 视频标签的按需加载
local g_fxVideoAddinTimer = 0
local g_VideoAddinHaveAppend = false
function AddFxVideoPlugins()
	if g_VideoAddinHaveAppend == true then
		timerManager:KillTimer(g_fxVideoAddinTimer)
		return
	end
	local objAddin = XLGetGlobal("VideoAddin.DigitalShopObj")
	if objAddin then
		local objLayout = objAddin:GetDigitalShopObj()
		if objLayout then
			g_VideoAddinHaveAppend = true
			-- 加载FxVideoAddin Xar
			local theManager = XLGetObject("Xunlei.UIEngine.XARManager")
			theManager:AsynLoadXAR("FxVideoAddin", 
				function (xarName, ret)
					if ret then
						local videoaddinid = "VideoAddin.DigitalShopObj.FxVideoAddinPanel"
						local objFactory = XLGetObject("Xunlei.UIEngine.ObjectFactory")	
						local gaobj = objFactory:CreateUIObject(videoaddinid, "Fx.VideoAddin")
						local left, top, right, bottom = objLayout:GetObjPos()	
						bottom = top + 90
						objLayout:SetObjPos(left, top, right, bottom)
						objLayout:AddChild(gaobj)	
						gaobj:SetObjPos(0, 0, right-left, 90)
					end
				end
				)
			-- 加载成功，关闭定时器
			timerManager:KillTimer(g_fxVideoAddinTimer)
		end
	end
end
g_fxVideoAddinTimer = timerManager:SetTimer( AddFxVideoPlugins, 1000 )

local g_fxLoadXarTimer = 0
function XLAddBhoTask()
	if IsXarAndDllLoad == false then
		LoadXarAndDll(5)
		return
	end
	local malladdin_obj = XLGetObject("MallAddin.MallFacade")
	if malladdin_obj then
		malladdin_obj:Invoke("AddBhoTask")
	end
end
function DelayLoadXarTime()
	local CommunityCtrl = XLGetGlobal("Community.QuickLogin")
	if (CommunityCtrl == nil) then
		return
	end
	timerManager:KillTimer(g_fxLoadXarTimer)
	g_fxLoadXarTimer = 0
	XLAddBhoTask()
end
-- 商城拉起触发
local xlApp = XLGetObject("Xunlei.Thunder.App")
if xlApp ~= nil then
	xlApp:AttachEvent("OnShellCommand",
		function(key, value)
			if key == "FxAction" then
				if value == "AddTask" then
					if g_fxLoadXarTimer == 0 then
						g_fxLoadXarTimer = timerManager:SetTimer( DelayLoadXarTime, 1000)
					end
				end
			end
		end
	)
end
