#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""按自建平台《试题导入模板》生成导入工作簿"""
import os, sys, json, re
from openpyxl import Workbook, load_workbook
from openpyxl.styles import Font, Alignment, Border, Side, PatternFill
from openpyxl.utils import get_column_letter

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import build_papers as bp

BASE = bp.BASE
OUT = os.path.join(BASE, "07-题库导入")
TPL = "/tmp/tpl_qbank.xlsx"
WORK = os.path.join(BASE, "05-学生复习资料", "工作区")

HEAD = ["题型", "题干", "A", "B", "C", "D", "正确答案", "分值", "难易度", "知识点",
        "考核目标", "解析", "自动阅卷（填空题）", "答案可乱序（填空题）",
        "判分时答案内字母区分大小写（填空题）"]
NOTE = ("注：1、红色字表示：必填项；黑色字表示：选填项；列表标题须和模板保持一致，请勿删除。\n"
        "      2、没有选择题时，无须填写选项内容。\n"
        "      3、若设置多个 Sheet 页，那么每个 Sheet 页中的章节名称需要保持一致。")
CH = {1: "软件项目管理概述", 2: "软件项目启动", 3: "软件项目采购管理", 4: "软件项目范围管理",
      5: "软件项目进度管理", 6: "软件项目成本管理", 7: "软件项目质量管理", 8: "软件项目资源管理",
      9: "软件项目干系人管理与沟通管理", 10: "软件项目风险管理"}
TYPE_CN = {"single": "单选题", "multi": "多选题", "tf": "判断题", "fill": "填空题", "short": "主观题", "case": "主观题"}


def new_sheet(wb, title, chapter_name):
    ws = wb.create_sheet(title)
    ws.merge_cells("A1:O1")
    c = ws["A1"]; c.value = NOTE
    c.font = Font(name="宋体", size=9, color="C00000")
    c.alignment = Alignment(wrap_text=True, vertical="center")
    ws.row_dimensions[1].height = 46
    ws.merge_cells("A2:O2")
    c = ws["A2"]; c.value = f"章节：{chapter_name}"
    c.font = Font(name="宋体", size=11, bold=True)
    c.alignment = Alignment(vertical="center")
    for j, h in enumerate(HEAD, 1):
        cell = ws.cell(row=3, column=j, value=h)
        cell.font = Font(name="宋体", size=10, bold=True)
        cell.fill = PatternFill("solid", fgColor="F2F2F2")
        cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
        cell.border = Border(*[Side(style="thin", color="BFBFBF")] * 4)
    widths = [10, 62, 20, 20, 20, 20, 22, 6, 8, 30, 10, 46, 10, 12, 16]
    for j, w in enumerate(widths, 1):
        ws.column_dimensions[get_column_letter(j)].width = w
    ws.freeze_panes = "A4"
    return ws


def row_for(it):
    t = it["type"]
    opts = [re.sub(r"^[A-D][\.．]\s*", "", o) for o in (it.get("options") or [])]
    opts = (opts + [""] * 4)[:4]
    if t == "single":
        ans = it["answer"]
    elif t == "multi":
        letters = re.findall(r"[A-D]", it["answer"])
        ans = "".join(f"【{x}】" for x in sorted(set(letters)))
    elif t == "tf":
        ans = "对" if it["answer"] in ("对", "√") else "错"
    elif t == "fill":
        ans = "".join(f"【{a}】" for a in (it.get("answers") or it["answer"].split("；")))
    else:
        ans = it.get("answer", "")
    diff = {"易": "易", "中": "中", "难": "难"}.get(it.get("difficulty", ""), "中")
    fill_cols = ("是", "是", "否") if t == "fill" else (None, None, None)
    opts = [o if o else None for o in opts]
    return [TYPE_CN[t], it.get("stem") or "", opts[0], opts[1], opts[2], opts[3],
            ans, (len(it.get("answers") or []) if t == "fill" else (it.get("points") or {"single": 1, "multi": 2, "tf": 1, "short": 5, "case": 10}[t])),
            diff, it.get("kp") or None, None, it.get("explain") or None, *fill_cols]


def write_rows(ws, items):
    r = 4
    for it in items:
        vals = row_for(it)
        for j, v in enumerate(vals, 1):
            c = ws.cell(row=r, column=j, value=v)
            c.font = Font(name="宋体", size=9)
            c.alignment = Alignment(vertical="top", wrap_text=j in (2, 3, 4, 5, 6, 7, 10, 12))
            c.border = Border(*[Side(style="thin", color="D9D9D9")] * 4)
        r += 1


def case_stem(it):
    qs = "　".join(f"（{i}）{re.sub(r'^（[0-9]+）', '', q['q'])}（{q['points']}分）"
                   for i, q in enumerate(it.get("questions", []), 1))
    return (it.get("background", "") or "") + "　" + qs


def build_papers_wb():
    a, c = bp.load_all()
    P = bp.assemble(a, c)
    wb = Workbook(); wb.remove(wb.active)
    for pid in sorted(P):
        cls = bp.CLASSES[int(pid[0])]
        ws = new_sheet(wb, f"{pid}卷", f"软件项目管理-{cls}-{pid[1]}卷")
        write_rows(ws, P[pid])
    out = os.path.join(OUT, "试题导入-期末12卷（按卷分Sheet）.xlsx")
    wb.save(out)
    return out


def build_practice_wb():
    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"]
    subs = json.load(open(os.path.join(WORK, "subjective.json"), encoding="utf-8"))["items"]
    wb = Workbook(); wb.remove(wb.active)
    for ch in range(1, 11):
        chs = [x for x in items if x["chapter"] == ch]
        for x in subs:
            if x["chapter"] == ch:
                chs.append(x)
        if not chs:
            continue
        ws = new_sheet(wb, f"第{ch}章", f"第{ch}章 {CH[ch]}")
        out = []
        for x in chs:
            if x["type"] == "case":
                y = dict(x); y["stem"] = case_stem(x)
                out.append(y)
            else:
                out.append(x)
        write_rows(ws, out)
    out = os.path.join(OUT, "试题导入-练习题库.xlsx")
    wb.save(out)
    return out


def build_chapter_wb():
    """备选：按教材章节分 sheet，知识点前缀卷别题号，便于按卷筛选"""
    a, c = bp.load_all()
    P = bp.assemble(a, c)
    wb = Workbook(); wb.remove(wb.active)
    for ch in range(1, 11):
        rows = []
        for pid in sorted(P):
            for no, it in enumerate(P[pid], 1):
                if it["chapter"] != ch:
                    continue
                y = dict(it)
                y["kp"] = f"{pid}-Q{no:02d}｜{it.get('kp','')}"
                rows.append(y)
        if not rows:
            continue
        ws = new_sheet(wb, f"第{ch}章", f"第{ch}章 {CH[ch]}")
        write_rows(ws, rows)
    out = os.path.join(OUT, "试题导入-期末题库（按章分Sheet）.xlsx")
    wb.save(out)
    return out


if __name__ == "__main__":
    print(build_papers_wb())
    print(build_chapter_wb())
    print(build_practice_wb())
