跳转到内容

模組:MilAward

维基百科,自由的百科全书

require('strict')
local p = {}
local data = mw.loadData('Module:MilAward/data')
local getArgs = require('Module:Arguments').getArgs
local GlobalTemplateArgs = '' -- 定义为模块级全局变量

function p.GraphData (frame)
    -- 此例程仅用于生成按国家统计条目数量的图表 x 和 y 数据行
    -- 它遍历数据,统计每个国家的条目数量,然后
    -- 创建两行以逗号分隔的值表示这些数据
    -- 此函数应仅生成两行包含图表数据的文本,
    -- 并应在图表设置的正确位置调用。

    -- 创建空的本地表 "StatCount"
    local StatCount = {}
    
    -- 遍历数据表 "data"
    for code, record in pairs(data) do
        local country = record.Country
        -- 检查该国家是否已在 StatCount 中
        if StatCount[country] then
            -- 若已存在,则计数加一
            StatCount[country] = StatCount[country] + 1
        else
            -- 若不存在,则将其加入表并赋值为 1
            StatCount[country] = 1
        end
    end
    local xGraphValues = "| x=" -- 创建图表的 x 值行开头
    local yGraphValues = "| y=" -- 创建图表的 y 值行开头
    -- 使用 pairs 遍历 StatCount 表
    for country, count in pairs(StatCount) do
        xGraphValues = xGraphValues .. ", " .. country -- 将国家名添加为逗号分隔值
        yGraphValues = yGraphValues .. ", " .. count -- 将国家计数添加为逗号分隔值
    end
    local output =  " \n" .. xGraphValues .. " \n" .. yGraphValues .. "\n"
    return output
end

function p.Stats(frame)
    -- 创建空的本地表 "StatCount"
    local StatCount = {}
    
    -- 遍历数据表 "data"
    for code, record in pairs(data) do
        local country = record.Country
        -- 检查该国家是否已在 StatCount 中
        if StatCount[country] then
            -- 若已存在,则计数加一
            StatCount[country] = StatCount[country] + 1
        else
            -- 若不存在,则将其加入表并赋值为 1
            StatCount[country] = 1
        end
    end
    
	-- 创建空表存储维基表格行
    local wikiRows = {}
local xGraphValues =''
local yGraphValues =''
    -- 使用 pairs 遍历 StatCount 表
    for country, count in pairs(StatCount) do
        -- 将国家和计数数据作为一行加入 wikiRows 表
        table.insert(wikiRows, "|-\n|" .. country .. "||" .. count)
         xGraphValues = xGraphValues .. ", " .. country
         yGraphValues = yGraphValues .. ", " .. count
    end

    -- 使用 wikiRows 表创建表格的维基代码
    local wikiCode = "{| class=\"wikitable sortable col2right\"\n|-\n! 国家 !! 数量\n" .. table.concat(wikiRows, "\n") .. "\n|}"
    local wikiCode = wikiCode .. " \n" .. xGraphValues .. " \n" .. yGraphValues .. "\n"

    -- 返回维基代码
    local tablist= p.PrintStats()
    local output = wikiCode .. "\n\n" .. tablist
    return output
end

