import os,re,json,time,sys

"""---设置讲义种类 papertype---"""
"""1: 高三复习讲义(课前, 课后)"""
"""2: 测验卷与周末卷(填空题, 选择题, 解答题)"""
"""3: 日常选题讲义(一个section)"""

paper_type = 1 # 随后设置一下后续的讲义标题

"""---设置题块编号---"""

problems = [
"14624,14950,14956,14957,14947","14613,14615,14953,14961,14962"

]

"""---设置结束---"""


if paper_type == 1:
    enumi_mode = 0 #设置模式(1为整卷统一编号, 0为每一部分从1开始编号)
    template_file = "模板文件/复习讲义模板.txt" #设置模板文件名
    exec_list = [("标题数字待处理","01"),("标题文字待处理","函数方程与不等式")] #设置讲义标题
    destination_file = "临时文件/"+exec_list[0][1]+"_"+exec_list[1][1] # 设置输出文件名
elif paper_type == 2:
    enumi_mode = 1 #设置模式(1为整卷统一编号, 0为每一部分从1开始编号)
    template_file = "模板文件/测验周末卷模板.txt" #设置模板文件名
    exec_list = [("标题替换","下学期测验08")] #设置讲义标题
    destination_file = "临时文件/"+exec_list[0][1] # 设置输出文件名
elif paper_type == 3:
    enumi_mode = 0 #设置模式(1为整卷统一编号, 0为每一部分从1开始编号)
    template_file = "模板文件/日常选题讲义模板.txt" #设置模板文件名
    exec_list = [("标题文字待处理","07超几何分布")]  #设置讲义标题
    destination_file = "临时文件/"+exec_list[0][1] # 设置输出文件名
    




#生成数码列表, 逗号分隔每个区块, 区块内部用:表示整数闭区间
def generate_number_set(string):
    string = re.sub(r"[\n\s]","",string)
    string_list = string.split(",")
    numbers_list = []
    for s in string_list:
        if not ":" in s:
            numbers_list.append(s.zfill(6))
        else:
            start,end = s.split(":")
            for ind in range(int(start),int(end)+1):
                numbers_list.append(str(ind).zfill(6))
    return numbers_list

#将正确率转化为含颜色代码的字符串
def get_color(value):
    value = float(value)
    if value>=0.5:
        (r,g,b)=(1,2-2*value,0)
    else:
        (r,g,b)=(2*value,1,0)
    return "{" + "%.3f" %(r) + "," + "%.3f" %(g) + ",0}"


def color_value(matchobj):
    value = matchobj.group(1)
    return "\t"+"\\fcolorbox[rgb]{0,0,0}"+ get_color(value) +"{" + value +"}"


#读取题库json文件并转化为字典
with open(r"../题库0.3/Problems.json","r",encoding = "utf8") as f:
    database = f.read()
pro_dict = json.loads(database)

#读取目标数据库json并转化为字典
with open(r"../题库0.3/LessonObj.json","r",encoding = "utf8") as f:
    database = f.read()
obj_dict = json.loads(database)

#读取系统日期
current_time = time.localtime()
time_string = "_"+str(current_time.tm_year).zfill(4)+str(current_time.tm_mon).zfill(2)+str(current_time.tm_mday).zfill(2)

#生成目标文件名和目标文件目录
teachers_latex_file = destination_file + "_教师" + time_string + ".tex"
students_latex_file = destination_file + "_学生" + time_string + ".tex"
d = re.search("/[^/]*$",destination_file).span()[0]
destination_dir = destination_file[:d]

#读取模板
with open(template_file,"r",encoding="utf8") as f:
    latex_raw = f.read()

#识别操作系统
if sys.platform != "win32":
    latex_raw = re.sub(r"fontset[\s]*=[\s]*none","fontset = fandol",latex_raw)
    latex_raw = re.sub(r"\\setCJKmainfont",r"% \\setCJKmainfont",latex_raw)

#预处理
for command in exec_list:
    latex_raw = re.sub(command[0],command[1],latex_raw)

