const { Document, Packer, Paragraph, TextRun, ImageRun, Header, Footer, AlignmentType,
        HeadingLevel, PageBreak, TableOfContents, PageNumber, Table, TableRow, TableCell,
        BorderStyle, WidthType, ShadingType, VerticalAlign, LevelFormat } = require('docx');
const fs = require('fs');
const path = require('path');

// 读取截图
const screenshots = {
  login: fs.readFileSync('/Users/retirado/ccProgram/docs/screenshots/01-login.png'),
  adminDashboard: fs.readFileSync('/Users/retirado/ccProgram/docs/screenshots/02-admin-dashboard.png'),
  adminCourses: fs.readFileSync('/Users/retirado/ccProgram/docs/screenshots/03-admin-courses.png'),
  courseDetail: fs.readFileSync('/Users/retirado/ccProgram/docs/screenshots/04-course-detail.png'),
  adminTenants: fs.readFileSync('/Users/retirado/ccProgram/docs/screenshots/05-admin-tenants.png'),
  schoolDashboard: fs.readFileSync('/Users/retirado/ccProgram/docs/screenshots/06-school-dashboard.png'),
  schoolTeachers: fs.readFileSync('/Users/retirado/ccProgram/docs/screenshots/07-school-teachers.png'),
  schoolSchedule: fs.readFileSync('/Users/retirado/ccProgram/docs/screenshots/08-school-schedule.png'),
  teacherCourses: fs.readFileSync('/Users/retirado/ccProgram/docs/screenshots/09-teacher-courses.png'),
  teacherPrepare: fs.readFileSync('/Users/retirado/ccProgram/docs/screenshots/10-teacher-prepare.png'),
  teacherLessons: fs.readFileSync('/Users/retirado/ccProgram/docs/screenshots/11-teacher-lessons.png'),
  parentDashboard: fs.readFileSync('/Users/retirado/ccProgram/docs/screenshots/12-parent-dashboard.png'),
  parentTasks: fs.readFileSync('/Users/retirado/ccProgram/docs/screenshots/13-parent-tasks.png'),
};

// 表格边框样式
const tableBorder = { style: BorderStyle.SINGLE, size: 1, color: "CCCCCC" };
const cellBorders = { top: tableBorder, bottom: tableBorder, left: tableBorder, right: tableBorder };

// 创建带标题的图片段落
function createImageWithCaption(imageData, caption, width = 550, height = 350) {
  return [
    new Paragraph({
      alignment: AlignmentType.CENTER,
      spacing: { before: 200, after: 100 },
      children: [new ImageRun({
        type: "png",
        data: imageData,
        transformation: { width, height },
        altText: { title: caption, description: caption, name: caption }
      })]
    }),
    new Paragraph({
      alignment: AlignmentType.CENTER,
      spacing: { after: 300 },
      children: [new TextRun({ text: caption, italics: true, size: 20, color: "666666" })]
    })
  ];
}

// 创建表格
function createTable(headers, rows) {
  const headerCells = headers.map(h => new TableCell({
    borders: cellBorders,
    width: { size: Math.floor(9360 / headers.length), type: WidthType.DXA },
    shading: { fill: "1E3A5F", type: ShadingType.CLEAR },
    verticalAlign: VerticalAlign.CENTER,
    children: [new Paragraph({
      alignment: AlignmentType.CENTER,
      children: [new TextRun({ text: h, bold: true, size: 22, color: "FFFFFF" })]
    })]
  }));

  const dataRows = rows.map(row => new TableRow({
    children: row.map(cell => new TableCell({
      borders: cellBorders,
      width: { size: Math.floor(9360 / headers.length), type: WidthType.DXA },
      children: [new Paragraph({
        spacing: { before: 60, after: 60 },
        children: [new TextRun({ text: cell, size: 22 })]
      })]
    }))
  }));

  return new Table({
    columnWidths: headers.map(() => Math.floor(9360 / headers.length)),
    rows: [new TableRow({ tableHeader: true, children: headerCells }), ...dataRows]
  });
}