function p.PrintStats()
    -- 将键值对转换为 {code, data[code]} 对的列表
    local pairsList = {}
    for code, values in pairs(data) do
        table.insert(pairsList, {code, values})
    end

    -- 根据每对的 "Description" 字段对列表排序
    table.sort(pairsList, function(a, b)
        return a[2].Description < b[2].Description
    end)

    -- 为排序后的列表生成维基表格代码
    local tableCode = "{| class=\"wikitable sortable\"\n"
    tableCode = tableCode .. "|-\n"
    tableCode = tableCode .. "! 代码 !! 旧代码 !! 描述 !! 国家\n !! 名后勋衔 !! 勋带 !! 组织\n"

    for i, pair in ipairs(pairsList) do
        local code, values = pair[1], pair[2]
        local oldcode = values.Code or ""
        local country = values.Country or ""
        local description = values.Description or ""
        local class = values.Class or ""
        local postnom = values.PostNom or ""
        local ribbonimage = values.RibbonImage or ""
        local pagelink = values.PageLink or ""
        local note = values.Note or ""
        local org = values.Org or ""

        tableCode = tableCode .. "|-\n"
        tableCode = tableCode .. "|" .. code .. "\n"
        if code == oldcode then
        	tableCode = tableCode .. "| \n"
        else
        	tableCode = tableCode .. "|" .. oldcode .. "\n"
        end
        tableCode = tableCode .. "|[[" .. pagelink .. "|" .. description 
        if string.len(class) > 0 then
        	tableCode = tableCode .. "]] '''(" .. class .. ")'''"
		else
        	tableCode = tableCode .. "]]"
        end
        if string.len(note) > 0 then
            tableCode = tableCode .. mw.getCurrentFrame():expandTemplate{ title = 'Efn', args = {note} } -- 注意:页面需要 {{notelist}}
        	--tableCode = tableCode .. " <sup>" .. note .. "</sup> " 
        end
        tableCode = tableCode .. "\n"
        tableCode = tableCode .. "|" .. country .. "\n"
        tableCode = tableCode .. "|" .. postnom .. "\n"
        tableCode = tableCode .. "|[[File:" .. ribbonimage .. "|x30px]]\n"
        tableCode = tableCode .. "|" .. org .. "\n"
    end

    tableCode = tableCode .. "|}"
    return tableCode
end

function p.Display(frame)
	-- 从 frame 中取出参数并传递给 p._Display(),返回结果。
	local templateArgs = getArgs(frame)
	--local templateArgs = frame.args
	local code = templateArgs[1] or 'None'
	local size = templateArgs[2] or "40px"
	local namedcode = templateArgs["code"]
	if namedcode then 
		code = namedcode
	end
	local namedsize = templateArgs["size"]
	if namedsize then
		size = namedsize
	end
	return p._Display(code, size)
end

function p._Display(code, size)
    -- data 全局加载
    
    local output = ""
            output = output .. " '''找到奖项代码''': " .. data[code].Code .. "<br />"
            output = output .. "''代码'': " .. data[code].Code .. "<br />"
            output = output .. "''描述'': " .. data[code].Description .. "<br />"
            output = output .. "''勋带图像'': " .. data[code].RibbonImage .. "<br />"
            output = output .. "''名后勋衔'': " .. data[code].PostNom .. "<br />"
            output = output .. "''页面链接'': " .. data[code].PageLink .. "<br />"
            output = output .. "''国家'': " .. data[code].Country .. "<br />"
    return output
end

local function _Ribbon(code, size)
	local ribbonimage=data[code].RibbonImage
	if string.len(size) <1 then 
		size="x12px" -- 防止 size 无值,设置默认值
	end
	if string.len(ribbonimage)<1 then  -- 若无勋带图像,则指定默认图像
		ribbonimage = "NOT-AVAILABLE-RIBBON.svg"
	end
    local output = "[[File:" .. ribbonimage .. "|".. size .. "|link=" .. data[code].PageLink .. "|" .. data[code].Description .. " ''" .. data[code].PostNom .. " ''" .. "]]" -- .. " [[Category:MilAward Ribbon]]"
    return output
end

function p.Ribbon(frame)
	-- 从 frame 中提取参数
	-- 检查第一个参数不为空,否则返回错误
	local templateArgs = getArgs(frame)
	--local templateArgs = frame.args
	local code = templateArgs[1] or 'None'
	local size = templateArgs[2] or "x12px"
	
    local namedcode = templateArgs["code"] -- 检查命名参数 "code",若有值则覆盖
	if namedcode then 
		code = namedcode
	end

	local namedsize = templateArgs["size"] -- 检查命名参数 "size",若有值则覆盖
	if namedsize then
		size = namedsize
	end

	if string.match(code, "%*") then -- 代码字段含星号,报错
		-- code = string.gsub(code, "%*", "x")
		local output = '<span style="color:#d33"> 错误代码:<b>[' .. code .. ']</b>。请将所有 * 替换为 x</span> [[Category:MilAward Error]]'
		return output
	end -- End if

	if not code or '' == code then
		-- return '<span style="color:#d33">Error: missing positional parameter 1</span>'
		return '<span style="color:#d33"> (无效代码:<b>' .. code .. '</b>)</span> [[Category:MilAward Error]]'
	end

