# -*- coding: UTF-8 -*-
import time
import re
import math
from io import BytesIO
from random import randint, shuffle
from threading import Thread

from docx_base import Word, Table, hex_to_rgb, rgb_to_hex, ParagraphBase
from docx.shared import Pt, Inches, Cm, RGBColor
from docx.enum.text import WD_COLOR_INDEX
from make_docx_demo.data import *
from make_docx_demo.docx_other_func import time_use, qrcode_maker, get_weekday, make_chart
from tools.loglog import logger, log_err_e
from make_docx_demo.word2pdf import convert_word_to_pdf

num_dict = {1: "❶", 2: "❷", 3: "❸", 4: "❹", 5: "❺", 6: "❻", 7: "❼", 8: "❽", 9: "❾",
            10: "❿", 11: "⓫", 12: "⓬", 13: "⓭", 14: "⓮", 15: "⓯", 16: "⓰", 17: "⓱", 18: "⓲", 19: "⓳", 20: "⓴"}



@time_use
def header_maker(docx: Word, json_data):
    exercise_id = str(json_data.get("ExerciseId", "")).rjust(11, "0") 
    exercise_title = json_data.get("ExerciseTitle", "") 
    exercise_level = json_data['StudentInfo']['StudentStudy']['ReadingLevel'] 

    student_name = json_data.get("StudentInfo").get("StudentName", '')
    class_name = json_data.get("StudentInfo").get("ClassName", '')
    t_date = time.strftime("%Y-%m-%d", time.localtime())
    t_weekday = get_weekday()
    t_time = time.strftime("%H:%M:%S", time.localtime())

    for i in range(2, len(docx.doc.sections) - 1):
        tb_header = docx.add_header_table(rows=1, cols=5, section_index=i, tb_name="页眉表格")

        tb_header.set_cell_text(0, 0, "春笋英语", bold=True, size=16, color=(220, 220, 220), border=False, chinese_font_name="黑体")
        tb_header.set_cell_text(0, 1, f"{class_name}\n{student_name}", size=8, border=False, color=(220, 220, 220))
        tb_header.set_cell_text(0, 2, f"{exercise_title}\n{exercise_level}级", size=8, border=False, color=(220, 220, 220))
        tb_header.set_cell_text(0, 3, f"{exercise_id}", bold=True, size=24, border=False, color=(220, 220, 220))
        tb_header.set_cell_text(0, 4, f"{t_date}\n{t_weekday}\n{t_time}", size=8, border=False, color=(220, 220, 220))

        tb_header.set_tb_colum_width(width=[100, 70, 70, 150, 80])
       

    target_section = docx.doc.sections[-1] 
    target_section.header.is_linked_to_previous = False
   
    for paragraph in target_section.header.paragraphs:
        paragraph.clear() 
   
   

    target_section.header_distance = 0
    target_section.footer_distance = 280000


@time_use
def sub_title_maker(docx: Word, main_title, sub_title_name1, sub_title_name2='春笋学习，高效学习专家'):
    p = docx.add_blank_paragraph()
    line_width = 205
    main_rect_x = line_width + 10
    main_rect_width = 150 

    right_line_x = main_rect_x + main_rect_width + 10 

    p.add_rectangle(main_title, x=main_rect_x, y=4, fill_color="000000", width=main_rect_width, height=48, font_color="ffffff",
                    font_size=18)
    p.add_rectangle("", x=0, y=50, boder_color="808080", width=line_width, height=2)
    p.add_rectangle("", x=right_line_x, y=50, boder_color="808080", width=line_width, height=2)

    p.add_rectangle(f"【{sub_title_name1}】", x=0, y=20, width=line_width, height=40, font_size=8, chinese_font="宋体")
    p.add_rectangle(sub_title_name2, x=right_line_x, y=20, width=line_width, height=40, font_color="808080", font_size=8,
                    chinese_font="宋体")
    docx.add_blank_paragraph()
    docx.add_blank_paragraph()
    docx.add_blank_paragraph()


@time_use
def section_1(docx: Word, json_data, *args, **kwargs):
    exercise_id = str(json_data.get("ExerciseId", "")).rjust(11, "0")
    student_name = json_data.get("StudentInfo").get("StudentName", '')
    t_date_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    reading_speed = json_data['StudentInfo']['StudentStudy']['ReadingSpeed'] 
    reading_accuracy = json_data['StudentInfo']['StudentStudy']['ReadingAccuracy'] 
    reading_level = json_data['StudentInfo']['StudentStudy']['ReadingLevel'] 

   
    chart_width = 5.4
    all_chart = json_data['StudentInfo']['StudentStudy']['ChartData']
    reading_speed_chart = all_chart["ReadingSpeed"] 
    reading_accuracy_chart = all_chart["ReadingAccuracy"] 
    reading_difficult_chart = all_chart["ReadingDifficulties"] 

    reading_speed_x_data = reading_speed_chart['XAxis'] 
    reading_speed_sub_title = reading_speed_chart['Legend'] 
    reading_speed_y_datas = [i['Data'] for i in reading_speed_chart['Series']] 

    reading_accuracy_x_data = reading_accuracy_chart['XAxis'] 
    reading_accuracy_sub_title = reading_accuracy_chart['Legend'] 
    reading_accuracy_y_datas = [i['Data'] for i in reading_accuracy_chart['Series']] 

    reading_difficult_x_data = reading_difficult_chart['XAxis'] 
    reading_difficult_sub_title = reading_difficult_chart['Legend'] 
    reading_difficult_y_datas = [i['Data'] for i in reading_difficult_chart['Series']] 

    "开始版面-------------------------------------------------"

    docx.add_paragraph("春笋英语     减负增效", size=24, bold=True, align="center", dq=20, dh=10)
    docx.add_paragraph("个性化学案", size=42, bold=True, chinese_font_name="黑体", align="center", dq=10, dh=20)

    p = docx.add_blank_paragraph(align="center")
    p.add_pic("make_docx_demo/static/logo.png", width=3)

    tb1 = Table(docx, rows=1, cols=3)
    tb1.set_cell_text(row=0, column=1, cell_text=f"姓名:{student_name} 编号:{exercise_id}", set_all_cell=False, color="CCCCCC")
    tb1.set_tb_colum_width(width=[100, 301, 100])

    tb2 = Table(docx, rows=1, cols=3, tb_name="三张图表")
    tb2.set_cell_text(0, 0, f"阅读速度\n{reading_speed}", bold=True, dq=10, dh=10)
    tb2.set_cell_text(0, 1, f"阅读准确率%\n{reading_accuracy}", bold=True, dq=10, dh=10)
    tb2.set_cell_text(0, 2, f"阅读等级\n{reading_level}", bold=True, dq=10, dh=10)
    tb2.set_tb_colum_width(width=[167, 167, 167])

    docx.add_blank_paragraph()

    tb3 = Table(docx, rows=1, cols=3, border=True)
    tb3.set_tb_colum_width(width=[167, 167, 167])

    p1 = tb3.get_cell_paragraph(0, 0, dq=15, dh=15)
    run1 = ParagraphBase(p1)
    chart1_io = make_chart(x_axis_data=reading_speed_x_data, y_axis_datas=reading_speed_y_datas, title="阅读速度",
                           sub_title_list=reading_speed_sub_title)
    run1.add_pic(chart1_io, width=chart_width)
    chart1_io.close() 

    p2 = tb3.get_cell_paragraph(0, 1, dq=15, dh=15)
    run2 = ParagraphBase(p2)
    chart2_io = make_chart(x_axis_data=reading_accuracy_x_data, y_axis_datas=reading_accuracy_y_datas, title="阅读准确率",
                           sub_title_list=reading_accuracy_sub_title)
    run2.add_pic(chart2_io, width=chart_width)
    chart2_io.close() 

    p3 = tb3.get_cell_paragraph(0, 2, dq=15, dh=15)
    run3 = ParagraphBase(p3)
    chart3_io = make_chart(x_axis_data=reading_difficult_x_data, y_axis_datas=reading_difficult_y_datas, title="阅读难度",
                           sub_title_list=reading_difficult_sub_title)
    run3.add_pic(chart3_io, width=chart_width)
    chart3_io.close() 

    docx.add_blank_paragraph()

    tb4 = Table(docx, rows=5, cols=5, border=True, tb_name="自主复习记录")
   
    tb4.set_table_width_xml([2000, 3000, 2000, 2000, 2000])

    first_cell = tb4.get_cell(0, 0)
    last_cell = tb4.get_cell(0, 4)
    first_cell.merge(last_cell)
    first_cell = tb4.get_cell(4, 0)
    last_cell = tb4.get_cell(4, 4)
    first_cell.merge(last_cell)

    tb4.set_cell_text(0, 0, "自主复习记录", size=14, bold=True, color=(230, 230, 230), set_all_cell=False)

    tb4.set_cell_text(1, 0, "模块", size=14, bold=True, color=(244, 244, 244), set_all_cell=False)
    tb4.set_cell_text(1, 1, "复习建议", size=14, bold=True, color=(244, 244, 244), set_all_cell=False)
    tb4.set_cell_text(1, 2, "10.1", size=14, bold=True, color=(244, 244, 244), set_all_cell=False)
    tb4.set_cell_text(1, 3, "10.4", size=14, bold=True, color=(244, 244, 244), set_all_cell=False)
    tb4.set_cell_text(1, 4, "10.7", size=14, bold=True, color=(244, 244, 244), set_all_cell=False)

    tb4.set_cell_text(2, 0, "词汇学习", size=14, bold=True, set_all_cell=False)
    tb4.set_cell_text(2, 1, "将单词、词义、例句朗读2遍", size=10, set_all_cell=False, align="left")

    tb4.set_cell_text(3, 0, "阅读理解", size=14, bold=True, set_all_cell=False)
    tb4.set_cell_text(3, 1, "1.文章朗读一遍\n2.口头翻译黑体词所在的句子", size=10, align="left")

    tb4.set_cell_text(4, 0, "备注：完成相应复习后在对应格子中打√", size=10, bold=True, align="right")

    docx.add_paragraph(f"生成日期:  {t_date_time}", align="center", dq=20)
    docx.add_page_section()


