# -*- coding: utf-8 -*-
"""시설유지보수 선로/토목/건축시설(G) → tab_depth5 H자식 전개. self탭=첫 자식(부모값 승계)+신규탭. 스타일보존·B재부번."""
import openpyxl, shutil, copy as _copy
from openpyxl.styles import PatternFill, Font
BLUE=PatternFill('solid',fgColor='FFBDD7EE',bgColor='FFBDD7EE')
BASE='https://info.korail.com/info/contents.do?key='
SRC='한국철도공사.xlsx'
shutil.copy(SRC,'한국철도공사_backup_depth5전.xlsx')
wb=openpyxl.load_workbook(SRC); ws=wb.active
maxr=ws.max_row
def data_row(r): return any(ws.cell(r,c).value not in (None,'') for c in range(2,18))
eff={}
for r in range(3,maxr+1):
    for c in range(4,8): eff[(r,c)]=ws.cell(r,c).value
for m in list(ws.merged_cells.ranges):
    if m.min_row>=3 and 4<=m.min_col<=7:
        t=ws.cell(m.min_row,m.min_col).value
        for rr in range(m.min_row,m.max_row+1): eff[(rr,m.min_col)]=t
rows=[]
for r in range(3,maxr+1):
    if not data_row(r): continue
    sty={c:(_copy.copy(ws.cell(r,c).font),_copy.copy(ws.cell(r,c).fill),
            _copy.copy(ws.cell(r,c).border),_copy.copy(ws.cell(r,c).alignment)) for c in range(2,18)}
    rec={'vals':{c:ws.cell(r,c).value for c in range(2,18)},
         'D':eff.get((r,4)),'E':eff.get((r,5)),'F':eff.get((r,6)),'G':eff.get((r,7)),
         'hl':ws.cell(r,11).hyperlink.target if ws.cell(r,11).hyperlink else None,
         'sty':sty,'h':ws.row_dimensions[r].height}
    for c in range(4,8): rec['vals'][c]=eff.get((r,c))
    rows.append(rec)
tmpl=rows[0]['sty']
def child(parent,Hlabel,key,L,M,N):
    cv={2:None,3:'한국철도공사',4:parent['D'],5:parent['E'],6:parent['F'],7:parent['G'],8:Hlabel,9:None,10:None,
        11:BASE+str(key),12:L,13:M,14:N,15:'미부착',16:None,17:None}
    return {'vals':cv,'D':parent['D'],'E':parent['E'],'F':parent['F'],'G':parent['G'],'hl':BASE+str(key),
            'sty':{c:(_copy.copy(t[0]),_copy.copy(t[1]),_copy.copy(t[2]),_copy.copy(t[3])) for c,t in tmpl.items()},'h':parent['h'],'NEW':True}
EXP={
 '선로시설':('선로시설 현황',[('점검/보수체계',1300,'페이지',1,'어문'),('보선장비',1301,'페이지',1,'어문'),('궤도사업',1302,'페이지',1,'어문,이미지')]),
 '토목시설':('토목시설 현황',[('구조물 안전관리',1305,'페이지',1,'어문,이미지'),('스마트 시설물 점검',2450,'페이지',1,'어문,이미지'),('건널목 안전관리',1306,'페이지',1,'어문,이미지'),('재해예방',1304,'페이지',1,'어문,이미지')]),
 '건축시설':('건축시설 현황',[('주요 업무',1540,'페이지',1,'어문,이미지')]),
}
new=[]
for rec in rows:
    if rec['F']=='시설유지보수' and rec['G'] in EXP and (rec['vals'].get(8) in (None,'')):
        selfH,children=EXP[rec['G']]
        rec['vals'][8]=selfH  # 현재행→self탭 H라벨(부모값 승계)
        rec['_selfH']=True
        new.append(rec)
        for lab,key,L,M,N in children:
            new.append(child(rec,lab,key,L,M,N))
    else:
        new.append(rec)
print('원본',len(rows),'-> 확장',len(new))

for m in list(ws.merged_cells.ranges):
    if m.min_row>=3: ws.unmerge_cells(str(m))
for r in range(3,maxr+12):
    for c in range(2,28):
        cc=ws.cell(r,c); cc.value=None; cc.hyperlink=None; cc.fill=PatternFill(); cc.font=Font()
r=3
for i,rec in enumerate(new,1):
    for c in range(2,18):
        cell=ws.cell(r,c); cell.value=rec['vals'].get(c)
        f,fi,bo,al=rec['sty'][c]; cell.font=f; cell.fill=fi; cell.border=bo; cell.alignment=al
    ws.cell(r,2).value=i
    if rec.get('hl'):
        ws.cell(r,11).hyperlink=rec['hl']; ws.cell(r,11).font=Font(color='0000FF',underline='single')
    if rec.get('NEW'):
        for c in range(2,18): ws.cell(r,c).fill=BLUE
    elif rec.get('_selfH'):
        ws.cell(r,8).fill=BLUE
    if rec.get('h'): ws.row_dimensions[r].height=rec['h']
    r+=1
last=r-1
for col in (4,5,6,7):
    rr=3
    while rr<=last:
        v=ws.cell(rr,col).value
        if v in (None,''): rr+=1; continue
        r2=rr
        while r2+1<=last and ws.cell(r2+1,col).value==v: r2+=1
        if r2>rr:
            for x in range(rr+1,r2+1): ws.cell(x,col).value=None
            ws.merge_cells(start_row=rr,start_column=col,end_row=r2,end_column=col)
        rr=r2+1
wb.save(SRC)
print('저장 행수=%d'%(last-2))
