#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""按上传的章节模板填章节，并生成考试平台题库导入表"""
import os, json, re, shutil
from openpyxl import load_workbook, Workbook
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side

BASE = "/home/zyw/Downloads/dl-hub/22-软件项目管理教学包/命题-2026秋"
OUT = os.path.join(BASE, "07-题库导入")
TPL = "/home/zyw/Downloads/dl-hub/用户上传/章节模板.xlsx"
WORK = os.path.join(BASE, "05-学生复习资料", "工作区")

CH = {1: "软件项目管理概述", 2: "软件项目启动", 3: "软件项目采购管理", 4: "软件项目范围管理",
      5: "软件项目进度管理", 6: "软件项目成本管理", 7: "软件项目质量管理", 8: "软件项目资源管理",
      9: "软件项目干系人管理与沟通管理", 10: "软件项目风险管理"}
TYPE_CN = {"single": "单选题", "multi": "多选题", "tf": "判断题", "fill": "填空题",
           "short": "简答题", "case": "案例分析题"}
SCORE = {"single": 1, "multi": 2, "tf": 1, "fill": 2, "short": 5, "case": 10}

os.makedirs(OUT, exist_ok=True)


def fill_chapter_template():
    dst = os.path.join(OUT, "章节模板-已填写.xlsx")
    shutil.copy2(TPL, dst)
    wb = load_workbook(dst)
    ws = wb["Sheet1"]
    ws["A1"].font = Font(name="宋体", size=11, bold=True)
    for i, ch in enumerate(range(1, 11), start=2):
        ws.cell(row=i, column=1, value=f"第{ch}章 {CH[ch]}")
        ws.cell(row=i, column=1).font = Font(name="宋体", size=11)
    ws.column_dimensions["A"].width = 34
    wb.save(dst)
    return dst


def load_items():
    items = json.load(open(os.path.join(WORK, "bank_1_7.json"), encoding="utf-8"))
    p = os.path.join(WORK, "bank_8_10.json")
    if os.path.exists(p):
        items += json.load(open(p, encoding="utf-8"))["items"]
    return items


def build_bank(items):
    wb = Workbook()
    ws = wb.active
    ws.title = "题目"
    heads = ["序号", "章节", "知识点", "题型", "题干", "选项A", "选项B", "选项C", "选项D",
             "正确答案", "分值", "难度", "答案解析"]
    ws.append(heads)
    thin = Side(style="thin", color="C9D3E3")
    border = Border(left=thin, right=thin, top=thin, bottom=thin)
    for c in ws[1]:
        c.font = Font(name="微软雅黑", size=10, bold=True)
        c.fill = PatternFill("solid", fgColor="DCE6F5")
        c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
        c.border = border

    def add(it):
        opts = (it.get("options") or []) + [""] * 4
        opts = [re.sub(r"^[A-D][\.．]\s*", "", o) for o in opts[:4]]
        t = it["type"]
        if t == "tf":
            ans = "对" if it["answer"] in ("对", "√") else "错"
        elif t == "fill":
            ans = "；".join(it.get("answers") or it["answer"].split("；"))
        else:
            ans = it["answer"]
        stem = it.get("stem") or it.get("background", "")
        ch = it["chapter"]
        chname = "综合（跨章）" if ch == 0 else f"第{ch}章 {CH[ch]}"
        ws.append([ws.max_row, chname, it.get("kp", ""),
                   TYPE_CN[t], stem, opts[0], opts[1], opts[2], opts[3], ans,
                   it.get("points") or SCORE[t], it.get("difficulty", ""), it.get("explain", "")])

    for it in items:
        add(it)
    # 主观题
    p = os.path.join(WORK, "subjective.json")
    if os.path.exists(p):
        subs = json.load(open(p, encoding="utf-8"))["items"]
        for it in subs:
            if it["type"] == "short":
                add(it)
            else:
                qs = "　".join(f"（{i}）{re.sub(r'^（[0-9]+）', '', q['q'])}（{q['points']}分）"
                               for i, q in enumerate(it["questions"], 1))
                rec = {"chapter": it["chapter"], "type": "case", "stem": it.get("background", "") + "　" + qs,
                       "answer": it.get("answer", ""), "explain": "见参考答案", "difficulty": it.get("difficulty", ""),
                       "kp": it.get("kp", ""), "points": 10, "options": []}
                add(rec)

    widths = [6, 26, 30, 10, 70, 22, 22, 22, 22, 12, 6, 6, 50]
    for i, w in enumerate(widths, 1):
        ws.column_dimensions[chr(64 + i)].width = w
    for row in ws.iter_rows(min_row=2):
        for c in row:
            c.border = border
            c.alignment = Alignment(vertical="top", wrap_text=c.column in (3, 5, 6, 7, 8, 9, 13))
            c.font = Font(name="宋体", size=9)
    ws.freeze_panes = "A2"

    # 说明页
    info = wb.create_sheet("说明", 0)
    info["A1"] = "《软件项目管理》考试平台题库导入表"
    info["A1"].font = Font(name="微软雅黑", size=14, bold=True)
    rows = [
        ("课程名称", "软件项目管理"),
        ("课程代码", "154431006"),
        ("题目总数", f"{ws.max_row - 1} 题"),
        ("章节范围", "第1章—第10章（与教学大纲一致）"),
        ("题型", "单选题、多选题、判断题、填空题、简答题、案例分析题"),
        ("列说明", "序号｜章节｜知识点｜题型｜题干｜选项A—D｜正确答案｜分值｜难度｜答案解析"),
        ("答案格式", "单选填字母；多选填字母（如 A,B,D）；判断填“对/错”；填空多空用“；”分隔；简答/案例填参考答案"),
        ("导入提示", "若平台要求固定列序，请按平台模板调整列的顺序与表头文字，数据行可直接对应。"),
    ]
    for i, (k, v) in enumerate(rows, start=3):
        info.cell(row=i, column=1, value=k).font = Font(name="宋体", size=10, bold=True)
        info.cell(row=i, column=2, value=v).font = Font(name="宋体", size=10)
        info.cell(row=i, column=2).alignment = Alignment(wrap_text=True, vertical="top")
    info.column_dimensions["A"].width = 14
    info.column_dimensions["B"].width = 90
    out = os.path.join(OUT, "题库导入表（475题）.xlsx")
    wb.save(out)
    return out, ws.max_row - 1


if __name__ == "__main__":
    print(fill_chapter_template())
    items = load_items()
    out, n = build_bank(items)
    print(out, n)