@time_use
def section_2(docx: Word, json_data, *args, **kwargs):
    docx.add_paragraph("致同学，家长们的一封信", bold=True, chinese_font_name="黑体", size=16, align="center", dq=5, dh=15)
    docx.add_paragraph("各位同学、家长，你们好！", bold=True, size=12)
    p1 = docx.add_blank_paragraph(dq=10, dh=10)
    p1.add_run_to_p("关于我们：", chinese_font_name="黑体", bold=True, size=10)
    p1.add_run_to_p("北京云知学科技有限公司是专注于", size=10)
    p1.add_run_to_p("英语课堂信息化研究的高新技术企业", underline=True, size=10)
    p1.add_run_to_p("，是教育部“数字校园综合解决方案”推荐单位。旗下品牌春笋英语是全国首家纸面化智能英语教学系统，合作学校超1000家，助力超50万名学生提升英语成绩。"
                    "春笋英语个性化学案，落实双减政策，根据每个学生的实际水平，一对一定制学案内容，实现减负、增效。",
                    size=10)

    docx.add_blank_paragraph()

    p2 = docx.add_blank_paragraph(dq=10, dh=5)
    p2.add_pic(pic_path="make_docx_demo/static/pen.png", width=0.5, underline=True)
    p2.add_run_to_p(" 为什么学好英语，而不是改学日语等小语种：", underline=True, size=10)
    p3 = docx.add_blank_paragraph(dq=5, dh=5)
    p3.add_run_to_p("1.专业限制：", bold=True, size=10, chinese_font_name="黑体")
    p3.add_run_to_p("学习小语种在高考志愿填报时会有专业限制。例如，军校、警校和多数科技类专业通常只招收考英语的学生。\n", size=10)
    p3.add_run_to_p("2.利于学业发展：", bold=True, size=10, chinese_font_name="黑体")
    p3.add_run_to_p("大学毕业及考研都需要英语，考小语种进大学后会更吃力。\n", size=10)
    p3.add_run_to_p("3.就业面窄：", bold=True, size=10, chinese_font_name="黑体")
    p3.add_run_to_p("大多数就业机会以及公务员考试往往都有英语要求。\n", size=10)
    p3.add_run_to_p("4.英语并不难：", bold=True, size=10, chinese_font_name="黑体")
    p3.add_run_to_p("只要方法得当，半年时间就可以显著提高。\n", size=10)

    p2 = docx.add_blank_paragraph(dq=10, dh=5)
    p2.add_pic(pic_path="make_docx_demo/static/pen.png", width=0.5, underline=True)
    p2.add_run_to_p(" 为什么学不好英语：方法不对", underline=True, size=10)
    p3 = docx.add_blank_paragraph(dq=5, dh=5)
    p3.add_run_to_p("1.单词+语法≠英语：", bold=True, size=10, chinese_font_name="黑体")
    p3.add_run_to_p("单纯的记忆单词和语法规则并不足以理解英语文章，更不足以写出流畅的作文。\n", size=10)
    p3.add_run_to_p("2.钻研英语考试≠学英语：", bold=True, size=10, chinese_font_name="黑体")
    p3.add_run_to_p("考试技巧并不能提高英语水平，只能造成得分虚高的假象，使英语学习越来越缺乏后劲，分数越学越低。\n", size=10)
    p3.add_run_to_p("3.英语是技能，用的多了就会了：", bold=True, size=10, chinese_font_name="黑体")
    p3.add_run_to_p("就像每个英国人都会说英语一样，每个中国人也都可以学好英语。\n", size=10)

    p2 = docx.add_blank_paragraph(dq=10, dh=5)
    p2.add_pic(pic_path="make_docx_demo/static/pen.png", width=0.5, underline=True)
    p2.add_run_to_p(" 怎样学好英语：", underline=True, size=10)
    p3 = docx.add_blank_paragraph(dq=5, dh=5)
    p3.add_run_to_p("1.大量阅读：", bold=True, size=10, chinese_font_name="黑体")
    p3.add_run_to_p("足量的阅读是掌握英语“技能”的必由之路。\n", size=10)
    p3.add_run_to_p("2.大量难度适宜的阅读：", bold=True, size=10, chinese_font_name="黑体")
    p3.add_run_to_p(
        "多数同学看不懂文章只能猜答案，即使做了阅读题也没有真正读文章，所以阅读材料难度适宜非常关键，“看得懂”才能真正实现“大量的阅读”。\n",
        size=10)
    p3.add_run_to_p("3.在阅读过程中自动掌握单词，领悟语法：", bold=True, size=10, chinese_font_name="黑体")
    p3.add_run_to_p("阅读量足够大，单词就自然掌握了，语法即使不知道概念也能理解其含义。\n", size=10)
    p3.add_run_to_p("4.四个月为一个周期：", bold=True, size=10, chinese_font_name="黑体")
    p3.add_run_to_p("几十万的春笋英语学员的经历表明，只要听话照做，平均四个月就能", size=10)
    p3.add_run_to_p("提升 20-30分", bold=True, size=10, chinese_font_name="黑体")
    p3.add_run_to_p("。\n", size=10)

    p2 = docx.add_blank_paragraph(dq=10, dh=5)
    p2.add_pic(pic_path="make_docx_demo/static/pen.png", width=0.5, underline=True)
    p2.add_run_to_p(" 春笋英语践行的理念：", underline=True, size=10)
    p3 = docx.add_blank_paragraph(dq=5, dh=5)
    p3.add_run_to_p("要抓紧，别着急，不走捷径，踏实看懂每句话，提分就是水到渠成。\n", size=10)
    p3.add_run_to_p("树立信心，有方法，有效果，有效率，100天脱胎换骨。", size=10)

    docx.add_blank_paragraph(dq=2, dh=2)
    docx.add_paragraph("北京云知学科技有限公司", align="right", size=10)
   
    docx.add_page_section()


