Модуль:Анонс

Материал из Справочника наблюдателя
Перейти к:навигация, поиск

(i)      Описание модуля[]
Var

Модуль Анонс обеспечивает реализацию шаблона {{Анонс кампании}} .


local p = {}

local mday = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334}
local gas = require 'Module:GAS'

function lenM (m,y) 
	return ({31, 
		(function ()
			if y%4 == 0 then return 29 else return 28 end -- неверно для 2100 года :-)
		end) (), 
		31, 30, 31, 30, 31, 31, 30, 31, 30, 31}) [m]
end

local nameM = { 'январь', 'февраль', 'март', 'апрель', 'май', 'июнь', 'июль', 'август', 'сентябрь', 'октябрь', 'ноябрь', 'декабрь'}




function p.campaign (frame)
	
	local res = ''
	local args -- = frame.args
--    if frame == mw.getCurrentFrame() then -- это всегда кроме консоли (и, возможно, внутренних вызовов)
        args = frame:getParent().args
--        args = frame.args
--    end
    
	local day = args ['дата'] or '31.12.2014'
	local dayN, dayD, dayM, dayY = date2number (day)
	local name = args ['местность'] or ''
	local address = args ['адрес'] or ''
	local region = args ['область'] or ''
	local url = gas._Page( args ['ГАС'] or '' )
	local elections = args ['кампания'] or ''
	local url1 = gas._Page( args ['ГАС1'] or '' )
	local elections1 = args ['кампания1'] or ''
	local url2 = gas._Page( args ['ГАС2'] or '' )
	local elections2 = args ['кампания2'] or ''
	local distance = args ['расстояние'] or ''
	local transfer = args ['проезд'] or ''
	local offices = args ['участков'] or ''
	local voters = args ['избирателей'] or ''
	local comment = args ['примечание'] or ''
	local page = args ['страница'] or ''
	local oldDay = frame:callParserFunction( '#var', 'announce-date' )
	local oldD,oldM,oldY,index -- заполняется из var

	local finita = args [1]
	local forma 
	if finita == 'начало' then
		forma = args ['format'] or ''
		frame:callParserFunction( '#vardefine', 'announce-format', forma )
		return ''
	else
		forma = frame:callParserFunction( '#var', 'announce-format' )
	end
	if forma ~= 'table' and forma ~= 'calendar' and forma ~= 'map' then
		forma = 'table'
	end
--[[	
	local forma = args ['format']
	if not forma then
		forma = frame.args['format']
	end
	if forma ~= 'table' and forma ~= 'calendar' then
		forma = 'table'
	end
--]]	
	
	
	local starta = oldDay == ''
	
	if finita == 'конец' and starta then
		return ''
	end
	
	
	
	if starta then