--	local code = code:upper() -- 不要这样做,代码区分大小写
	if not data[code] then
		-- return '<span style="color:#d33">Error: invalid positional parameter 1: ' .. code .. '</span>'
		return '<span style="color:#d33"> (未找到代码:<b>' .. code .. '</b>)</span> [[Category:MilAward Error]]'
	end
	return _Ribbon (code, size)
end


local function _RibbonDesc(code, size, country, norib, nocat, org)
    -- 此例程负责数据输出格式
    local output =''
    if norib ~= "yes" then -- 若为 yes 则不显示勋带
    	output = output .. _Ribbon(code, size) -- 首先获取勋带
    end
    local output = output ..  " [[" .. data[code].PageLink .. "|" .. data[code].Description .. "]] "  -- 添加页面链接和描述
    if data[code].Class then
    	if string.len(data[code].Class) > 0 then -- 仅当 Class 字段有内容时添加
    		output = output .. " (''" .. data[code].Class .. "'') " 
    	end
    end
    if string.len(data[code].PostNom) > 0 then -- 仅当 PostNom 有内容时添加
    	 output = output .. " ('''" .. data[code].PostNom .. "''') " 
    end

    if string.len(data[code].Note) > 0 then -- 仅当 Note 有内容时添加
    	output = output .. mw.getCurrentFrame():expandTemplate{ title = 'Efn', args = {data[code].Note} } -- 注意:页面需要 {{notelist}}
		-- output = output .. "<sup>" .. data[code].Note .. "</sup> " 
    end
    if string.len(country) > 0 then -- 若指定了国家参数
        if country:upper() ~= data[code].Country:upper() then -- 检查指定国家是否与记录不符
            output = output .. " (" .. data[code].Country .. ") " -- 在输出末尾添加国家代码
        end
    end
    if string.len(org) > 0 then -- 若指定了组织参数
        if org:upper() == "YES" then -- 检查是否为 YES
            if string.len(data[code].Org) > 0 then -- 检查 Org 字段是否有内容
                output = output .. " (''" .. data[code].Org .. "'') " -- 在输出末尾添加组织
            end
        end
    end
    

-- 优化代码。string.len 较昂贵
local nocat_length = string.len(nocat)
if nocat_length > 1 then -- 若 nocat 有任何值则视为真
    -- 不执行任何操作或添加追踪分类