@time_use
def section_3(docx: Word, json_data, *args, **kwargs):
    docx.add_paragraph("春笋英语学案学习流程", chinese_font_name="黑体", bold=True, align="center", size=16)

    p1 = docx.add_blank_paragraph(dq=10)
    p1.add_run_to_p("1.认读\n", bold=True, size=10, chinese_font_name="黑体")
    p1.add_run_to_p("按顺序朗读生词表两遍。\n", size=10)
    p1.add_run_to_p("（1）用红笔在不会的单词序号上打星号，增加记忆。\n", size=10)
    p1.add_run_to_p("（2）朗读例句，不认识的部分参照译文理解。\n", size=10)
    p1.add_run_to_p("（3）不会念的单词拼读音标；音标不会拼读的，申请音标课，约5个小时即可。\n", size=10)

    p2 = docx.add_blank_paragraph()
    p2.add_run_to_p("2.速记\n", bold=True, size=10, chinese_font_name="黑体")
    p2.add_run_to_p("（1）按顺序抄写，用黑笔完成，会的单词可以直接默写，不会的单词对照生词表进行抄写。提高效率，节约时间，不必犹豫纠结。\n", size=10)
    p2.add_run_to_p("（2）抄写过程中尽量朗读或默读，不必额外增加抄写次数，切勿死记硬背。\n", size=10)

    p3 = docx.add_blank_paragraph()
    p3.add_run_to_p("3.例句练习\n", bold=True, size=10, chinese_font_name="黑体")
    p3.add_run_to_p("翻译例句，可参考学生词表例句译文，在括号内写出单词汉语意思。\n", size=10)

    p4 = docx.add_blank_paragraph()
    p4.add_run_to_p("4.阅读\n", bold=True, size=10, chinese_font_name="黑体")
    p4.add_run_to_p("（1）认清阅读与做题的关系:阅读是为了提高文本敏感度，做题只是为了检验阅读质量。\n", size=10)
    p4.add_run_to_p(
        "不要为加快答题而跳读略读,不要先读题目再回原文查找答案，逐字逐句读完全文再做题，日常学案训练不要利用答题技巧，作答时要回到原文确认内容，养成良好答题习惯。\n",
        bold=True, size=10, chinese_font_name="黑体")
    p4.add_run_to_p("（2）读轻松愉快的文章才是难度适当的，如果阅读吃力，直接申请调整难度（", size=10)
    p4.add_run_to_p("可在筛查反馈表贴便贴留言", bold=True, size=10, chinese_font_name="黑体")
    p4.add_run_to_p("），不要勉强，提高时间利用率。\n", size=10)
    p4.add_run_to_p("（3）遇到生词，划线标记，事后查字典，把意思写在右侧标注区，不要写在原文上;生词太多的文章可以放弃，不要让查字典成为负担。\n",
                    size=10)
    p4.add_run_to_p("（4）黑体字、斜体字不认识，可以当场查阅生词表和标注。\n", size=10)
    p4.add_run_to_p("（5）必须将做题开始和结束时间填写上，精确到秒。\n", size=10)
    p4.add_run_to_p("（6）做题过程中，自己对于答案不理解、不确定的题目要标注出来。\n", size=10)

    p5 = docx.add_blank_paragraph()
    p5.add_run_to_p("5.核对答案\n", bold=True, size=10, chinese_font_name="黑体")
    p5.add_run_to_p("红笔批改。正常应该全对，允许因疏忽偶尔错一题。\n", size=10)

    p6 = docx.add_blank_paragraph()
    p6.add_run_to_p("6.划筛查表、报告阅读数据\n", bold=True, size=10, chinese_font_name="黑体")
    p6.add_run_to_p("和摸底一样的流程，", size=10)
    p6.add_run_to_p("筛查表很重要，务必严格对待，实事求是，否则下一份学案学习内容会有偏差；", bold=True, size=10, chinese_font_name="黑体")
    p6.add_run_to_p("务必填涂阅读用时和答对题数。\n", size=10)

    p7 = docx.add_blank_paragraph()
    p7.add_run_to_p("7.交卷\n", bold=True, size=10, chinese_font_name="黑体")
    p7.add_run_to_p("学案做完后，将学案的最后一页筛查反馈表反馈给老师。\n", size=10)

    p8 = docx.add_blank_paragraph()
    p8.add_run_to_p("8.回顾\n", bold=True, size=10, chinese_font_name="黑体")
    p8.add_run_to_p("回到学案第一页封面，在规定的时间内回顾学案内容并在自主复习记录表中登记(自主复习表在封面位置)。", size=10)

    docx.add_page_section()


@time_use
def section_4(docx: Word, json_data, *args, **kwargs):
    student_name = json_data.get("StudentInfo").get("StudentName", '')
    title_info = "\n".join(json_data.get("Title"))

    docx.add_paragraph(f"{student_name}  同学：", align="center", bold=True, dq=5, dh=5)

    p1 = docx.add_blank_paragraph()
    p1.add_run_to_p(title_info, size=10)

    sub_title_maker(docx, "词汇精准学", "智能定制专属词汇，轻松学习")

    tb = Table(docx, 1, 1, border=True, tb_name="词汇精准学")
    tb.set_tb_colum_width(0, 460)
    tb.set_cell_text(0, 0, "按顺序朗读生词表两遍。\n（1）用红笔在不会的单词序号上打星号，增加记忆。    （2）朗读例句，不认识的部分参照译文理解。",
                     align="left", size=10, dq=10, dh=10)
    docx.add_blank_paragraph()


