# -*- coding: utf-8 -*-
# @Time : 2023/3/23 09:43
# @Author : bruxellse_li
# @File : generate_report.py
# @Project : 从word中提取指定表格
from docx import Document
import os, time
from pathlib import Path
import requests
from flask import request
from flask import Flask, send_file
# from transform_doc_to_docx import doc2docx, closesoft
import subprocess
from generate.gen_user_report_auto_generated import new_main_process
UPLOAD_FOLDER = r'data'       # 上传路径
Path(UPLOAD_FOLDER).mkdir(parents=True, exist_ok=True)
abs_path = os.path.split(os.path.realpath(__file__))[0]


def doc2docx(doc_path, docx_path):
    # 使用LibreOffice将doc文件转换为docx文件
    subprocess.call(['libreoffice', '--headless', '--convert-to', 'docx', doc_path, '--outdir', os.path.dirname(docx_path)])
    # 将转换后的docx文件重命名为目标文件名
    os.rename(os.path.splitext(doc_path)[0] + '.docx', docx_path)


def generate_report(template_path, document_path, report_name, object):
    """
    template_path : 模板文件下载地址
    document_path: 半成品文件下载地址
    report_name: 报告名称
    data_object: 待填充数据
    :return:
    """
    template_request = template_path
    doc_request = document_path
    report_name = report_name + ".docx"
    data_object = object["data_object"]
    tables_dict = object["tables_dict"]
    current_filename = time.strftime('%Y_%m_%d-%H_%M_%S') + ".docx"
    save_path = UPLOAD_FOLDER + "/" + current_filename
    # 先判断是否是docx 格式
    template_filename = template_request.split("/")[-1]
    if ".doc" in template_request:
        temp_template_path = os.path.join(UPLOAD_FOLDER, template_filename)
        # 获取文件路径前缀
        template_path = os.path.splitext(temp_template_path)[0] + '.docx'
        # 将doc转换为docx
        doc2docx(temp_template_path, template_path)
    elif ".docx" in template_request:
        template_path = os.path.join(UPLOAD_FOLDER, template_filename)
    else:
        return "上传文件格式有误，当前仅支持doc 和 docx 格式，请选择正确文件重新上传！"

    doc_filename = doc_request.split("/")[-1]
    if ".doc" in doc_request:
        temp_doc_path = os.path.join(UPLOAD_FOLDER, doc_filename)
        # 获取文件路径前缀
        doc_path = os.path.splitext(temp_doc_path)[0] + '.docx'
        # 将doc转换为docx
        doc2docx(temp_doc_path, doc_path)
        half_work_path = doc_path
    elif ".docx" in doc_request:
        half_work_path = os.path.join(UPLOAD_FOLDER, template_filename)
    else:
        return "上传文件格式有误，当前仅支持doc 和 docx 格式，请选择正确文件重新上传！"
    # main_process(half_work_path, tables_dict, template_path, report_name, data_object, save_path)
    # send_path = os.path.join(UPLOAD_FOLDER, report_name)
    # return send_file(send_path, as_attachment=True)


if __name__ == "__main__":
    template_path = "data/wKjIbGQb3gaARMRCAACAACgxnK856.docx"
    document_path = "data/wKjIbGQb66OAH-8eAAQAAJHFYeM24.docx"
    report_name = "财务报告"
    object = {
          "tables_dict": {
                "table13": "（2）以名义金额计量的资产名称、数量等情况，以及以名义金额计量理由的说明。",
                "table5": "收入费用表（2）",
                "table4": "收入费用表（1）",
                "table3": "资产负债表续表2",
                "table2": "资产负债表续表1",
                "table1": "资产负债表",
                "table9": "（17）其他应付款明细信息如下：",
                "table8": "（9）无形资产明细信息如下：",
                "table10": "（24）其他收入明细信息如下：",
                "table7": "（7）固定资产明细信息如下：",
                "table11": "（25）业务活动费用明细信息如下：",
                "table6": "（1）货币资金明细信息如下：",
                "table12": "（28）商品和服务费用明细信息如下："
            },
        "data_object": {
                "负债占比": [],
                "费用占比": [],
                "流动资产占比": [],
                "流动负债占比": [],
                "收入占比": [],
                "finance": {
                    "currentLiabilitiesCompose": "",
                    "cashRatio": "",
                    "revenueExpensesRatio": "",
                    "currentRatioRemark": "说明本单位流动资产偿还短期债务的能力弱",
                    "beInDebtChangeRatioRemark": "",
                    "assetLiabilityRatioRemark": "说明本单位财务风险低",
                    "totalExpensesCompose": "",
                    "debtComposition": "流动负债占""，非流动负债占""",
                    "totalRevenueCompose": "",
                    "totalExpensesChangeRatioRemark": "",
                    "composition": "流动资产占比，非流动资产占比",
                    "unitDebtComposition": "流动负债和非流动负债",
                    "cashRatioRemark": "说明本单位利用现金和现金等价物偿还短期债务的能力弱",
                    "affordableHouseNewRation": "",
                    "totalAssetsChangeRatioRemark": "",
                    "currentRatio": "",
                    "currentAssetsCompose": "",
                    "publicInfrastructureNewRatio": "",
                    "totalRevenueComposeDetail": "",
                    "assetLiabilityRatio": "",
                    "unitAssetComposition": "流动资产和非流动资产",
                    "fixedAssetsDepreciationRatio": "",
                    "revenueExpensesRatioRemark": "大于",
                    "totalRevenueChangeRatioRemark": "",
                    "otherRemark": "",
                    "nonCurrentAssetsCompose": ""
                },
                "资产占比": [],
                "info": {
                    "internalControl": "2021年，本单位加强学习国家和省关于内部控制的文件。建立健全了单位层面的内部控制体系和制度，健全了预算、收支、采购、建设、资产和合同的内控流程和制度，把内部控制落实在业务流程中，实现了不相容岗位相互分离、形成相互制约、相互监督的工作机制；实现了内部授权审批控制。",
                    "unitName": "安丘速度单位",
                    "unitCall": "本部门",
                    "mainFunctions": "无资料数据",
                    "year": "2023",
                    "unitBudgetLevel": "",
                    "institutionalSituation": "无资料数据",
                    "performanceManagement": "2021年，本单位按照绩效管理要求对照设定预算绩效目标、绩效指标的成本指标、产出指标、效益指标、满意度指标等具体内容，开展项目绩效目标申报、运行监控和自评工作。通过预算绩效管理对工作中存在的薄弱环节作出针对性查漏补缺和持续完善。",
                    "LastYear": "2022",
                    "personnelSituation": "无资料数据",
                    "unitType": "",
                    "budgetManagement": "2021年，本单位严格按照《预算法》、《会计法》、《政府会计制度》和上级的文件建立健全财务制度；严格执行财经纪律和各项财务制度；强化预算管理，加强对银行存款和现金的管理；单位对年终决算高度重视，组织专人负责编制决算报告，对决算数据进行了严格审核，认真分析并应用到下年的预算工作。",
                    "assetManagement": "2021年，本单位资产实行分类管理，建立健全了资产内部管理制度；单位加强对实物资产和无形资产的管理，明确相关部门和岗位的职责权限，强化对配置、使用和处置等关键环节的管控；明确资产使用和保管责任人，落实资产使用人在资产管理中的责任。",
                    "pppProject": "本单位无PPP项目。",
                    "careerAchievements": "无资料数据"
                },
                "非流动资产占比": []
            }
        }
    generate_report(template_path, document_path, report_name, object)