--		res = campaignHeader (forma)
		if forma == 'calendar' then
			res = '<table style="border-collapse: collapse"><tr>'
		elseif forma == 'table' then
			res = [==[<table class="wikitable sortable" style="font-size:90%; width:100%"><tr>
        	      <th>дата</th>
            	  <th>место</th>
	              <th>кампания</th>
    	          <th>расст.</th>
        	      <th>проезд</th>
            	  <th>УИКов</th>
	              <th>числ.</th>
    	          <th>примечание</th>
        	    </tr>]==]
		elseif forma == 'map' then
			res = '' -- <!-- перед вызовом шаблонов должен стоять текст «{{#multimaps:» -->
		end
		---- Заносим в oldDay данные последнего воскресенья предыдущего месяца		
		if dayM == 1 then
			oldM, oldY = 12,dayY-1
		else
			oldM,oldY = dayM-1,dayY
		end
		oldD = dayD % 7
		if oldD == 0 then 
			oldD = 7
		end
		oldD = lenM (oldM,oldY) - 7 + oldD
		index = 42
	else
		local dmyi= mw.text.split(oldDay,',',true)
		oldD,oldM,oldY,index = tonumber(dmyi[1]),tonumber(dmyi[2]),tonumber(dmyi[3]),tonumber(dmyi[4])
		if finita == 'конец' then
			dayD,dayM,dayY = oldD + math.floor ((lenM (oldM,oldY) - oldD) / 7) * 7,oldM,oldY
		end
	end
	
	if finita ~= 'конец' then
		if dayD == 32 then
			return '<p style="color:red; font-size:120%; font-weight:bold">Не воскресенье! ' .. day .. ' — ' .. name .. ' (' .. region ..')</p>'
		elseif dayM == 13 then
			return '<p style="color:red; font-size:120%; font-weight:bold">Плохой формат даты! ' .. day .. ' — ' .. name .. ' (' .. region ..')</p>'
		elseif not (dayY > oldY or (dayY == oldY and (dayM > oldM or (dayM == oldM and dayD >= oldD)))) then 
			return '<p style="color:red; font-size:120%; font-weight:bold">Неверная последовательность дат! ' .. day .. ' — ' .. name .. ' (' .. region ..')</p>'
		end
	end
	

	if forma == 'calendar' then
		local monthBlock = ''
		while oldD ~= dayD or oldM ~= dayM or oldY ~= dayY do
			oldD = oldD + 7
			local xx = lenM (oldM, oldY)
			if oldD > xx then
				oldD = oldD - xx
				oldM = oldM + 1
				if oldM == 13 then
					oldM = 1
					oldY = oldY + 1
				end
-- http://www.vybory.izbirkom.ru/region/izbirkom?s_day=1&s_month=02&s_year=2014&urovproved=all&vidvibref=all&vibtype=all&f_day=28&f_month=02&f_year=2014&sxemavib=all&action=search_by_calendar				
				monthBlock = '<th rowspan='.. math.floor ((lenM (oldM, oldY) + 7 - oldD) / 7) 
								.. ' style="border:1px solid grey; background:#eef;">&nbsp;'
								..'[http://www.vybory.izbirkom.ru/region/izbirkom?urovproved=all&vidvibref=all&vibtype=all&sxemavib=all&action=search_by_calendar'
								.. '&s_year=' .. oldY .. '&f_year=' .. oldY .. '&s_month=' .. oldM .. '&f_month=' .. oldM 
								.. '&s_day=' .. 1 .. '&f_day=' .. lenM (oldM, oldY) .. ' '
								.. nameM[oldM] .. ']&nbsp;</th>'
				
			end
			-- формируем пустую строку
			if not starta then
				res = res .. ' &nbsp; &nbsp;</td></tr>'
			end
			res = res .. '<tr style="border:1px solid grey">' .. monthBlock .. '<th style="border:1px solid grey; background:#eef" class=plainlinks>&nbsp;' 
						..'[http://www.vybory.izbirkom.ru/region/izbirkom?urovproved=all&vidvibref=all&vibtype=all&sxemavib=all&action=search_by_calendar'
						.. '&s_year=' .. oldY .. '&f_year=' .. oldY .. '&s_month=' .. oldM .. '&f_month=' .. oldM 
						.. '&s_day=' .. oldD .. '&f_day=' .. oldD .. ' '
						.. oldD .. ']&nbsp;</th><td style=line-height:100%;vertical-align:middle;">&nbsp;'
						.. '<div style="display:inline-block;">&nbsp;<p style="font-size:82%; line-height:95%; margin-bottom:0;">&nbsp;</p></div>'
			monthBlock = ''
		end
	elseif forma == table then
		if oldD ~= dayD or oldM ~= dayM or oldY ~= dayY then
			res = res .. '<tr><td></td></tr>'
		end
	elseif forma == 'map' then
		
	end
	if finita == 'конец' then
		frame:callParserFunction( '#vardefine', 'announce-date', '')
		if forma == 'calendar' then
			return res .. '</td></tr></table>'
		elseif forma == 'table' then
			return res .. '</table>'
		elseif forma == 'map' then
--			return frame:preprocess ('55.1456306645,37.4837100506~3240~ул. Чехова, д. 8а, гимназия № 2~icon=/E/3/uik3240-e.png|height=750px|service=yandex|icon=:39,30:11,30')
			return '' -- <!-- после всех шаблонов должен стоять текст «|height=750px|service=yandex}}» -->
		end
		
	end
	
	if forma == 'calendar' then
