# -*- coding: utf-8 -*-
"""把本课程的教材与参考书目填进学院"教材及参考书目录"模板。

模板：_tpl5/教材目录模板.docx（源文件 8《软件项目管理》教材及参考书目录.docx）
输出：《软件测试课程设计》教材及参考书目录.docx

格式与模板一致：居中标题（18pt 加粗）＋ 2×2 表格（左列"使用教材/参考书目"，
右列逐条成段、两端对齐、正文样式）。
"""
import copy
import importlib.util
import os
import sys

from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Pt
from docx.text.paragraph import Paragraph

BASE = os.path.dirname(os.path.abspath(__file__))


def _load(name, path):
    spec = importlib.util.spec_from_file_location(name, path)
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return mod


G = _load('gen', os.path.join(BASE, '_gen_教学文件.py'))
C = G.C


def set_text(p, text):
    if not p.runs:
        p.add_run(text)
        return
    p.runs[0].text = text
    for r in p.runs[1:]:
        r.text = ''


def fill_list(cell, items, proto_para):
    """按模板段落样式逐条写入（第一条复用原段落，其余克隆其格式）。"""
    # 清空多余段落，只留第一段作为样板
    while len(cell.paragraphs) > 1:
        cell.paragraphs[-1]._p.getparent().remove(cell.paragraphs[-1]._p)
    first = cell.paragraphs[0]
    if proto_para is not None:
        first._p.getparent().replace(first._p, copy.deepcopy(proto_para._p))
        first = cell.paragraphs[0]
    set_text(first, items[0])
    cur = first
    for line in items[1:]:
        el = copy.deepcopy(first._p)
        cur._p.addnext(el)
        cur = Paragraph(el, cell)
        set_text(cur, line)


def main():
    doc = Document(os.path.join(BASE, '_tpl5', '教材目录模板.docx'))

    for p in doc.paragraphs:
        if '教材及参考书目录' in p.text:
            set_text(p, '《%s》“教材及参考书目录”' % C['name'])
            for r in p.runs:
                r.font.size = Pt(18)
                r.font.bold = True

    tbl = doc.tables[0]
    textbook_cell = tbl.rows[0].cells[1]
    ref_cell = tbl.rows[1].cells[1]
    proto = ref_cell.paragraphs[0] if ref_cell.paragraphs else None

    set_text(textbook_cell.paragraphs[0], C['textbook'])
    for r in textbook_cell.paragraphs[0].runs:
        r.font.name = '宋体'

    fill_list(ref_cell, list(C['refs']), proto)
    # 模板正文样式是"两端对齐"，短行会被拉开字距（如"官方文档"被撑开）→ 统一左对齐
    for p in list(ref_cell.paragraphs) + list(textbook_cell.paragraphs):
        p.alignment = WD_ALIGN_PARAGRAPH.LEFT
        for r in p.runs:
            r.font.name = '宋体'

    # 删除模板尾部残留的空表格
    for t in list(doc.tables[1:]):
        t._tbl.getparent().remove(t._tbl)

    out = os.path.join(BASE, '《软件测试课程设计》教材及参考书目录.docx')
    doc.save(out)
    d = Document(out)
    print('已生成：%s' % out)
    print('表格 %d 个 ｜ 参考书目 %d 条 ｜ 使用教材：%s'
          % (len(d.tables), len(d.tables[0].rows[1].cells[1].paragraphs), C['textbook'][:40]))
    return 0


if __name__ == '__main__':
    sys.exit(main())