const doc = new Document({
  styles: {
    default: { document: { run: { font: "Microsoft YaHei", size: 24 } } },
    paragraphStyles: [
      { id: "Title", name: "Title", basedOn: "Normal",
        run: { size: 72, bold: true, color: "1E3A5F", font: "Microsoft YaHei" },
        paragraph: { spacing: { before: 400, after: 200 }, alignment: AlignmentType.CENTER } },
      { id: "Heading1", name: "Heading 1", basedOn: "Normal", next: "Normal", quickFormat: true,
        run: { size: 36, bold: true, color: "1E3A5F", font: "Microsoft YaHei" },
        paragraph: { spacing: { before: 400, after: 200 }, outlineLevel: 0 } },
      { id: "Heading2", name: "Heading 2", basedOn: "Normal", next: "Normal", quickFormat: true,
        run: { size: 28, bold: true, color: "2E5A8F", font: "Microsoft YaHei" },
        paragraph: { spacing: { before: 300, after: 150 }, outlineLevel: 1 } },
      { id: "Heading3", name: "Heading 3", basedOn: "Normal", next: "Normal", quickFormat: true,
        run: { size: 24, bold: true, color: "3E7ABF", font: "Microsoft YaHei" },
        paragraph: { spacing: { before: 200, after: 100 }, outlineLevel: 2 } }
    ]
  },
  numbering: {
    config: [
      { reference: "bullet-list",
        levels: [{ level: 0, format: LevelFormat.BULLET, text: "•", alignment: AlignmentType.LEFT,
          style: { paragraph: { indent: { left: 720, hanging: 360 } } } }] }
    ]
  },
  sections: [{
    properties: {
      page: { margin: { top: 1440, right: 1440, bottom: 1440, left: 1440 } }
    },
    headers: {
      default: new Header({ children: [new Paragraph({
        alignment: AlignmentType.RIGHT,
        children: [new TextRun({ text: "少儿智慧阅读 - 产品介绍", size: 20, color: "888888" })]
      })] })
    },
    footers: {
      default: new Footer({ children: [new Paragraph({
        alignment: AlignmentType.CENTER,
        children: [new TextRun({ text: "第 ", size: 20 }), new TextRun({ children: [PageNumber.CURRENT], size: 20 }),
                   new TextRun({ text: " 页 / 共 ", size: 20 }), new TextRun({ children: [PageNumber.TOTAL_PAGES], size: 20 }),
                   new TextRun({ text: " 页", size: 20 })]
      })] })
    },
    children: [
      // ===== 封面页 =====
      new Paragraph({ spacing: { before: 2000 } }),
      new Paragraph({
        alignment: AlignmentType.CENTER,
        children: [new TextRun({ text: "少儿智慧阅读", size: 72, bold: true, color: "1E3A5F", font: "Microsoft YaHei" })]
      }),
      new Paragraph({ spacing: { before: 400 } }),
      new Paragraph({
        alignment: AlignmentType.CENTER,
        children: [new TextRun({ text: "产品介绍与功能说明", size: 40, color: "3E7ABF", font: "Microsoft YaHei" })]
      }),
      new Paragraph({ spacing: { before: 1500 } }),
      new Paragraph({
        alignment: AlignmentType.CENTER,
        children: [new TextRun({ text: "版本：v1.0", size: 28, color: "666666" })]
      }),
      new Paragraph({
        alignment: AlignmentType.CENTER,
        spacing: { before: 100 },
        children: [new TextRun({ text: "日期：2026年2月24日", size: 28, color: "666666" })]
      }),
      new Paragraph({ children: [new PageBreak()] }),

      // ===== 目录页 =====
      new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new TextRun("目录")] }),
      new TableOfContents("目录", { hyperlink: true, headingStyleRange: "1-3" }),
      new Paragraph({ children: [new PageBreak()] }),

      // ===== 第一章：产品概述 =====
      new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new TextRun("第一章 产品概述")] }),

      new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun("1.1 产品定位")] }),
      new Paragraph({
        spacing: { after: 200 },
        children: [new TextRun({ text: "少儿智慧阅读是一款面向幼儿园的B2B2C综合性阅读教学管理系统，致力于为幼儿园、教师和家长提供全方位的绘本阅读教学服务。平台采用多端协同架构，打通超管、学校、教师、家长四方角色，实现从课程创作、教学管理到家校互动的完整闭环。" })]
      }),

      new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun("1.2 目标用户")] }),
      createTable(
        ["用户角色", "使用场景", "核心需求"],
        [
          ["平台超管", "运营管理", "课程内容管理、租户服务、平台运营"],
          ["学校管理员", "园所管理", "教师学生管理、课程授权、数据统计"],
          ["教师", "教学实施", "课程备课、课堂教学、任务布置、成长记录"],
          ["家长", "家校共育", "查看任务、提交反馈、了解孩子成长"]
        ]
      ),

      new Paragraph({ heading: HeadingLevel.HEADING_2, spacing: { before: 300 }, children: [new TextRun("1.3 核心价值")] }),
      new Paragraph({ numbering: { reference: "bullet-list", level: 0 }, children: [new TextRun("标准化教学：专业绘本课程包，标准化教学流程")] }),
      new Paragraph({ numbering: { reference: "bullet-list", level: 0 }, children: [new TextRun("效率提升：备课上课一体化，教学管理智能化")] }),
      new Paragraph({ numbering: { reference: "bullet-list", level: 0 }, children: [new TextRun("家校联动：任务布置与反馈，家校共育更紧密")] }),
      new Paragraph({ numbering: { reference: "bullet-list", level: 0 }, children: [new TextRun("成长可视：多维度数据记录，成长轨迹清晰可见")] }),
      new Paragraph({ numbering: { reference: "bullet-list", level: 0 }, children: [new TextRun("灵活管理：多租户架构，满足不同规模园所需求")] }),

      // 登录界面
      new Paragraph({ heading: HeadingLevel.HEADING_2, spacing: { before: 300 }, children: [new TextRun("1.4 登录界面")] }),
      ...createImageWithCaption(screenshots.login, "图1-1 系统登录界面 - 支持四种角色切换", 500, 400),
      new Paragraph({ children: [new PageBreak()] }),

      // ===== 第二章：技术架构 =====
      new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new TextRun("第二章 技术架构")] }),

      new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun("2.1 系统架构")] }),
      new Paragraph({
        spacing: { after: 200 },
        children: [new TextRun("系统采用前后端分离架构，前端使用Vue 3框架，后端使用NestJS框架，通过JWT进行身份认证。数据层使用Prisma ORM，支持SQLite（开发）和PostgreSQL（生产）数据库。")]
      }),

      new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun("2.2 技术选型")] }),
      createTable(
        ["层级", "技术栈", "说明"],
        [
          ["前端框架", "Vue 3 + Vite", "现代化前端开发框架"],
          ["UI组件", "Ant Design Vue 4.x", "企业级UI组件库"],
          ["状态管理", "Pinia", "Vue官方状态管理"],
          ["后端框架", "NestJS", "企业级Node.js框架"],
          ["ORM", "Prisma", "现代化数据库工具"],
          ["数据库", "SQLite / PostgreSQL", "开发/生产数据库"],
          ["认证", "JWT + Passport", "安全认证方案"]
        ]
      ),
      new Paragraph({ children: [new PageBreak()] }),

      // ===== 第三章：超管端功能 =====
      new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new TextRun("第三章 超管端功能")] }),
      new Paragraph({
        spacing: { after: 200 },
        children: [new TextRun("超管端是平台的运营管理中心，负责课程内容生产、租户服务和平台运营。")]
      }),

      new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun("3.1 数据看板")] }),
      new Paragraph({
        spacing: { after: 100 },
        children: [new TextRun("提供平台整体运营数据的可视化展示，包括核心指标、趋势图表和快捷入口。")]
      }),
      ...createImageWithCaption(screenshots.adminDashboard, "图3-1 超管端数据看板 - 平台运营数据一目了然"),

      new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun("3.2 课程包管理")] }),
      new Paragraph({
        spacing: { after: 100 },
        children: [new TextRun("完整的课程内容生产与发布流程，支持基础信息、资源上传、教学环节、逐页脚本、延伸活动等完整内容。")]
      }),
      ...createImageWithCaption(screenshots.adminCourses, "图3-2 课程包列表 - 管理所有课程内容"),
      ...createImageWithCaption(screenshots.courseDetail, "图3-3 课程详情 - 完整的教学设计展示", 500, 600),

      new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun("3.3 租户管理")] }),
      new Paragraph({
        spacing: { after: 100 },
        children: [new TextRun("多租户服务的核心管理功能，包括租户列表、套餐配置、课程授权、服务管理等。")]
      }),
      ...createImageWithCaption(screenshots.adminTenants, "图3-4 租户管理 - 管理所有签约园所"),
      new Paragraph({ children: [new PageBreak()] }),

      // ===== 第四章：学校端功能 =====
      new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new TextRun("第四章 学校端功能")] }),
      new Paragraph({
        spacing: { after: 200 },
        children: [new TextRun("学校端是园所管理员的管理后台，负责本园的教师、学生、班级和教学管理。")]
      }),

      new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun("4.1 数据概览")] }),
      new Paragraph({
        spacing: { after: 100 },
        children: [new TextRun("园所运营数据一目了然，包括人员统计、教学统计和图表展示。")]
      }),
      ...createImageWithCaption(screenshots.schoolDashboard, "图4-1 学校端数据概览 - 园所运营数据统计"),

      new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun("4.2 人员管理")] }),
      new Paragraph({
        spacing: { after: 100 },
        children: [new TextRun("支持教师和学生的增删改查、批量导入、调班等功能。")]
      }),
      ...createImageWithCaption(screenshots.schoolTeachers, "图4-2 教师管理 - 管理本园教师信息"),

      new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun("4.3 课程排期")] }),
      new Paragraph({
        spacing: { after: 100 },
        children: [new TextRun("日历视图展示排课情况，支持创建、编辑、删除排课。")]
      }),
      ...createImageWithCaption(screenshots.schoolSchedule, "图4-3 课程排期 - 日历视图管理排课"),
      new Paragraph({ children: [new PageBreak()] }),

      // ===== 第五章：教师端功能 =====
      new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new TextRun("第五章 教师端功能")] }),
      new Paragraph({
        spacing: { after: 200 },
        children: [new TextRun("教师端是教师日常教学的核心工具，覆盖备课、上课、课后全流程。")]
      }),

      new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun("5.1 课程中心")] }),
      new Paragraph({
        spacing: { after: 100 },
        children: [new TextRun("浏览和使用已授权的课程，支持年级筛选、领域筛选、关键词搜索。")]
      }),
      ...createImageWithCaption(screenshots.teacherCourses, "图5-1 课程中心 - 浏览可用课程"),

      new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun("5.2 备课模式")] }),
      new Paragraph({
        spacing: { after: 100 },
        children: [new TextRun("课前准备工作，包括教学流程、教师讲稿、逐页脚本、备课笔记、教学材料等。")]
      }),
      ...createImageWithCaption(screenshots.teacherPrepare, "图5-2 备课模式 - 完整的备课支持", 500, 500),

      new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun("5.3 上课记录")] }),
      new Paragraph({
        spacing: { after: 100 },
        children: [new TextRun("历史授课记录管理，支持状态筛选、日期筛选、查看详情。")]
      }),
      ...createImageWithCaption(screenshots.teacherLessons, "图5-3 上课记录 - 授课历史管理"),
      new Paragraph({ children: [new PageBreak()] }),

      // ===== 第六章：家长端功能 =====
      new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new TextRun("第六章 家长端功能")] }),
      new Paragraph({
        spacing: { after: 200 },
        children: [new TextRun("家长端是家校互动的桥梁，让家长了解并参与孩子的阅读成长。")]
      }),

      new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun("6.1 首页")] }),
      new Paragraph({
        spacing: { after: 100 },
        children: [new TextRun("孩子信息概览，包括孩子卡片、最近任务、成长档案等。")]
      }),
      ...createImageWithCaption(screenshots.parentDashboard, "图6-1 家长端首页 - 孩子信息概览"),

      new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun("6.2 阅读任务")] }),
      new Paragraph({
        spacing: { after: 100 },
        children: [new TextRun("完成教师布置的任务，支持查看任务详情、提交反馈、查看反馈记录。")]
      }),
      ...createImageWithCaption(screenshots.parentTasks, "图6-2 阅读任务 - 查看并完成阅读任务"),
      new Paragraph({ children: [new PageBreak()] }),

      // ===== 第七章：核心业务流程 =====
      new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new TextRun("第七章 核心业务流程")] }),

      new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun("7.1 课程生产流程")] }),
      new Paragraph({
        spacing: { after: 200 },
        children: [new TextRun("超管创建课程 → 填写基础信息 → 上传资源 → 设计教学环节 → 添加延伸活动 → 提交审核 → 审核通过 → 发布课程 → 授权给租户 → 学校/教师使用")]
      }),

      new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun("7.2 教学实施流程")] }),
      new Paragraph({
        spacing: { after: 200 },
        children: [new TextRun("教师浏览课程 → 进入备课模式 → 记录备课笔记 → 选择班级 → 开始上课 → 按流程教学 → 课堂评价 → 结束课程 → 填写课堂记录 → 查看上课记录")]
      }),

      new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun("7.3 家校互动流程")] }),
      new Paragraph({
        spacing: { after: 200 },
        children: [new TextRun("教师布置任务 → 分配给学生/班级 → 家长查看任务 → 亲子完成阅读 → 家长提交反馈 → 教师查看反馈")]
      }),

      new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun("7.4 成长记录流程")] }),
      new Paragraph({
        spacing: { after: 200 },
        children: [new TextRun("教师观察学生 → 创建成长档案 → 选择学生 → 填写内容 → 上传图片 → 保存档案 → 家长查看")]
      }),
      new Paragraph({ children: [new PageBreak()] }),

      // ===== 第八章：部署与运维 =====
      new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new TextRun("第八章 部署与运维")] }),

      new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun("8.1 环境配置")] }),
      createTable(
        ["环境", "前端地址", "后端地址", "数据库"],
        [
          ["开发", "localhost:5173", "localhost:3000", "SQLite"],
          ["生产", "域名/CDN", "域名/API", "PostgreSQL"]
        ]
      ),

      new Paragraph({ heading: HeadingLevel.HEADING_2, spacing: { before: 300 }, children: [new TextRun("8.2 启动命令")] }),
      new Paragraph({
        spacing: { after: 100 },
        shading: { fill: "F5F5F5", type: ShadingType.CLEAR },
        children: [new TextRun({ text: "# 开发环境启动", font: "Consolas", size: 22 })]
      }),
      new Paragraph({
        spacing: { after: 100 },
        shading: { fill: "F5F5F5", type: ShadingType.CLEAR },
        children: [new TextRun({ text: "./start-all.sh", font: "Consolas", size: 22 })]
      }),
      new Paragraph({
        spacing: { after: 100 },
        shading: { fill: "F5F5F5", type: ShadingType.CLEAR },
        children: [new TextRun({ text: "# 停止服务", font: "Consolas", size: 22 })]
      }),
      new Paragraph({
        spacing: { after: 200 },
        shading: { fill: "F5F5F5", type: ShadingType.CLEAR },
        children: [new TextRun({ text: "./stop-all.sh", font: "Consolas", size: 22 })]
      }),

      new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun("8.3 测试账号")] }),
      createTable(
        ["角色", "账号", "密码"],
        [
          ["超管", "admin", "123456"],
          ["学校", "school", "123456"],
          ["教师", "teacher1", "123456"],
          ["家长", "parent1", "123456"]
        ]
      ),

      // 结束页
      new Paragraph({ spacing: { before: 800 } }),
      new Paragraph({
        alignment: AlignmentType.CENTER,
        children: [new TextRun({ text: "— 文档结束 —", size: 24, color: "888888", italics: true })]
      })
    ]
  }]
});

// 生成文档
Packer.toBuffer(doc).then(buffer => {
  fs.writeFileSync("/Users/retirado/ccProgram/docs/少儿智慧阅读-产品介绍与功能说明.docx", buffer);
  console.log("文档生成成功！");
}).catch(err => {
  console.error("生成文档失败:", err);
});
