# 文档处理工具
import json

from .tools.document_tools import (
    create_document, add_documents,add_table_and_replace,
    add_table_to_document,process_images_table,
)

# 内容处理工具
from .tools.content_tools import (
    add_picture,split_table_by_row_content,
    search_and_replace,add_picture_to_table
)

from .tools.get_pictures import (
    get_dict,
)

from .tools.dataproccess import (
    caculate_work_days,
    get_year_month,merge_info,
)

import asyncio


from .tools.defines import *
import os, re, datetime

async def generate_report(base_info, baogao_info):
    #获取模板编号、模板名称
    num_to_chinese = {1 : '一', 2 : '二', 3 : '三', 4 : '四', 5 : '五', 6 : '六', 7 : '七', 8 : '八', 9 : '九', 10 : '十', 11 : '十一', 12 : '十二'}
    cover_encode = "encode"
    cover_project = "project"
    baogao_name1 = "baogaoname1"
    baogao_name2 = "baogaoname2"
    company_name_yi = "company_name_yi"
    cover_date = "time"
    TITLE_OF_REPORT = "companyencode"
    jiegou_xuhao = 'num'
    
    
    
    try:
        base_info = merge_info(base_info, DEFAULT_BASE_INFO)
        jizu_data = base_info["jizu_data"]
        project_data = base_info["project_data"]
        shigong_data = base_info["shigong_data"]
        
        fengchang_name = project_data['farmName']
        Yi_company = project_data['inspectionUnit']
        yi_fuzeren = project_data['inspectionContact']
        yi_phone = project_data['inspectionPhone']
        fengchang_location = project_data['farmAddress']
        Jia_company = project_data['client']
        jia_fuzeren = project_data['clientContact']
        jia_phone = project_data['clientPhone']
        jizu_num = project_data['scale']
        jizu_xinghao = project_data['turbineModel']
        project_name = project_data['projectName']
        jizu_bianhao = jizu_data["turbineName"]
        start_date = project_data['startDate']
        end_date = project_data['endDate']
        
        fengmian_dir = project_data["fengmian_dir"]
        try:
            gongqi = caculate_work_days(start_date, end_date)
        except:
            gongqi = "日期获取失败"
    except Exception as e:
        print(f"数据库的项目-机组基本信息获取失败：{e}")
        return
        
    try:
        baogao_date = datetime.datetime.now().strftime("%Y年%m月%d日 %H:%M")   #现在的时间
        date_year_month = get_year_month(baogao_date)
        
        #前端信息
        baogao_info = merge_info(baogao_info, DEFAULT_BAOGAO_INFO)
        
        key_words= re.compile('|'.join(map(re.escape, baogao_info['key_words'].split(','))))
        
        shengcheng_dir = baogao_info['shengcheng_dir']
        muban_dir = baogao_info['muban_dir']
        if muban_dir == "" or shengcheng_dir == "":
            print("未配置模板/生成路径，请检查配置")
            return
        
        if_waibu = baogao_info["if_waibu"]
        if_neibu = baogao_info["if_neibu"]
        if_fanglei = baogao_info["if_fanglei"]
        total_pic_num = baogao_info["total_pic_num"]
        jiancha_renyuan = baogao_info["jiancha_renyuan"]
        baogao_zongjie = baogao_info["baogao_zongjie"]

        try:
            Jiancha_date = shigong_data["startTime"].replace("T", " ")   #检查日期
        except:
            Jiancha_date = "日期获取失败"
        image_count = shigong_data['imageCount']  #从施工方案获取的图片数量，待定!!!
        temperature = shigong_data['temperature']   #温度
        wind_speed = shigong_data['windSpeed'] #风速
        weather = shigong_data["weatherCode"]   #天气 不从此接口获取，待定！！！
        
        Y1 = base_info["Y1"]
        Y2 = base_info["Y2"]
        Y3 = base_info["Y3"]
        Y_Code = [Y1["Code"], Y2["Code"], Y3["Code"]] #Y1,Y2,Y3的编号
        partManufacturer = base_info["partManufacturer"]  #厂商
        print(f"找到叶片号{Y_Code},厂商{partManufacturer}")
        
        baogao_label = []
        renyuan_peizhi = []
        gongzuo_neirong = []
        shigong_fangan = []
        shebei_peizhi = []
        beizhu = []
        jiancha = []
        neirong = []
        #获取对应枚举字段
        if if_waibu:
            baogao_label.append("外观")
            if baogao_info["shigong_fangan"] == "None":
                print("未传入施工方案,使用已有枚举")
                renyuan_peizhi.append(SHIGONG_FANGAN_ENUM.WAIBU.RENYUAN_PEIZHI)
                gongzuo_neirong.append(SHIGONG_FANGAN_ENUM.WAIBU.GONGZUO_NEIRONG)
                shebei_peizhi.append(SHIGONG_FANGAN_ENUM.WAIBU.SHEBEI_PEIZHI)
                shigong_fangan.append(SHIGONG_FANGAN_ENUM.WAIBU.SHIGONG_FANGAN)
            else:
                pass  #待添加如果从平台传入枚举，但目前没必要，如果这种枚举标准信息库有更好的优化则可以实现
            jiancha.append("无人机近距离外观检查")
            neirong.append(f"、".join(Y_Code) + f"{len(Y_Code)}支叶片的前缘、后缘、迎风面、背风面。")
        if if_neibu:
            baogao_label.append("内部")
            if baogao_info["shigong_fangan"] == "None":
                renyuan_peizhi.append(SHIGONG_FANGAN_ENUM.NEIBU.RENYUAN_PEIZHI)
                gongzuo_neirong.append(SHIGONG_FANGAN_ENUM.NEIBU.GONGZUO_NEIRONG)
                shebei_peizhi.append(SHIGONG_FANGAN_ENUM.NEIBU.SHEBEI_PEIZHI)
                shigong_fangan.append(SHIGONG_FANGAN_ENUM.NEIBU.SHIGONG_FANGAN)
            else:
                pass
            jiancha.append("人工内部拍摄")
            neirong.append(f"、".join(Y_Code) +  f"{len(Y_Code)}支叶片的内部导雷卡、腹板、透光、人孔盖版、叶根盖板...")
        if if_fanglei:
            baogao_label.append("防雷")
            if baogao_info["shigong_fangan"] == "None":
                renyuan_peizhi.append(SHIGONG_FANGAN_ENUM.FANGLEI.YEPIAN.RENYUAN_PEIZHI)
                gongzuo_neirong.append(SHIGONG_FANGAN_ENUM.FANGLEI.YEPIAN.GONGZUO_NEIRONG)
                shebei_peizhi.append(SHIGONG_FANGAN_ENUM.FANGLEI.YEPIAN.SHEBEI_PEIZHI)
                shigong_fangan.append(SHIGONG_FANGAN_ENUM.FANGLEI.YEPIAN.SHIGONG_FANGAN)
            else:
                pass
            jiancha.append("人工防雷")
            neirong.append(f"轮毂至塔基导通、内部导线线阻、外部导线线阻...")
            
        
        baogao_bianzhi = baogao_info["userName"]
        baogao_shenghe = baogao_info["baogaoCheck"]
        tatong_dir = baogao_info["tatong_dir"]
        total_pic_dir = baogao_info["total_pic_dir"]
    except Exception as e:
        print(f"报告基本信息获取失败：{e}")
        return

    output_doc = None
    head_num = 1
    ###封面创建###
    cover_dirs = [os.path.join(muban_dir,"fengmian1.docx"),fengmian_dir,os.path.join(muban_dir,"fengmian2.docx")]
    #输出目录
    baogao_name = "叶片" + "、".join(baogao_label) + "检查报告"
    output_dir = os.path.normpath(f"{shengcheng_dir}/{project_name}项目{baogao_name}{jizu_bianhao}{baogao_date.split(' ')[0]}版.docx")
    
    version = 1
    while os.path.exists(output_dir):
        if version != 1:
            output_dir = output_dir.replace(f"版{version - 1}",f"版{version}")
        else:
            output_dir = output_dir.replace("版",f"版{version}")
        version += 1

    mianzhe_shengming = f"本报告仅涵盖{'、'.join(baogao_label)}检测内容"

    #创建文档、添加封面
    print(await create_document(output_dir))
    print(add_documents(output_dir, cover_dirs[0]))
    print(await add_picture(output_dir, cover_dirs[1], 6.41, 4))
    print(add_documents(output_dir, cover_dirs[2]))
    print("封面创建成功")

    #更改文档信息
    print(await search_and_replace(output_dir, TITLE_OF_REPORT, jizu_bianhao))
    print(await search_and_replace(output_dir, baogao_name1, baogao_name))
    print(await search_and_replace(output_dir, baogao_name2, baogao_name))
    print(await search_and_replace(output_dir, company_name_yi, Yi_company))
    print(await search_and_replace(output_dir, cover_project, fengchang_name))
    print(await search_and_replace(output_dir, cover_encode, jizu_bianhao))
    print(await search_and_replace(output_dir, cover_date, date_year_month))
    print(await search_and_replace(output_dir, 'bianzhi', baogao_bianzhi))
    print(await search_and_replace(output_dir, 'shenghe', baogao_shenghe))
    print(await search_and_replace(output_dir, 'mianzhe_shengming', mianzhe_shengming))
    
    total_table_num = 0
    #项目概况表
    print("开始添加项目概况表")
    XIANG_MU_GAI_KUANG = os.path.join(muban_dir,"xiangmugaikuo.docx")
    print(f"查找模板，找到模板：{XIANG_MU_GAI_KUANG}")
    project_location = fengchang_location
    company_name_jia = Jia_company
    fuzeren = yi_fuzeren
    phone_fuzeren = yi_phone
    xiangmuguige = jizu_num
    Yi_company = Yi_company
    XIANGMU_GAIKUO = list(list("" for i in range(6)) for j in range(5))
    XIANGMU_GAIKUO[0][1] = fengchang_name
    #XIANGMU_GAIKUO[0][3]=XIANGMU_GAIKUO[0][4] = "盐城市滨海县"
    XIANGMU_GAIKUO[0][4] = project_location
    #XIANGMU_GAIKUO[1][1]=XIANGMU_GAIKUO[2,1]=XIANGMU_GAIKUO[3,1] = "国家电投集团滨海风力发电有限公司"
    XIANGMU_GAIKUO[1][1] = company_name_jia
    XIANGMU_GAIKUO[1][4] = Yi_company
    XIANGMU_GAIKUO[2][1] = jia_fuzeren
    XIANGMU_GAIKUO[2][4] = fuzeren
    XIANGMU_GAIKUO[3][2] = jia_phone
    XIANGMU_GAIKUO[3][5] = phone_fuzeren
    XIANGMU_GAIKUO[4][1] = jizu_xinghao
    XIANGMU_GAIKUO[4][3] = xiangmuguige
    XIANGMU_GAIKUO[4][5] = gongqi
    print("建立表结构完毕，开始插入模板")
    #添加项目概况表
    print(f"输出路径:{output_dir}，模板路径:{XIANG_MU_GAI_KUANG},插入数据：{XIANGMU_GAIKUO}")
    output_doc, message = await add_table_to_document(output_dir, XIANG_MU_GAI_KUANG,5,5,total_table_num,XIANGMU_GAIKUO)
    print(message)
    print("模板插入完毕，开始替换内容")
    total_table_num  += 1
    print(await search_and_replace(output_dir, jiegou_xuhao, num_to_chinese[head_num]))
    head_num += 1

    #检查方案描述
    FANGAN_JIANCHA_DIR = os.path.join(muban_dir,"checkmethod.docx")
    list_to_replace = {
        'renyuan_peizhi' : "\n".join(renyuan_peizhi),
        'shebei_peizhi' : "\n".join(shebei_peizhi),
        'shigong_fangan' : "\n".join(shigong_fangan),
        'gongzuo_neirong' : "\n".join(gongzuo_neirong),
        'beizhu' : beizhu,
        'num' : num_to_chinese[head_num],
    }
    print(await add_table_and_replace(output_dir, FANGAN_JIANCHA_DIR, 0, list_to_replace))
    print(split_table_by_row_content(output_dir, output_dir, total_table_num))
    total_table_num  += 1
    head_num += 1


    JIANCHA_XINGXI_DIR = os.path.join(muban_dir,"checkinfo.docx")
    JIANCHA_XINGXI = list(list("" for i in range(4)) for j in range(9))
    JIANCHA_XINGXI[0][1] = jiancha_renyuan
    JIANCHA_XINGXI[1][1] = Jiancha_date.split(' ')[0]
    JIANCHA_XINGXI[1][3] = jizu_bianhao
    JIANCHA_XINGXI[2][1] = "风力发电机组" + baogao_name
    JIANCHA_XINGXI[2][3] = "、".join(jiancha)
    JIANCHA_XINGXI[3][2] = partManufacturer
    JIANCHA_XINGXI[4][1] = '叶片型号:' + jizu_xinghao
    JIANCHA_XINGXI[5][1] = Y_Code[0] if len(Y_Code) > 0 else "无"
    JIANCHA_XINGXI[6][1] = Y_Code[1] if len(Y_Code) > 1 else "无"
    JIANCHA_XINGXI[7][1] = Y_Code[2] if len(Y_Code) > 2 else "无"
    JIANCHA_XINGXI[8][0] = "本次" + "、".join(_ for _ in jiancha) + f"检查，采集叶片图片{total_pic_num}张，内容覆盖" + ";".join(_ for _ in neirong)
    #新建检查信息表
    output_doc, message = await add_table_to_document(output_dir, JIANCHA_XINGXI_DIR,9,4,total_table_num ,JIANCHA_XINGXI,False)
    #添加塔筒图片
    print(await add_picture_to_table(output_doc, output_dir, 4, 2, tatong_dir, total_table_num, width = 1.18))
    #添加略缩图
    print(await add_picture_to_table(output_doc, output_dir, 8, 0, total_pic_dir, total_table_num))
    print(message)
    print(await search_and_replace(output_dir, jiegou_xuhao, num_to_chinese[head_num]))
    head_num += 1
    total_table_num  += 1

    # 添加成果递交表
    CHENGGUO_DIJIAO_DIR = os.path.join(muban_dir,"chengguo_sub.docx")
    CHENGGUO_DIJIAO = list(list("" for i in range(4)) for j in range(6))
    CHENGGUO_DIJIAO[0][1] = jiancha_renyuan
    CHENGGUO_DIJIAO[1][1] = jia_fuzeren
    try:
        CHENGGUO_DIJIAO[2][1] = Jiancha_date.split(' ')[0]
    except:
        CHENGGUO_DIJIAO[2][1] = "日期获取失败"
    CHENGGUO_DIJIAO[3][1] = jiancha_renyuan
    CHENGGUO_DIJIAO[4][1] = baogao_bianzhi
    CHENGGUO_DIJIAO[5][1] = baogao_shenghe
    try:
        CHENGGUO_DIJIAO[2][3] = Jiancha_date.split(' ')[1]
        CHENGGUO_DIJIAO[3][3] = baogao_date.split(' ')[0]
        CHENGGUO_DIJIAO[4][3] = baogao_date.split(' ')[0]
    except:
        CHENGGUO_DIJIAO[2][3] = "日期获取失败"
        CHENGGUO_DIJIAO[3][3] = "日期获取失败"
        CHENGGUO_DIJIAO[4][3] = "日期获取失败"
    CHENGGUO_DIJIAO[5][3] = "未审核"

    output_doc, message = await add_table_to_document(output_dir, CHENGGUO_DIJIAO_DIR,5,5,total_table_num,CHENGGUO_DIJIAO,True,0.04)
    print(message)
    print(await search_and_replace(output_dir, jiegou_xuhao, num_to_chinese[head_num]))
    head_num += 1
    total_table_num  += 1
    
    #主要部位图片展示表/检查内容表
    #获取典型图信息        
    """
    需要获取：
    Y1、Y2、Y3叶片的图片数量，字典{描述：图片路径}
    """
    try:
        Y1_dict = get_dict(Y1)
        Y2_dict = get_dict(Y2)
        Y3_dict = get_dict(Y3)
        picture_Y1_num = len(Y1_dict)
        picture_Y2_num = len(Y2_dict)
        picture_Y3_num = len(Y3_dict)
    except Exception as e:
        print(f"获取图失败：{e}")
    print(f"图片、文字数量：{picture_Y1_num} {picture_Y2_num} {picture_Y3_num}")
    JIANCHA_NEIRONG_TOTAL_NUM = picture_Y1_num+ picture_Y2_num + picture_Y3_num
    col ,row = 3, 0
    JIANCHA_NEIRONG_PICTURES_TABLE = os.path.join(muban_dir,"check2.docx")
    JIANCHA_NEIRONG_Y1_DIR = os.path.join(muban_dir,"check_content.docx")
    JIANCHA_NEIRONG_Y1 = list(list("" for _ in range(3)) for j in range(1))
    JIANCHA_NEIRONG_Y1[0][0] = f"叶片1：{Y_Code[0]}检查内容"
    print(f"Y1标题内容：{JIANCHA_NEIRONG_Y1}")
    JIANCHA_NEIRONG_Y2_DIR = os.path.join(muban_dir,"check3.docx")
    JIANCHA_NEIRONG_Y2 = list(list("" for _ in range(3)) for j in range(1))
    JIANCHA_NEIRONG_Y2[0][0] = f"叶片2：{Y_Code[1]}检查内容"
    print(f"Y2标题内容：{JIANCHA_NEIRONG_Y2}")
    JIANCHA_NEIRONG_Y3_DIR = os.path.join(muban_dir,"check3.docx")
    JIANCHA_NEIRONG_Y3 = list(list("" for _ in range(3)) for j in range(1))
    JIANCHA_NEIRONG_Y3[0][0] = f"叶片3：{Y_Code[2]}检查内容"
    print(f"Y3标题内容：{JIANCHA_NEIRONG_Y3}")
    print(f"当前表格序号为 {total_table_num}")
    print(key_words)
    output_doc, message = await add_table_to_document(output_dir, JIANCHA_NEIRONG_Y1_DIR,1,3,total_table_num,JIANCHA_NEIRONG_Y1,True, 1)
    print(message)
    total_table_num += 1
    
    total_table_num = await process_images_table(Y1_dict, output_dir, total_table_num, JIANCHA_NEIRONG_PICTURES_TABLE, key_words)
    
    output_doc, message = await add_table_to_document(output_dir, JIANCHA_NEIRONG_Y2_DIR,1,3,total_table_num,JIANCHA_NEIRONG_Y2,True, 1)
    print(message)    
    total_table_num += 1
    
    total_table_num = await process_images_table(Y2_dict, output_dir, total_table_num, JIANCHA_NEIRONG_PICTURES_TABLE, key_words)
    
    output_doc, message = await add_table_to_document(output_dir, JIANCHA_NEIRONG_Y3_DIR,1,3,total_table_num,JIANCHA_NEIRONG_Y3,True, 1)
    print(message)  
    total_table_num += 1
    
    total_table_num = await process_images_table(Y3_dict, output_dir, total_table_num, JIANCHA_NEIRONG_PICTURES_TABLE, key_words)
    print(await search_and_replace(output_dir, jiegou_xuhao, num_to_chinese[head_num]))
    head_num += 1

    
    #总结
    ZONG_JIE_DIR = os.path.join(muban_dir,"result.docx")
    ZONG_JIE_BEFORE = "result"
    ZONG_JIE = baogao_zongjie
    print(add_documents(output_dir, ZONG_JIE_DIR))
    print(await search_and_replace(output_dir, ZONG_JIE_BEFORE, ZONG_JIE))
    print(await search_and_replace(output_dir, 'company_yi', Yi_company))
    print(await search_and_replace(output_dir, 'baogao_date', baogao_date.split(' ')[0]))
    print(await search_and_replace(output_dir, jiegou_xuhao, num_to_chinese[head_num]))
    return output_dir
def main(json_data1,json_data2):
    json_data1=json.loads(json_data1)
    json_data2=json.loads(json_data2)
    asyncio.run(generate_report(json_data1,json_data2))
    print('文档生成完毕')