@time_use
def section_4_1(docx: Word, json_data, *args, **kwargs):
    def insert_content(row, col, data, qrcode_result: dict):

        cell_outside = tb_outside.get_cell(row, col, delete_default_para=True)
        tb_inside = Table(cell_outside, rows=5, cols=3, tb_name="内部内容")

        tb_inside.merge_cell(0, 0, 0, 1)
        tb_inside.merge_cell(1, 0, 1, 1) 
        tb_inside.merge_cell(0, 2, 1, 2) 
        tb_inside.merge_cell(2, 0, 2, 2) 
        tb_inside.merge_cell(3, 0, 3, 2) 
        tb_inside.merge_cell(4, 0, 4, 2) 

       

       
        num_calucate = 2 * row + 1 if col == 0 else 2 * row + 2
        p = ParagraphBase(tb_inside.get_cell_paragraph(0, 0, align="left"))
        p.add_run_to_p(num_dict[num_calucate], bold=True, size=22, font_name="MS Gothic")
        p.add_run_to_p(' ' + data[0], bold=True, size=20)
        tb_inside.set_cell_text(row=1, column=0, cell_text=data[1] + "  " + data[2], border=False, size=10, align="left",
                                bk_color=(240, 240, 240))

       
        image_io:BytesIO = qrcode_result.get(data[9], "") 
        if image_io:
            cell_p = tb_inside.get_cell_paragraph(0, 2, dq=5)
            p_base = ParagraphBase(cell_p)
            p_base.add_pic(image_io, width=1.5)
            image_io.close()

       
        cell_p = tb_inside.get_cell_paragraph(2, 0, align="left")
        cell_p_1 = ParagraphBase(cell_p)
        cell_p_1.add_run_to_p(data[3], size=10, bold=True) 
        cell_p_1.add_run_to_p("   " + data[4], size=8) 

        cell_p = tb_inside.get_cell_paragraph(3, 0, align="left")
        cell_p_1 = ParagraphBase(cell_p)
        cell_p_1.add_run_to_p(data[5], size=10, bold=True)
        cell_p_1.add_run_to_p(" " + data[6], size=8)

        cell_p = tb_inside.get_cell_paragraph(4, 0, align="left")
        cell_p_1 = ParagraphBase(cell_p)
        cell_p_1.add_run_to_p(data[7], size=10, bold=True)
        cell_p_1.add_run_to_p(" " + data[8], size=8)

    properties_chinese_map = {"adj": "形容词", "n": "名词", "interj": "感叹词", "conj": "连词", "num": "数字", "art": "冠词",
                              "pron": "代词", "adv": "副词", "prep": "介词", "v": "动词"}
    strange_words_data = [] 
    strange_words = json_data.get('StrangeWords')
    qrcode_thread = [] 
    qrcode_result = {}

    for item in strange_words:
        spell = item['Spell'] 
        word_id = item['WordId'] 
        en = "" if not item.get("SymbolsEn", "") else item.get("SymbolsEn")
        am = "" if not item.get("SymbolsAm", "") else item.get("SymbolsAm")

        symbols_en = "英" + f'[{en}]' 
        symbols_am = "美" + f'[{am}]' 

       
        tts_url = f"https://dcjxb.yunzhixue.cn/exercise/word?id={word_id}"
        t = Thread(target=qrcode_maker, args=(tts_url, qrcode_result))
        qrcode_thread.append(t)
        t.start()

        word_properties = " ".join([properties_chinese_map.get(i, "") for i in item['WordProperties']]) 
        word_meanings = item.get('Meaning', "") 
        word_changes = ";".join([s["Type"] + ":" + s["Spell"] for s in item["WordChanges"]])

        if item['Sentences']:
            sentences = item['Sentences'][0]['English'] + '\n' + item['Sentences'][0]['Chinese']
        else:
            sentences = ""
       
        single_word_tuple = (spell, symbols_en, symbols_am, word_properties, word_meanings,
                             "词汇变形", word_changes, "例句", sentences, tts_url)
        strange_words_data.append(single_word_tuple)

    rows = math.ceil(len(strange_words_data) / 2) 
    tb_outside = Table(docx, rows=rows, cols=2, tb_name="外层框架")
    tb_outside.set_tb_colum_width(width=[230, 230])

    for t in qrcode_thread:
        t.join()

    for row in range(rows):
        for col in range(2):
            try:
                data_item = strange_words_data.pop(0)
                insert_content(row, col, data_item, qrcode_result)
            except IndexError:
                break

    docx.add_page_section()


@time_use
def section_5(docx: Word, json_data, *args, **kwargs):
   
    copy_word_list = [i['Meaning'] for i in json_data.get('StrangeWords')]
    random_copy_word_list = copy_word_list * 3 
    shuffle(random_copy_word_list)

   
    first_copy_word_list = copy_word_list.copy()
    copy_word_list_add_num = [f"{i} ({idx})" for idx, i in enumerate(first_copy_word_list, start=1)]
    shuffle(copy_word_list_add_num)
    total_copy_word_list = copy_word_list_add_num + random_copy_word_list

    sub_title_maker(docx, "单词高效记", "会读会写才算真学会")
    tb = Table(docx, 1, 1, tb_name="SuperMemo 速记", border=True)
    tb.set_tb_colum_width(0, 460)
    text = ["请先按照浅色水印显示的助记音节小声朗读，并在浅色水印上摹写，音节分隔点不用抄写。\n",
            "请在横线上写下对应单词，每格写一遍，尽量默写，默写不出的，可查阅生词表；\n",
            "书写时保持工整；每写完一个单词小声念一遍词义与单词。\n"]
    cell_p = tb.get_cell_paragraph(0, 0, align="left")
    p = ParagraphBase(cell_p)
    p.add_run_to_p("                SuperMemo 速记\n", size=16, bold=True, )
    for t in text:
        p.add_run_to_p("☆ ", size=10, font_name="MS Gothic")
        p.add_run_to_p(t, size=10)
    docx.add_blank_paragraph()

    total_count = len(total_copy_word_list)
    half_count = int(total_count / 2)
    tb2 = Table(docx, half_count + 1, 4, tb_name="SuperMemo 速记下面的单词")
    for row in range(total_count):
        data = total_copy_word_list[row]
        if row < half_count:
            tb2.set_cell_text(row, 0, data, size=9, align="right", border=False, dq=2.5, dh=2)
            tb2.set_cell_text(row, 1, str(row + 1) + "." + "_" * 20, size=9, align="left", border=False, dq=2.5, dh=2)
        else:
            tb2.set_cell_text(row - half_count, 2, data, size=9, align="right", border=False, dq=2.5, dh=2)
            tb2.set_cell_text(row - half_count, 3, str(row + 1) + "." + "_" * 20, size=9, align="left", border=False, dq=2.5, dh=2)

    tb2.set_tb_colum_width(width=[120, 110] * 2)

    docx.add_page_section()


@time_use
def section_6(docx: Word, json_data, *args, **kwargs):
    example_sentence = [f"{index}. {i['Sentences'][0]['English']}  ({i['Spell']})" for index, i in
                        enumerate(json_data['StrangeWords'], start=1) if i['Sentences']]
    sub_title_maker(docx, "例句填填看", "记词义，练拼写，学的快")
    tb = Table(docx, 1, 1, tb_name="例句填填看", border=True)
    tb.set_tb_colum_width(0, 460)
    text = ["请在横线上写下单词在例句中的词义，若想不起来，可随时到例句答案表中查看。\n",
            "参阅过答案的例句，请在句前的“□”中标记问号，以便复习回顾。\n",
            "单词有多个意思的，应只填写适合语境的意思。"]
    cell_p = tb.get_cell_paragraph(0, 0, align="left", dq=10, dh=10)
    p = ParagraphBase(cell_p)
    for t in text:
        p.add_run_to_p("☆ ", size=10, font_name="MS Gothic")
        p.add_run_to_p(t, size=10)

   

    data = ["1. I have no chance to go sightseeing this summer.	(chance)",
            "2. And with that, we conclude the third and final example.	(third)",
            "3. He lives a healthy and normal life and has a strong body.	(healthy)",
            "4. Popular music evolved from folk songs	(song)",
            "5. The town is famous for its name.	(for)",
            "6. Let's call room service, I need a bottle of wine.	(wine)",
            "7. That was the beginning of my life's work.	(life)",
            "8. The student wants to learn something.	(learn)",
            "9. How long did the movie last?	(last)",
            "10. I don't want to marry while I am studying.	(marry)",
            "11. Each paragraph begins on a new line.	(paragraph)",
            "12. Mike studies harder, so his grades are getting better and better.	(better)",
            "13. Tutors are better and more helpful than school teachers in any fields a student respondent said.	(helpful)",
            "14. Our team won a great victory and won the prize.	(prize)",
            "15. His performance at the concert last night proved that he is in the top of international pianists.	(concert)"]

    for i in example_sentence:
        p = docx.add_blank_paragraph(dq=4,dh=4)
        p.add_run_to_p("□  ", size=12,font_name="宋体")
        p.add_run_to_p(i + "___________")

    docx.add_page_section()