data_teachers = latex_raw
data_students = latex_raw

#计数待替换部分
blocks_count = len(re.findall("待替换[\d]",latex_raw))

if not len(problems) == blocks_count:
    print("题号块数与模板待替换块数不符, 请检查")
else:
    problems_count = 0
    for blockid in range(1,blocks_count+1):
        print("正在处理题块",blockid,".")
        string_to_replace = "待替换" + str(blockid)
        teachers_string = ""
        students_string = ""
        problem_list = [id for id in generate_number_set(problems[blockid-1].strip()) if id in pro_dict]
        #生成教师题目字符串与学生题目字符串, 准备替换至latex文件
        for id in problem_list:
            problemset = pro_dict[id]
            problem = problemset["content"]
            solution = (problemset["solution"] if problemset["solution"] != "" else "暂无解答与提示")
            answer = "\\textcolor{red}{" + (problemset["ans"] if problemset["ans"] != "" else "暂无答案") + "}"
            remarks = (problemset["remark"] if problemset["remark"] != "" else "暂无备注")
            usages_list = problemset["usages"]
            if len(usages_list) > 0:
                usage = re.sub("\\t([\d]\.[\d]{0,10})",color_value,"\n\n".join(usages_list))
                usage = re.sub("[\\t ]([\d]\.[\d]{0,10})",color_value,usage)
            else:
                usage = "暂无使用记录"
            origin = (problemset["origin"] if problemset["origin"] != "" else "出处不详")
            objects = problemset["objs"]
            if len(objects) == 0:
                objects = "暂未关联目标\n\n"
            elif "KNONE" in [o.upper() for o in objects]:
                objects = "该题的考查目标不在目前的集合中\n\n"
            else:
                objects_string = ""
                for obj in objects:
                    if not obj in obj_dict:
                        objects_string = "目标" + obj + "有误\n\n"
                        break
                    else:
                        objects_string += "\\textcolor{blue}{" + obj + "|" + obj_dict[obj]["content"] + "}\n\n"
                objects = objects_string
            space = ("" if problemset["space"] == "" else "\n"+r"\vspace*{"+problemset["space"]+"}\n")
            tags = ("|".join(problemset["tags"]) if len(problemset["origin"])>0 else "暂无标签")
            raw_string = "\\item " + "{\\tiny ("+id+")} "+problem
            teachers_string += raw_string.replace("\\tiny","")+"\n\n关联目标:\n\n"+ objects + "\n\n标签: " + tags + "\n\n答案: "+answer + "\n\n" + "解答或提示: " + solution + "\n\n使用记录:\n\n"+ usage + "\n" + "\n\n出处: "+origin + "\n"
            students_string += raw_string + space + "\n\n"
        teachers_string = r"\setcounter{enumi}{"+ str(enumi_mode * problems_count) + "}\n\n" + teachers_string
        students_string = r"\setcounter{enumi}{"+ str(enumi_mode * problems_count) + "}\n\n" + students_string
        problems_count += len(problem_list)

        #替换源文件中的字符串
        data_teachers = data_teachers.replace(string_to_replace,teachers_string)
        data_students = data_students.replace(string_to_replace,students_string)
        print("题块",blockid,"处理完毕.")

    #保存和编译latex文件
    with open(teachers_latex_file,"w",encoding = "utf8") as f:
        f.write(data_teachers)
    print("开始编译教师版本pdf文件: ", teachers_latex_file)
    os.system("xelatex -interaction=batchmode -output-directory=" + destination_dir + " "+ teachers_latex_file)
    print(os.system("xelatex -interaction=batchmode -output-directory=" + destination_dir + " "+ teachers_latex_file))
    with open(students_latex_file,"w",encoding = "utf8") as f:
        f.write(data_students)
    print("开始编译学生版本pdf文件: ", students_latex_file)
    os.system("xelatex -interaction=batchmode -output-directory=" + destination_dir + " "+ students_latex_file)
    print(os.system("xelatex -interaction=batchmode -output-directory=" + destination_dir + " "+ students_latex_file))