else
    -- 需排除非主命名空间添加获得者分类
    -- 目前仅检查不在 "Template:" 或 "User:" 空间
    local current_title = mw.title.getCurrentTitle()
    local namespace = current_title.nsText
    local namespace_length = string.len(namespace)
    if namespace_length < 2 then
        local recipcat = data[code].RecipCat or "" -- 若指定了获得者分类则添加到输出
        local categories = {}
        --categories[#categories+1] = " [[Category:MilAward Ribbon Description]]" -- 添加追踪分类(已注释)
        if string.len(recipcat) > 0 then
            local categoryTitle = mw.title.new('Category:' .. mw.text.trim(recipcat))
            if categoryTitle.exists and not categoryTitle.isRedirect then
                -- 分类存在且非重定向
                categories[#categories+1] = " [[Category:" .. recipcat .. "]]"
            else
                -- 分类不存在或是重定向
                -- 添加到追踪分类?
            end
        end
        output = output .. table.concat(categories)
    end
end

    return output
end

function p.RibbonDesc(frame)
	local templateArgs = getArgs(frame)
	-- local templateArgs = frame.args
    local code = 'Unknown' -- 初始化 code 变量
    local size = 'x20px' -- 初始化 size 变量
	if templateArgs[1] then code = templateArgs[1] end -- 若非 nil 则赋值
    if templateArgs[2] then size = templateArgs[2] end -- 若非 nil 则赋值

	local namedcode = templateArgs["code"] -- 获取命名参数 code
	if namedcode then  -- 若存在则覆盖
		code = namedcode
	end

	local namedsize = templateArgs["size"] -- 同上
	if namedsize then
		size = namedsize
	end

    local namedcountry = templateArgs["country"] or '' -- 获取 country 参数
    local country = namedcountry
    local norib = templateArgs["norib"] or ''
	if not size then size = "x20px" end -- 设置默认值

	if not code or '' == code then -- 若无 code 则返回错误
	--	 '<span style="color:#d33">Error: missing positional parameter 1</span>'
		local output =  '<span style="color:#d33"> (无效代码:<b>' .. code .. '</b>)</span>'
        return output
	end
	if string.match(code, "%*") then -- 代码含星号报错
		local output = '<span style="color:#d33"> 错误代码:<b>[' .. code .. ']</b>。请将所有 * 替换为 x</span> [[Category:MilAward Error]]'
		return output
	end -- End if

--	local code = templateArgs[1]:upper() -- 不要转为大写,代码区分大小写
	if not data[code] then
	--	return '<span style="color:#d33">Error: invalid positional parameter 1: ' .. code .. '</span>'
		return '<span style="color:#d33"> (未找到代码:<b>' .. code .. '</b>)</span>'
	end

    local nocat= templateArgs["nocat"] or '' -- 获取 nocat 参数
    local org=templateArgs["org"] or '' -- 获取 org 参数

	return _RibbonDesc (code, size, country, norib, nocat, org)
end

function p.Stack(frame)
    GlobalTemplateArgs = getArgs(frame)
    -- local size = GlobalTemplateArgs[1] or "x12px"
    local size = "x12px"
    local namedsize = GlobalTemplateArgs["size"]
    if namedsize then
        size = namedsize
    else
        size = "x12px"
    end

    local output = ''

    local RibbonList = {}
    for i = 1, 40 do -- 最多检查40个参数
        local rl = GlobalTemplateArgs[i] or ""
        if rl ~= "" then
            table.insert(RibbonList, rl)
        end
    end
    local row={}
    for i, rl in ipairs(RibbonList) do
        if rl ~= "" then
            if data[rl] then -- 检查是否存在于数据中
			    local rowoutput = _Ribbon(rl, size) 
			    table.insert(row,string.format('%s',rowoutput) )
            end
        end
    end
    output = table.concat(row, " ")

    --output = output .. "[[Category:MilAward Stack]]" -- 添加追踪分类
    return output
end

function p.DescList(frame)
    local templateArgs = getArgs(frame)
    local size = templateArgs["size"] or 'x20px'
    local namedcountry = templateArgs["country"] or 'yes'
    local output = '\n'

    for key, value in pairs(templateArgs) do
        if string.len(value) > 1 and data[value] then
                output = output .. "* " .. _RibbonDesc(value, size, namedcountry,'','','') .. "\n"
        end
    end
    return output
end

function p.PostNom(frame)
    local templateArgs = getArgs(frame)
    local size = templateArgs["size"] or '85%'
    local sep = templateArgs["sep"] or ', '
    if sep == "none" then
        sep = " "
    end
    local output = '<span class="noexcerpt nowraplinks" style="font-size:' .. size .. '; font-weight:normal;">'

    for key, value in pairs(templateArgs) do
        if key ~= "size" and string.len(value) > 1 and data[value] then
            if string.len(data[value].PostNom) > 1 then
                output = output .. "[[" .. data[value].PageLink .. "|" ..  data[value].PostNom .. "]]" .. sep .. ""
            end
        end
    end
    local seplen = (string.len(sep) + 1) * -1 -- 获取分隔符长度,加一后取负值
    output = output:sub(1, seplen) -- 移除末尾分隔符
    output = output .. '</span>'

    return output
end

-- 初始代码由 John Dovey(2023年4月13日)[[User:BoonDock]] 编写
return p