@time_use
def section_7(docx: Word, json_data, *args, **kwargs):
   
    def wanxing(index, article_single):
        article_id = article_single['Id']
        article_length = article_single['AllWordAmount']
       
        strange_words_ids = [i['MeanId'] for i in json_data['StrangeWords']]
       
        explanatory_words_ids = [i['MeaningId'] for i in article_single['ExplanatoryWords']]

       
        select_text = []
        for ques_index, candidates in enumerate(article_single['Questions'], start=1):
            single_select_text = ''
            for s in candidates['Candidates']:
                single_select_text += s['Label'] + '. '
                participle = s['Participle'] 
                if participle:
                    single_select_text += participle + ' \n'
                else:
                    text = s['Text']
                    single_select_text += text + ' \n'

            select_text.append(f"{ques_index}. {single_select_text}")

       
        all_select_text = "\n".join(select_text)

       
        article_main: str = article_single['English'] + "\n\n郑重提示：认真看完全文再看问题。\n\n" + all_select_text
        article_main_list = article_main.split(" ")

       
        explanatory_words = "\n\n".join(
            [f"{index}. {i['Spell']} {i['SymbolsEn']} {i['SymbolsAm']} {i['Meaning']}" for index, i in
             enumerate(article_single['ExplanatoryWords'], start=1)])

        sub_title_maker(docx, "真题强化练", "智能匹配难度，轻松提升阅读")
        tb = Table(docx, 1, 1, tb_name="真题强化练", border=True)
        tb.set_tb_colum_width(0, 460)
        text = ["练习中不认识的单词，尽量猜测词义，并用红笔加以标记。\n",
                "答题完毕后，可查字典，并注释在右侧批注区，不要在原文上注释。复习时不必通读全文，结合上下文能回忆起标记词的词义即可，想不起的再对照批注区。\n",
                "完形填空是优秀的测验题型，却不适合用于训练阅读能力和提升词汇量，所以建议在阅读能力（理解度、速度、难度）达标后再做完形填空题型练习。\n",
                "阅读能力达标的同学，按三遍法做完形填空，基本可以达到满分。三遍法要求如下：\n",
                "第一遍（理解）：结合选项通读全文，以求理解文章主旨，但不动笔，以免形成成见。\n",
                "第二遍（填空）：通读全文，从候选词中选出适宜项目，将完整的单词填入空格，使文章连贯。\n",
                "第三遍（核验）：通读填空后的全文，确认上下文无矛盾之处。\n",
                "三遍通读均应记录起讫时间，并将速度纳入能力考核项目。能力合格者，考试中也应有充裕时间完成以上 3 遍通读。\n",
                "阅读计时从此处开始，请按顺序完成阅读，并注意记录时间。\n",
                "\n"]

        text2 = [f"全题长度（含问题及选项）：{article_length}； 编号：{article_id}；\n",
                 "第一遍（理解）开始时间：_________________     第二遍（填空）开始时间：_________________\n",
                 "第三遍（核验）开始时间：_________________"]
        cell_p = tb.get_cell_paragraph(0, 0, align="left", dq=10, dh=10)
        p = ParagraphBase(cell_p)
        for t in text:
            p.add_run_to_p("☆ ", size=10, font_name="MS Gothic")
            p.add_run_to_p(t, size=10)
        for t2 in text2:
            p.add_run_to_p(t2, size=10)

        docx.add_blank_paragraph()

        tb1 = Table(docx, 1, 3)
        tb1.set_tb_colum_width(width=[90, 370, 5])

        tb1_p = ParagraphBase(tb1.get_cell_paragraph(0, 0, align="left"))
        tb1_p.add_pic("make_docx_demo/static/lianxi1.jpg", width=2.5)
        tb1.set_cell_text(0, 1, f"本篇编号：{article_id}，篇幅（含问题选项）：{article_length} 词	阅读开始时间:  点	 分	 秒",
                          size=9.5, underline=True, border=False, align="left")

        tb2 = Table(docx, rows=1, cols=2, border=True, tb_name="完形填空")
        tb2.set_tb_colum_width(width=[320, 140])

       
       
        tb2_p = ParagraphBase(tb2.get_cell_paragraph(0, 0, align="left"))
        for w in article_main_list:
            word = re.search(r"\[(\d+)]", w)
            if word:
                w = w[:w.find('[')]
                meaning_id = int(word.group(1))
                if meaning_id in strange_words_ids:
                    tb2_p.add_run_to_p(w + ' ', size=10.5, bold=True)
                elif meaning_id in explanatory_words_ids:
                    tb2_p.add_run_to_p(w + ' ', size=10.5, italic=True)
                else: 
                    tb2_p.add_run_to_p(w + ' ', size=10.5)
            else:
                tb2_p.add_run_to_p(w + ' ', size=10.5)

        tb2.set_cell_text(0, 1, explanatory_words, size=10.5, font_color=(80, 80, 80), align="left")

        docx.add_blank_paragraph()
        tail_zhushi = """第一遍（理解）结束时间：__________用时：____秒
第二遍（填空）结束时间：__________用时：____秒
第三遍（核验）结束时间：__________用时：____秒
总计用时：____分____秒

阅读计时在此结束。
今日总计阅读量 392 词，用时____秒，整份学案共有____个题目答对。答题用时、答对题数两项数据请抄写到筛查反馈表页脚。"""
        docx.add_paragraph(tail_zhushi, size=10.5)
        docx.add_blank_paragraph()

   
    def reading(index, article_single):
       
        all_article_length = 0

        def single_yuedu(index, a):
            article_id = a['Id']
            article_length = a['AllWordAmount']
            nonlocal all_article_length
            all_article_length += article_length
           
            strange_words_ids = [i['MeanId'] for i in json_data['StrangeWords']]
           
            explanatory_words_ids = [i['MeaningId'] for i in a['ExplanatoryWords']]

           
            select_text = []
            for ques_index, candidates in enumerate(a['Questions'], start=1):
                single_select_text = ''
               
                subject = candidates['Subject'] + '\n' 
                for s in candidates['Candidates']:
                    single_select_text += s['Label'] + '. ' 
                    participle = s['Participle'] 
                    if participle:
                        single_select_text += participle + ' \n'
                    else:
                        text = s['Text']
                        single_select_text += text + ' \n'
                select_text.append(str(ques_index) + ". " + subject + single_select_text)

           
            all_select_text = "\n".join(select_text)

           
            article_main: str = a['English'] + "\n\n郑重提示：认真看完全文再看问题。\n\n" + all_select_text
            article_main_list = article_main.split(" ")

           
            explanatory_words = "\n\n".join(
                [f"{index}. {i['Spell']} {i['SymbolsEn']} {i['SymbolsAm']} {i['Meaning']}" for index, i in
                 enumerate(a['ExplanatoryWords'], start=1)])

            tb1 = Table(docx, 1, 3, tb_name="图片小标题")
            tb1.set_tb_colum_width(width=[90, 370, 5])

            tb1_p = ParagraphBase(tb1.get_cell_paragraph(0, 0, align="left"))
            tb1_p.add_pic(f"make_docx_demo/static/lianxi{index}.jpg", width=2.5)
            tb1.set_cell_text(0, 1, f"本篇编号：{article_id}，篇幅（含问题选项）：{article_length} 词	阅读开始时间:  点	 分	 秒",
                              size=9.5, underline=True, border=False, align="left")

            tb2 = Table(docx, rows=1, cols=2, border=True, tb_name="七选五")
            tb2.set_tb_colum_width(width=[320, 140])

           
            tb2_p = ParagraphBase(tb2.get_cell_paragraph(0, 0, align="left"))
            for w in article_main_list:
                word = re.search(r"\[(\d+)]", w)
                if word:
                    w = w[:w.find('[')]
                    meaning_id = int(word.group(1))
                    if meaning_id in strange_words_ids:
                        tb2_p.add_run_to_p(w + ' ', size=10.5, bold=True)
                    elif meaning_id in explanatory_words_ids:
                        tb2_p.add_run_to_p(w + ' ', size=10.5, italic=True)
                    else: 
                        tb2_p.add_run_to_p(w + ' ', size=10.5)
                else:
                    tb2_p.add_run_to_p(w + ' ', size=10.5)

            tb2.set_cell_text(0, 1, explanatory_words, size=10.5, font_color=(80, 80, 80), align="left", centre=False)

            docx.add_blank_paragraph()
            tail_zhushi = """完成时间：_____点_____分_____秒，本篇用时：_____秒。"""
            docx.add_paragraph(tail_zhushi, size=10.5)
            docx.add_blank_paragraph()

        "---------------------开始单篇运行---------------------"
        if index == 1: 
            sub_title_maker(docx, "阅读提升练", "智能匹配难度，轻松提升阅读", "春笋智学, 高效学习专家")
           
            tb = Table(docx, 1, 1, tb_name="真题强化练", border=True)
            tb.set_tb_colum_width(0, 460)
            text = ["阅读中不认识的单词，尽量猜测词义，并用红笔加以标记，以便日后快速回顾。\n",
                    "读完全文后，可查字典，并抄在右侧批注区，不要在原文上注释。复习时不必通读全文，结合上下文能回忆起标记词的词义即可，想不起的再对照批注区。\n",
                    "阅读训练的目的是提高对英语词、句、篇的敏感度，答题只是检验学习成果的手段，所以切勿为了快速做题而跳读、略读。阅读速度是很重要的训练指标，请在确实理解词句的基础上尽量提高阅读速度。只要平时扎实阅读，考试中不会没有时间认真读题。\n",
                    "阅读计时从此处开始，请按顺序完成阅读，并注意记录时间。\n",
                    ]
            cell_p = tb.get_cell_paragraph(0, 0, align="left", dq=10, dh=10)
            p = ParagraphBase(cell_p)
            for t in text:
                p.add_run_to_p("☆ ", size=10, font_name="MS Gothic")
                p.add_run_to_p(t, size=10)

            docx.add_blank_paragraph()

        single_yuedu(index, article_single)

        tail_zhushi = f"""阅读计时在此结束。
今日总计阅读量 {all_article_length} 词，用时________秒，整份学案共有_______个题目答对。
答题用时、答对题数两项数据请抄写到筛查反馈表页脚。
请翻译并熟读下列句子。熟读时停顿要合理，并做到大声、清晰、流畅、快速；口音可逐步调整，不必立刻追求十分标准。"""
        docx.add_paragraph(tail_zhushi, size=10.5)
        docx.add_blank_paragraph()

   
    def seven_to_five(index, article_single):
        article_id = article_single['Id']
        article_length = article_single['AllWordAmount']
       
        strange_words_ids = [i['MeanId'] for i in json_data['StrangeWords']]
       
        explanatory_words_ids = [i['MeaningId'] for i in article_single['ExplanatoryWords']]

       
        select_text = []
        for ques_index, s_candidates in enumerate(article_single['Candidates'], start=1):
            single_select_text = ''
            single_select_text += s_candidates['Label'] + '. '
            participle = s_candidates['Participle'] 
            if participle:
                single_select_text += participle
            else:
                text = s_candidates['Text']
                single_select_text += text

            select_text.append(f"{single_select_text}")

       
        all_select_text = "\n".join(select_text)

       
        article_main: str = article_single['English'] + "\n\n郑重提示：认真看完全文再看问题。\n\n" + all_select_text
        article_main_list = article_main.split(" ")

       
        explanatory_words = "\n\n".join(
            [f"{index}. {i['Spell']} {i['SymbolsEn']} {i['SymbolsAm']} {i['Meaning']}" for index, i in
             enumerate(article_single['ExplanatoryWords'], start=1)])

        sub_title_maker(docx, "阅读提升练", "智能匹配难度，轻松提升阅读", "春笋智学, 高效学习专家")
        tb = Table(docx, 1, 1, tb_name="真题强化练", border=True)
        tb.set_tb_colum_width(0, 460)
        text = ["阅读中不认识的单词，尽量猜测词义，并用红笔加以标记。\n",
                "读完全文后，可查字典，并抄在右侧批注区，不要在原文上注释。复习时不必通读全文，结合上下文能回忆起标记词的词义即可，想不起的再对照批注区。\n",
                "7 选 5 题型是测试学生对文章理解程度的好题型，但因打破里文章的连贯性，故不是训练阅读能力的好素材。建议学生在阅读基本能力（理解度、速度、难度）达标后再开展 7 选 5 题型训练。若不能胜任本练习，请回到词汇与阅读训练，先打好基础。\n",
                "阅读计时从此处开始，请按顺序完成阅读，并注意记录时间。\n",
                ]
        cell_p = tb.get_cell_paragraph(0, 0, align="left", dq=10, dh=10)
        p = ParagraphBase(cell_p)
        for t in text:
            p.add_run_to_p("☆ ", size=10, font_name="MS Gothic")
            p.add_run_to_p(t, size=10)

        docx.add_blank_paragraph()

        tb1 = Table(docx, 1, 3, tb_name="图片小标题")
        tb1.set_tb_colum_width(width=[90, 370, 5])

        tb1_p = ParagraphBase(tb1.get_cell_paragraph(0, 0, align="left"))
        tb1_p.add_pic("make_docx_demo/static/lianxi1.jpg", width=2.5)
        tb1.set_cell_text(0, 1, f"本篇编号：{article_id}，篇幅（含问题选项）：{article_length} 词	阅读开始时间:  点	 分	 秒",
                          size=9.5, underline=True, border=False, align="left")

        tb2 = Table(docx, rows=1, cols=2, border=True, tb_name="七选五")
        tb2.set_tb_colum_width(width=[320, 140])

       
        tb2_p = ParagraphBase(tb2.get_cell_paragraph(0, 0, align="left"))
        for w in article_main_list:
            word = re.search(r"\[(\d+)]", w)
            if word:
                w = w[:w.find('[')]
                meaning_id = int(word.group(1))
                if meaning_id in strange_words_ids:
                    tb2_p.add_run_to_p(w + ' ', size=10.5, bold=True)
                elif meaning_id in explanatory_words_ids:
                    tb2_p.add_run_to_p(w + ' ', size=10.5, italic=True)
                else: 
                    tb2_p.add_run_to_p(w + ' ', size=10.5)
            else:
                tb2_p.add_run_to_p(w + ' ', size=10.5)

        tb2.set_cell_text(0, 1, explanatory_words, size=10.5, font_color=(80, 80, 80), align="left")

        docx.add_blank_paragraph()
        tail_zhushi = """完成时间：_____点_____分_____秒，用时：_____秒
阅读计时在此结束。
今日总计阅读量 292 词，用时________秒，整份学案共有_______个题目答对。
答题用时、答对题数两项数据请抄写到筛查反馈表页脚。"""
        docx.add_paragraph(tail_zhushi, size=10.5)
        docx.add_blank_paragraph()

    "判断题型；根据题型选择----------------------------"
    for index, article_single in enumerate(json_data['Articles'], start=1):
        article_type = article_single['Category'] 

        article_type_select = {1: reading, 2: wanxing, 3: seven_to_five}

        assert article_type in article_type_select
        article_type_select[article_type](index, article_single) 

    docx.add_page_section()


