import os,re,json,time

"""---设置原题目id与新题目id列表, 新id的数目不能小于旧id的数目---"""
old_ids = "14993,14941,14933,14912,14937"
new_ids = "31397:31500"
"""---设置完毕---"""
"""---完成编辑后记得运行第二个单元格---"""

# 题号转换
def generate_number_set(string,dict):
    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

with open(r"../题库0.3/Problems.json","r",encoding = "utf8") as f:
    database = f.read()
pro_dict = json.loads(database)

old_id_list = generate_number_set(old_ids,pro_dict)
new_id_list = generate_number_set(new_ids,pro_dict)




#判断是否有已占用的题号
occupied_flag = False
for new_id in new_id_list:
    if new_id in pro_dict:
        print("ID",new_id,"已被使用.")
        occupied_flag = True

length_old = len(old_id_list)
length_new = len(new_id_list)
if length_old > length_new:
    print("新ID的个数不够")


# 将未修订的题目添加入数据库, 并作好关联
used_new_id_list = []
if not occupied_flag and length_new >= length_old:
    for pos in range(length_old):
        old_id = old_id_list[pos]
        new_id = new_id_list[pos]
        used_new_id_list.append(new_id)
        pro_dict[new_id] = {}
        for field in pro_dict[old_id]:
            if not field == "id":
                pro_dict[new_id][field] = pro_dict[old_id][field] if not type(pro_dict[old_id][field]) == list else pro_dict[old_id][field].copy()
            else:
                pro_dict[new_id][field] = new_id
        pro_dict[new_id]["related"].append(old_id)
        pro_dict[new_id]["same"] = []
        pro_dict[new_id]["objs"] = pro_dict[old_id]["objs"].copy()
        pro_dict[new_id]["usages"] = []
        pro_dict[new_id]["edit"].append(str(time.localtime().tm_year)+str(time.localtime().tm_mon).zfill(2)+str(time.localtime().tm_mday).zfill(2) + "\t")
        pro_dict[old_id]["related"].append(new_id)
        pro_dict[new_id]["origin"] += "-" + str(time.localtime().tm_year)+str(time.localtime().tm_mon).zfill(2)+str(time.localtime().tm_mday).zfill(2) + "修改"
    with open(r"../题库0.3/Problems.json","w",encoding = "utf8") as f:
        f.write(json.dumps(pro_dict,indent = 4,ensure_ascii= False))
    output_list = {}
    for id in used_new_id_list:
        output_list[id] = pro_dict[id].copy()

    with open(r"临时文件/problem_edit.json","w",encoding="u8") as f:
        f.write(json.dumps(output_list,indent = 4,ensure_ascii=False))
    os.system(r"code -g 临时文件/problem_edit.json")