-- Уже открыта текущая дата (то есть у нас уже начата строка)
		local bold
		if page == '' then
			bold = ''
		else
			bold = "'''"
		end
			
		res = res .. ' &nbsp; &nbsp; <div style="display:inline-block; line-height:100%"><span style="cursor:pointer;" class="mw-customtoggle-announce' .. index .. '"> ' .. bold .. name .. bold
						.. '&nbsp;<div style="float:right; color:#0B0095">[+]</div>&nbsp; </span> ' .. '<p style="font-size:82%; line-height:95%; font-style:italic; margin-bottom:0;">' .. region ..'</p>'
						.. '<div id="mw-customcollapsible-announce' .. index
						.. '" class="mw-collapsible mw-collapsed" style="z-index:5; margin-left:2em; max-width:300px; position:absolute; '
						.. 'background-color:LightYellow; border:1px dotted black; padding:0.5em; display:none; font-size:88%; line-height:105%;"'
						.. '><div style="float:right; margin:0 0 1ex 1ex; color:#0B0095; cursor:pointer" class="mw-customtoggle-announce' .. index .. '">[×]</div>'
		res = res .. urlel (url, elections, '')
		res = res .. urlel (url1, elections1, ', ')
		res = res .. urlel (url2, elections2, ', ')
		
		res = res .. ' ([[' .. region .. ']])<br />'
		
		if offices ~= '' then
			res = res .. "'''Участков''': " .. offices .. '. '
		end
		if voters ~= '' then
			res = res .. "'''Избирателей''': " .. voters .. '<br />'
		elseif offices ~= '' then
			res = res .. '<br />'
		end
		
		if distance ~= '' then
			res = res .. "'''" .. distance .. "'''"
			if transfer ~= '' then
				res = res .. ' — ' .. transfer .. '<br />'
			else
				res = res .. '<br />'
			end
		elseif transfer ~= '' then
			res = res .. "'''Проезд''': " .. transfer .. '<br />'
		end
		if comment then
			res = res .. comment
		end
		
		
		if page ~= '' then
			res = res .. "&nbsp; &nbsp; &nbsp; '''''[[" .. page .. "|Подробнее]]'''''"
		end
		res = res .. '</div></div>'
	elseif forma == 'table' then
		local nametext
		if page ~= '' then
			nametext = "'''[[" .. page .. '|' .. name .. "]]'''"
		else
			nametext = name
		end
		if address == '' then
			nametext = frame:expandTemplate { title = 'геоадрес', args = { nametext, region .. ', ' .. name} }
		else
			nametext = frame:expandTemplate { title = 'геоадрес', args = { nametext,  region .. ', ' .. address} }
		end
		
		res = res .. '<tr><td style="font-weight:bold; text-align:center">'..day..'</td>'
					.. '<td style="line-height:120%">' .. nametext .. '<br /><span style="font-size:95%">[[' .. region ..']]</span></td>'
					.. '<td class=plainlinks style="font-size:97%; line-height:115%">' .. urlel (url,elections,'') .. urlel (url1,elections1,', ') .. urlel (url2,elections2,', ') .. '</td>'
					.. '<td style="text-align:center">' .. distance .. '</td>'
					.. '<td style="font-size:95%; line-height:115%">' .. transfer .. '</td>'
					.. '<td  style="text-align:center">' .. offices .. '</td>'
					.. '<td  style="text-align:center">' .. voters .. '</td>'
					.. '<td style="font-size:95%; line-height:115%">' .. comment .. '</td>'
					.. '</tr>'
	elseif forma == 'map' then
		local dot
		if address == '' then
			dot = name
		else
			dot = address
		end
		dot = frame:callParserFunction( '#yandexgeo', region .. ', ' .. dot, 'maps' )
		res = res .. dot .. '~' .. name .. ', ' .. day .. '~' .. elections
		dot = dayM % 4 + 1
		local dayDX, dayMX = string.sub ('0' .. dayD, -2, -1), string.sub ('0' .. dayM, -2, -1)
		res = res .. '~icon=/Date/' .. dot .. '/' .. dayMX .. '/date-' .. dot .. '-' .. dayDX .. '.' .. dayMX .. '.png;'
	end
	
	index = index + 1
	frame:callParserFunction( '#vardefine', 'announce-date', dayD .. ',' .. dayM .. ',' .. dayY .. ',' .. index )
	return res
end


function date2number (s)
	local d,m,y = mw.ustring.match (s,'^(%d%d)%.(%d%d)%.(%d%d%d%d)$')
	if not d then 
		return 0, 1, 13, 2014
	end
	
	d,m,y = tonumber(d),tonumber(m),tonumber(y)
	return dmy2number (d,m,y)
end

function dmy2number (d,m,y)	
	if d then
		local n = (y-1)*365 + math.floor ((y-1)/4) - math.floor ((y-1)/100) + math.floor ((y-1)/400) + mday [m] + d
		if  y%4 == 0 and (y%100 ~= 0 or y%400 == 0) and m > 2 then 
			n = n + 1
		end
		if n % 7 == 0 then -- отдаем только воскресенья
			return n, d, m, y
		else
			return n, 32,m,y
		end
	end
	return nil
end

function number2dmy (n)
	local y = math.floor (n / 365.2425)
	local m = math.floor ((n % 365.2425) / 30.437) + 1
	mw.log ('первичный результат: ' .. y .. '/' .. m .. '\n')
	if m == 13 then
		y = y+1
		m = 1
	end
end	

function urlel (u, e, sep)
	if e == '' then
		return ''
	end
	if u == '' then
		return sep .. e
	end
	return sep .. '[' .. u .. ' ' .. e .. ']'
end		
		
		
		
		
		
		


return p