@time_use
def section_8(docx: Word, json_data, *args, **kwargs):
   
    sub_title_maker(docx, "单词趣味填", "趣味练习，多维提升和巩固")
    docx.add_pic_single_paragraph("make_docx_demo/static/happy_word.jpg", align="center", width=14.58)
    docx.add_page_section()


@time_use
def section_9(docx: Word, json_data, *args, **kwargs):
    def wanxing(index, article_single):
        chinese_article = article_single['Chinese']
        all_analysis = '' 

        docx.add_paragraph("答案和解析", chinese_font_name="微软雅黑", dq=5, dh=5, bold=True)
        text = "做阅读题的目的是锻炼理解英语文本的能力，答题只是检验理解程度的手段。请尽量根据所给题眼理解解题依据。若需要看汉语解析才能明白，你需要回到词汇与阅读训练，并从较低难度入手，以便打好基础。"
        docx.add_paragraph(text, size=9)

       
        for ques_index, question_item in enumerate(article_single['Questions'], start=1):
            analysis = question_item['Analysis'].strip() 
            abcd_label = '' 

            candidates = question_item['Candidates']
            for abcd_selected in candidates:
                if abcd_selected['IsRight']: 
                    abcd_label += abcd_selected['Label'].strip()

            all_analysis += f"{ques_index}.\n{abcd_label}  {analysis}\n" 

        docx.add_paragraph(all_analysis, size=9)
        docx.add_paragraph("全文参考译文", chinese_font_name="微软雅黑", dq=15, dh=5, bold=True)
        docx.add_paragraph(chinese_article, size=9, dq=5, dh=5, line_spacing=300)

   
    def reading(index, article_single):
        all_analysis = '' 
        all_difficult_sentences = [] 

        chinese_article = article_single['Chinese']

       
        for ques_index, question_item in enumerate(article_single['Questions'], start=1):
            analysis = question_item['Analysis'].strip("\n") 
            abcd_label = '' 

            candidates = question_item['Candidates']
            for abcd_selected in candidates:
                if abcd_selected['IsRight']: 
                    abcd_label += abcd_selected['Label'].strip("\n")

            all_analysis += f"{ques_index}.{abcd_label}  {analysis}\n"

       
        all_analysis += '\n'

       
        for difficult_sentence_item in article_single['DifficultSentences']:
            all_difficult_sentences.append(difficult_sentence_item['Chinese'])

        docx.add_paragraph("答案和解析", chinese_font_name="微软雅黑", dq=5, dh=5, bold=True)
        text = "做阅读题的目的是锻炼理解英语文本的能力，答题只是检验理解程度的手段。请尽量根据所给题眼理解解题依据。若需要看汉语解析才能明白，你可能需要暂时调低阅读难度。"
        docx.add_paragraph(text, size=9)
        docx.add_paragraph(all_analysis, size=9)

        docx.add_paragraph("难句翻译参考译文", chinese_font_name="微软雅黑", dq=5, dh=5, bold=True)
        for index_, difficult_sentence in enumerate(all_difficult_sentences, start=1):
            docx.add_paragraph(f'{index_}. {difficult_sentence}', size=9)

        docx.add_paragraph("全文参考译文", chinese_font_name="微软雅黑", dq=15, dh=5, bold=True)
        docx.add_paragraph(f"Passage {index}", chinese_font_name="微软雅黑", dq=15, dh=5, bold=True)
        docx.add_paragraph(chinese_article, size=9)

    def seven_to_five(index, article_single):
        chinese_article = article_single['Chinese']
        all_analysis = '' 

        docx.add_paragraph("答案和解析", chinese_font_name="微软雅黑", dq=5, dh=5, bold=True)
        text = "做阅读题的目的是锻炼理解英语文本的能力，答题只是检验理解程度的手段。请尽量根据所给题眼理解解题依据。若需要看汉语解析才能明白，你需要回到词汇与阅读训练，并从较低难度入手，以便打好基础。"
        docx.add_paragraph(text, size=9)
       
        for q_index, question_item in enumerate(article_single['Questions'], start=1):
            analysis = question_item['Analysis'] 
            abcd_label = '' 

            candidates = question_item['Candidates']
            for abcd_selected in candidates:
                if abcd_selected['IsRight']: 
                    abcd_label += abcd_selected['Label']
            all_analysis += f"{q_index}.{abcd_label}  {analysis}\n"

        docx.add_paragraph(all_analysis, size=9)
        docx.add_paragraph("全文参考译文", chinese_font_name="微软雅黑", dq=15, dh=5, bold=True)
        docx.add_paragraph("Passage 1", chinese_font_name="微软雅黑", dq=15, dh=5, bold=True)
        docx.add_paragraph(chinese_article, size=9, dq=5, dh=5, line_spacing=300)

    "判断题型；根据题型选择----------------------------"
    sub_title_maker(docx, "解题自主纠", "自主学习，逐步养成良好学习习惯")
    for index, article_single in enumerate(json_data['Articles'], start=1):
        article_type = article_single['Category'] 
        article_type_select = {1: reading, 2: wanxing, 3: seven_to_five}
        assert article_type in article_type_select
        article_type_select[article_type](index, article_single) 
        docx.add_blank_paragraph()

    docx.add_docx_component("make_docx_demo/word_component/blank.docx")
    docx.add_page_section()


@time_use
def section_10(docx: Word, json_data, scanpage_format, **kwargs):
    docx.add_paragraph("☆ 请写出词义，再对照筛査表批改。词义顺序可互换;答案意思相符即可，不要求一字不差。批改结果眷抄到筛査表。", size=9, dq=2,
                       dh=2)
    tb = Table(docx, 50, 4, tb_name="写出词义")
    tb.set_tb_colum_width(width=[110, 120, 110, 120])

    for row in range(50):
        tb.set_cell_text(row, 0, str(row + 1) + " " + "rich", size=8.5, dq=1, dh=1, border=False)
        tb.set_cell_text(row, 1, "□________________", size=10, dq=0, dh=0, border=False)
        tb.set_cell_text(row, 2, str(row + 51) + " " + "rich", size=8.5, dq=1, dh=1, border=False)
        tb.set_cell_text(row, 3, "□________________", size=10, dq=0, dh=0, border=False)
    tb.set_row_height(13)
    docx.add_page_break()

    docx.add_paragraph("☆ 请在需要加强学习的词义前方框中划线，两头各超出 1 毫米为宜(示例:□☑52.example);请保持本表整洁并交回。", size=9, dq=2,
                       dh=2)
    tb2 = Table(docx, 25, 8, tb_name="划线表")
    tb2.set_tb_colum_width(width=[57.5] * 8)

    docx.add_blank_paragraph(dq=5, dh=5)

    for row in range(25):
        tb2.set_cell_text(row, 0, "[01] Tuesday", size=8.5, border=False, dq=1.2, dh=1.2)
        tb2.set_cell_text(row, 1, "星期二", size=8.5, border="right", dq=1.2, dh=1.2)
        tb2.set_cell_text(row, 2, "[01] Tuesday", size=8.5, border=False, dq=1.2, dh=1.2)
        tb2.set_cell_text(row, 3, "星期二", size=8.5, border="right", dq=1.2, dh=1.2)
        tb2.set_cell_text(row, 4, "[01] Tuesday", size=8.5, border=False, dq=1.2, dh=1.2)
        tb2.set_cell_text(row, 5, "星期二", size=8.5, border="right", dq=1.2, dh=1.2)
        tb2.set_cell_text(row, 6, "[01] Tuesday", size=8.5, border=False, dq=1.2, dh=1.2)
        tb2.set_cell_text(row, 7, "星期二", size=8.5, border=False, dq=1.2, dh=1.2)

    docx.set_page_column(5)
    docx.add_docx_component("make_docx_demo/word_component/component.docx")
    docx.end_page_column()

    if scanpage_format == 3:
        docx.add_page_section()


def two_check_page(docx: Word, json_data, **kwargs):
   
    def empty_filter_page(class_name, student_name, page_title, page_sub_title, t_datetime, word_data_list):
        if len(word_data_list) % 2 != 0:
            word_data_list.append("") 

        tb = Table(docx, 1, 3, tb_name="头部三元素")
        tb.set_tb_colum_width(width=[40, 100, 100])

        p_cell = tb.get_cell_paragraph(0, 0, dq=10)
        p = ParagraphBase(p_cell)
        p.add_pic("make_docx_demo/static/logo2.png", width=Inches(1.2)) 

        tb.set_cell_text(0, 1, f"{class_name}\n{student_name}", border=False, size=8, dh=2)
        tb.set_cell_text(0, 2, f"{page_title}\n{page_sub_title}", border=False, size=8, dh=2)

        docx.add_paragraph("请写出词义，再对照筛查表批改。词义顺序可互换；答案意思相符即可，不要求一字不差。批改结果誊抄到筛查表。", size=9)

        tb = Table(docx, rows=0, cols=4, tb_name="第一页筛查表")

        tb.set_all_border_fastly(xml=True, outside_side_border=True, outside_side_border_size=5)

        half_count = int(len(word_data_list) / 2) 
        for index,row in enumerate(range(half_count)):
            first_word, second_word = word_data_list[row],word_data_list[row + half_count]
            cell3 = f"{index + 1 + half_count}. {second_word}" if second_word else ""
            cell4 = "□ ___________________________" if second_word else ""

            data = [f"{index + 1}. {first_word}", "□ ___________________________", cell3, cell4]
            tb.add_table_row_data_xml_fastly(data, font_size=[10.5, 9, 10.5, 9])
        tb.set_row_height(13.8)
        tb.set_table_width_xml([2124, 3257, 2140, 3257])
        blank_count = " " * 80
        p = docx.add_blank_paragraph(dq=5)
        p.add_run_to_p(f"{t_datetime} {page_title}-{page_sub_title}{blank_count}", size=8, chinese_font_name="仿宋", font_name="仿宋")
        docx.add_page_break() 

   
    def filter_table_page(page_id, class_name, student_name, page_title, page_sub_title, t_datetime,
                          foot_description, foot_description2, article_type, word_data_list2):
        if len(word_data_list2) % 2 != 0:
            word_data_list2.append(["", ""]) 

        tb = Table(docx, 1, 5, tb_name="头部五元素")
        tb.set_tb_colum_width(width=[40, 130, 130, 150, 70])

        p_cell = tb.get_cell_paragraph(0, 0, dq=10)
        p = ParagraphBase(p_cell)
        p.add_pic("make_docx_demo/static/logo2.png", width=Inches(1.2))

        tb.set_cell_text(0, 1, f"{class_name}\n{student_name}", border=False, size=8)
        tb.set_cell_text(0, 2, f"{page_id}", border=False, size=16, dh=2, bold=True, font_name="黑体")
        tb.set_cell_text(0, 3, f"{page_title}\n{page_sub_title}", border=False, size=8)

        p_cell = tb.get_cell_paragraph(0, 4)
        p = ParagraphBase(p_cell)
        p.add_pic(qrcode_maker(f"{page_id}"), width=Inches(0.5))

        pp = docx.add_blank_paragraph()
        p_base = ParagraphBase(pp)
        p_base.p.add_run_to_p("请在需要加强学习的词义前方框中划线，两头各超出1毫米为宜（示例：", size=9)
        p_base.p.add_pic("make_docx_demo/static/line_example.png", width=Inches(0.8))
        p_base.p.add_run_to_p(" ）；请保持本表整洁并交回。", size=9)

        tb = Table(docx, rows=0, cols=4, tb_name="第二页筛查表")

        ## 1234横着放
       
       
       
        #
       
       
        #
       
       

        ## 1234竖着放
        total_row = int(len(word_data_list2) / 2)
        for row in range(total_row):
            spell1, meaning1 = word_data_list2[row]
            spell2, meaning2 = word_data_list2[total_row + row]

            cell3 = f"{total_row + row + 1}. {spell2}" if spell2 else ""
            cell4 = f"□ {meaning2}" if meaning2 else ""

            data = [f"{row + 1}. {spell1}", f"□ {meaning1}", cell3, cell4] 
            tb.add_table_row_data_xml_fastly(data, font_size=[10.5, 9, 10.5, 9])

        tb.set_all_border_fastly(xml=True, outside_side_border=True, outside_side_border_size=5)
        tb.set_row_height(13.6)
        tb.set_table_width_xml([2124, 3257, 2140, 3257])
        if article_type == 1: 
            docx.add_paragraph(f"{t_datetime} {page_title}-{page_sub_title}{foot_description}", size=8, chinese_font_name="仿宋",
                               font_name="仿宋", dq=5)
            docx.add_paragraph(foot_description2, align="right", size=8, chinese_font_name="仿宋")
        else:
            docx.add_paragraph(f"{t_datetime} {page_title}-{page_sub_title}{foot_description}", size=8, chinese_font_name="仿宋",
                               font_name="仿宋", dq=5)


   
    student_name = json_data.get("StudentInfo").get("StudentName", '') 
    class_name = json_data.get("StudentInfo").get("ClassName", '') 
    t_datetime = time.strftime("%Y-%m-%d %H:%M", time.localtime()) 
    article_type = json_data['Articles'][0]['Category'] 
    is_add_empty_filter_page = json_data['Config']['AddEmptyFilterPage'] 

    """---------------------------------------------------------------------------------"""
    for index, page in enumerate(json_data['ScreeningScanPages'], start=1):
        page_id = str(page['PageId']).rjust(11, "0")

       
        if index >= 2:
            docx.add_page_break()

        page_title = page['Title'] 
        page_sub_title = page['SubTitle'] 
        foot_description = page['FootDescription'] 
        foot_description2 = page['FootDescription2'] 

        word_data_list1 = []
        word_data_list2 = []
        for i in page['FilterTable']['Items']: 
            word_data_list1.append(i['Spell'])
            word_data_list2.append([i['Spell'], i['Meaning']])

       
        if is_add_empty_filter_page:
            empty_filter_page(class_name, student_name, page_title, page_sub_title, t_datetime, word_data_list1)

       
        filter_table_page(page_id, class_name, student_name, page_title, page_sub_title, t_datetime,
                          foot_description, foot_description2, article_type, word_data_list2)


@time_use
def other(docx, json_data, **kwargs):
   
    sections = docx.doc.sections
    for section in sections[:-1]:
        section.top_margin = Inches(0.3)
        section.bottom_margin = Inches(0.3)
        section.left_margin = Inches(0.8)
        section.right_margin = Inches(0.8)

    sections[-1].top_margin = Inches(0.1)
    sections[-1].bottom_margin = Inches(0.1)
    sections[-1].left_margin = Inches(0.5)
    sections[-1].right_margin = Inches(0.5)

    header_maker(docx, json_data)


def start_make_word(json_data, document_format, scanpage_format):
    try:
        docx = Word(save_file_name="develop.docx", start_template_name="make_docx_demo/word_component/start_template.docx")
        menu = [section_1, section_2, section_3, section_4, section_4_1,
                section_5, section_6, section_7, section_8, section_9, ]
        if scanpage_format == 1:
            menu.append(two_check_page)
        elif scanpage_format == 2:
            menu.append(section_10)
        elif scanpage_format == 3:
            menu.append(section_10)
            menu.append(two_check_page)
        menu.append(other)

        for s in menu:
            s(docx=docx, json_data=json_data, scanpage_format=scanpage_format)

       
        docx.save_docx()
        if document_format == 1:
            return "develop.docx"
        else:
            convert_word_to_pdf("develop")
            return "develop.pdf"

    except Exception as e:
        log_err_e(e)


if __name__ == '__main__':
    import os

    t = time.time()
    os.chdir("..")

   
    start_make_word(test_json5, 1, 1)
    print(time.time() - t)
