#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2023/3/20 11:43
# @Author : bruxellse_li
# @File : app_run.py
# @Project : 从word中提取指定表格
import time
import datetime
import os
from docx import Document
from flask import Flask, send_file, jsonify
from flask import request, Response
import requests
from extract_table import get_choose_table, get_other_table, get_other1_table, read_document, replace_document
from extract_factor import get_text_from_docx, Extract, get_cover_content_from_docx, Other_Extract
import json, re
from utils.log import logger
import subprocess
from pathlib import Path
import traceback
from fdfs_client.client import *
# from generate.gen_user_report_auto_generated import new_main_process
from TextRewriting import get_list_result
from sentence_split import qx_correct, ner_correct
from multiy_area_copy_content import send_regenerate_report
import queue
# Queue基本FIFO队列  先进先出 FIFO即First in First Out,先进先出
# maxsize设置队列中，数据上限，小于或等于0则不限制，容器中大于这个数则阻塞，直到队列中的数据被消掉
q = queue.Queue(maxsize=0)
# 关闭多余连接
s = requests.session()
s.keep_alive = False

# 定义数据库链接基础信息
database_config = {
    'host': '114.116.44.11',
    'port': 3306,
    'user': 'root',
    'password': 'f7s0&7qqtK',
    'database': 'clb_project'
}
# temp_url = "http://114.115.215.96/"
temp_url = "http://dfs/"
"""
测试地址：http://114.115.185.13:9988/datapull/aiReport/report/callbackStatus
正式地址：http://192.168.1.70:9988/datapull/aiReport/report/callbackStatus
"""
# callback_url = "http://114.115.185.13:9988/datapull/aiReport/report/callbackStatus"
callback_url = "http://192.168.1.70:9988/datapull/aiReport/report/callbackStatus"

app = Flask(__name__)
UPLOAD_FOLDER = r'data/'       # 上传路径
Path(UPLOAD_FOLDER).mkdir(parents=True, exist_ok=True)
abs_path = os.path.split(os.path.realpath(__file__))[0]
ALLOWED_EXTENSIONS = set(['doc', 'docx'])   # 允许上传的文件类型

# 文件上传服务器定义
tracker_conf = get_tracker_conf("data/fdfs_client.conf")
client = Fdfs_client(tracker_conf)
# 跨域支持1
from flask_cors import CORS

CORS(app, supports_credentials=True)


def allowed_file(filename):
    # 验证上传的文件名是否符合要求，文件名必须带点并且符合允许上传的文件类型要求，两者都满足则返回 true
    if '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS:
        return filename


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)    # zhangtao 2023-05-12


@app.route("/", methods=["GET"])
def hello_world():
    app.logger.info('Hello World!')
    return "Hello World"


@app.route('/subject_consumer', methods=['GET', 'POST'])
def subject_consumer():
    if not q.empty():
        config_info = q.get()
        logger.info(config_info)
        return jsonify(message='当前队列数量：' + str(q.qsize()),
                       queue_left_number=str(q.qsize()),
                       data=config_info)
    else:
        return jsonify(message='队列为空！', queue_left_number=0)


@app.route('/queue_size', methods=['GET', 'POST'])
def queue_size():
    return jsonify(queue_left_number=q.qsize())


@app.route('/extract_special_table', methods=['POST'])
def extract_special_table():
    # table_params ——['资产负债表', '收入费用表（1）', '收入费用表（2）']
    data = request.get_json()
    template_request = data["path"]
    logger.info(template_request)
    # filename = file_request.split("/")[-1]
    template_filename = os.path.split(template_request)[-1]
    # 文件先下载再判断是否转换
    if str(template_filename).endswith(".doc"):
        r = requests.get(template_request, stream=True)
        my_timestamp = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
        save_path4doc = os.path.join(UPLOAD_FOLDER, '{}_{}'.format(my_timestamp, template_filename))
        with open(save_path4doc, "wb") as f:
            for chunk in r.iter_content(chunk_size=512):
                f.write(chunk)

        # temp_template_path = os.path.join(UPLOAD_FOLDER, template_filename)
        # # 获取文件路径前缀
        # template_path = os.path.splitext(temp_template_path)[0] + '.docx'
        # # 将doc转换为docx
        save_path4docx = '{}.docx'.format(os.path.splitext(save_path4doc)[0])
        doc2docx(save_path4doc, save_path4docx)
        template_path = save_path4docx

    elif ".docx" in template_request:
        r = requests.get(template_request, stream=True)
        my_timestamp = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
        save_path4docx = os.path.join(UPLOAD_FOLDER, '{}_{}'.format(my_timestamp, template_filename))
        with open(save_path4docx, "wb") as f:
            for chunk in r.iter_content(chunk_size=512):
                f.write(chunk)
        # template_path = os.path.join(UPLOAD_FOLDER, template_filename)
        template_path = save_path4docx
    else:
        return "上传文件格式有误，当前仅支持doc 和 docx 格式，请选择正确文件重新上传！"

    document = Document(template_path)

    table_names = ["以名义金额计量的资产名称、数量等情况，以及以名义金额计量理由的说明"]
    data_result = get_other_table(document, table_names)
    if data_result["以名义金额计量的资产名称、数量等情况，以及以名义金额计量理由的说明"]:
        data_result = data_result
    else:
        temp_table_result = get_other_table(document, ["本单位无以名义金额计量的资产"])
        del data_result["以名义金额计量的资产名称、数量等情况，以及以名义金额计量理由的说明"]
        data_result.update(temp_table_result)
    # os.remove(os.path.join(UPLOAD_FOLDER, filename))
    return Response(json.dumps(data_result, ensure_ascii=False), content_type='application/json')


@app.route('/extract_other_table1', methods=['POST'])
def extract_special_table1():
    # table_params ——['资产负债表', '收入费用表（1）', '收入费用表（2）']
    data = request.get_json()
    file_request = data["path"]
    logger.info(file_request)
    filename = file_request.split("/")[-1]
    if ".doc" in file_request:
        r = requests.get(file_request, stream=True)
        with open(os.path.join(UPLOAD_FOLDER, filename), "wb") as f:
            for chunk in r.iter_content(chunk_size=512):
                f.write(chunk)

        doc_path = os.path.join(UPLOAD_FOLDER, filename)

        # 获取文件路径前缀
        new_path = os.path.splitext(doc_path)[0] + '.docx'
        # 将doc转换为docx
        doc2docx(doc_path, new_path)

        document = Document(new_path)
    elif ".docx" in file_request:
        r = requests.get(file_request, stream=True)
        with open(os.path.join(UPLOAD_FOLDER, filename), "wb") as f:
            for chunk in r.iter_content(chunk_size=512):
                f.write(chunk)
        document = Document(os.path.join(UPLOAD_FOLDER, filename))
    else:
        return "上传文件格式有误，当前仅支持doc 和 docx 格式，请选择正确文件重新上传！"

    table_names = ['货币资金明细信息如下']
    data_result = get_other1_table(document, table_names)
    # os.remove(os.path.join(UPLOAD_FOLDER, filename))
    return Response(json.dumps(data_result, ensure_ascii=False), content_type='application/json')


@app.route('/extract_table', methods=['POST'])
def extract_table():
    # table_params ——['资产负债表', '收入费用表（1）', '收入费用表（2）']
    data = request.get_json()
    file_request = data["path"]
    logger.info(file_request)
    filename = file_request.split("/")[-1]
    if ".doc" in file_request:
        r = requests.get(file_request, stream=True)
        with open(os.path.join(UPLOAD_FOLDER, filename), "wb") as f:
            for chunk in r.iter_content(chunk_size=512):
                f.write(chunk)

        doc_path = os.path.join(UPLOAD_FOLDER, filename)
        # print(doc_path)
        # 获取文件路径前缀
        new_path = os.path.splitext(doc_path)[0] + '.docx'
        # 将doc转换为docx
        doc2docx(doc_path, new_path)

        document = Document(new_path)
    elif ".docx" in file_request:
        r = requests.get(file_request, stream=True)
        with open(os.path.join(UPLOAD_FOLDER, filename), "wb") as f:
            for chunk in r.iter_content(chunk_size=512):
                f.write(chunk)
        document = Document(os.path.join(UPLOAD_FOLDER, filename))
    else:
        return "上传文件格式有误，当前仅支持doc 和 docx 格式，请选择正确文件重新上传！"

    table_params = ['资产负债表', '收入费用表（1）', '收入费用表（2）']
    data = get_choose_table(document, table_params)
    # 解析上级关系
    # 处理资产负债表
    temp_list = data["资产负债表"]
    temp_dict = {}

    for temp in temp_list:
        temp_text = re.sub(":", "：", temp["项目"])
        pro_text = temp_text[-1]

        if pro_text == "：":
            temp_dict.update({"temp_key": temp_text})
            continue
        elif pro_text.isdigit():
            temp["项目"] = temp_text[:-1]
            temp["上级项目"] = temp_dict["temp_key"].strip("：")
        else:
            temp["上级项目"] = temp_dict["temp_key"].strip("：")

    # 处理收入费用表（1）
    temp_list_0 = data["收入费用表（1）"]
    temp_dict_0 = {"temp_key": "收入合计"}

    for temp_0 in temp_list_0:
        # 先判断字段名是否为数字
        temp_text = temp_0["项目"]
        pro_text = temp_text[-1]
        if pro_text.isdigit():
            temp_0["项目"] = temp_text[:-1]
        else:
            temp_0["项目"] = temp_text

        if temp_0["项目"].strip() == "收入合计":
            temp_dict_0.update({"temp_key": "费用合计"})
        else:
            if temp_0["项目"].strip() == "费用合计" or temp_0["项目"].strip() == "本年盈余":
                continue
            else:
                temp_0["上级项目"] = temp_dict_0["temp_key"]

    # 处理收入费用表（2）
    temp_list_1 = data["收入费用表（2）"]
    temp_dict_1 = {"temp_key": "收入合计"}
    for temp_1 in temp_list_1:
        # 先判断字段名是否为数字
        temp_text = temp_1["项目"]
        pro_text = temp_text[-1]

        if pro_text.isdigit():
            temp_1["项目"] = temp_text[:-1]
        else:
            temp_1["项目"] = temp_text

        if temp_1["项目"].strip() == "收入合计":
            temp_dict_1.update({"temp_key": "费用合计"})
        else:
            if temp_1["项目"].strip() == "费用合计" or temp_1["项目"].strip() == "本年盈余":
                continue
            else:
                temp_1["上级项目"] = temp_dict_1["temp_key"]
    # os.remove(os.path.join(UPLOAD_FOLDER, filename))

    return Response(json.dumps(data, ensure_ascii=False), content_type='application/json')


@app.route('/extract_factor', methods=['POST'])
def extract_factor():
    data = request.get_json()
    file_request = data["path"]
    logger.info(file_request)
    filename = file_request.split("/")[-1]
    if ".doc" in file_request:
        r = requests.get(file_request, stream=True)
        with open(os.path.join(UPLOAD_FOLDER, filename), "wb") as f:
            for chunk in r.iter_content(chunk_size=512):
                f.write(chunk)

        doc_path = os.path.join(UPLOAD_FOLDER, filename)
        new_path = os.path.splitext(doc_path)[0] + '.docx'

        doc2docx(doc_path, new_path)
        document = get_text_from_docx(new_path)

    elif ".docx" in file_request:
        r = requests.get(file_request, stream=True)
        with open(os.path.join(UPLOAD_FOLDER, filename), "wb") as f:
            for chunk in r.iter_content(chunk_size=512):
                f.write(chunk)

        document = get_text_from_docx(os.path.join(UPLOAD_FOLDER, filename))
    else:
        return "上传文件格式有误，当前仅支持doc 和 docx 格式，请选择正确文件重新上传！"

    data = Extract().extract_result(document)
    # os.remove(os.path.join(UPLOAD_FOLDER, filename))
    return Response(json.dumps(data, ensure_ascii=False), content_type='application/json')


@app.route('/generate_report', methods=['POST'])
def generate_report():
    """
    template_path : 模板文件下载地址
    document_path: 半成品文件下载地址
    report_name: 报告名称
    data_object: 待填充数据
    :return:
    """

    data = request.get_json()
    template_url = data["template_path"]  # 模板 下载链接
    half_document_url = data["document_path"]  # 半成品  下载链接
    logger.info(template_url)
    logger.info(half_document_url)

    report_id = data["report_id"]
    template_id = data["template_id"]
    report_name = data["report_name"]
    data_object = data["object"]["data_object"]
    tables_dict = data["object"]["tables_dict"]

    try:
        # 先判断是否是docx 格式
        # template_filename = template_request.split("/")[-1]
        template_filename = os.path.split(template_url)[-1]   # todo: url 切分是否对？？？
        # 文件先下载再判断是否转换
        if str(template_filename).endswith(".doc"):
            r = requests.get(template_url, stream=True)
            my_timestamp = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
            save_path4doc = os.path.join(UPLOAD_FOLDER, '{}_{}'.format(my_timestamp, template_filename))
            with open(save_path4doc, "wb") as f:
                for chunk in r.iter_content(chunk_size=512):
                    f.write(chunk)

            save_path4docx = '{}.docx'.format(os.path.splitext(save_path4doc)[0])
            doc2docx(save_path4doc, save_path4docx)
            template_path = save_path4docx  # 本地路径

        elif str(template_filename).endswith(".docx"):
            r = requests.get(template_url, stream=True)
            my_timestamp = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
            save_path4docx = os.path.join(UPLOAD_FOLDER, '{}_{}'.format(my_timestamp, template_filename))
            with open(save_path4docx, "wb") as f:
                for chunk in r.iter_content(chunk_size=512):
                    f.write(chunk)
            # template_path = os.path.join(UPLOAD_FOLDER, template_filename)
            template_path = save_path4docx
        else:
            return "上传文件格式有误，当前仅支持doc 和 docx 格式，请选择正确文件重新上传！"

        # doc_filename = doc_request.split("/")[-1]
        doc_filename = os.path.split(half_document_url)[-1]   # todo: url 切分是否对？？？
        if str(doc_filename).endswith(".doc"):
            r1 = requests.get(half_document_url, stream=True)
            my_timestamp2 = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
            save_path4doc2 = os.path.join(UPLOAD_FOLDER, '{}_{}'.format(my_timestamp2, doc_filename))
            with open(save_path4doc2, "wb") as f1:
                for chunk in r1.iter_content(chunk_size=512):
                    f1.write(chunk)

            # temp_doc_path = os.path.join(UPLOAD_FOLDER, doc_filename)
            # # 获取文件路径前缀
            # doc_path = os.path.splitext(temp_doc_path)[0] + '.docx'

            save_path4docx2 = '{}.docx'.format(os.path.splitext(save_path4doc2)[0])
            # 将doc转换为docx
            doc2docx(save_path4doc2, save_path4docx2)
            # half_work_path = doc_path
            half_document_path = save_path4docx2

        elif str(doc_filename).endswith(".docx"):
            r1 = requests.get(half_document_url, stream=True)
            my_timestamp2 = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
            half_document_path = os.path.join(UPLOAD_FOLDER, '{}_{}'.format(my_timestamp2, doc_filename))
            with open(half_document_path, "wb") as f1:
                for chunk in r1.iter_content(chunk_size=512):
                    f1.write(chunk)
        else:
            return "上传文件格式有误，当前仅支持doc 和 docx 格式，请选择正确文件重新上传！"

        # todo: 调整为

        output_report_path = os.path.join(UPLOAD_FOLDER,
                                          '{}_{}.docx'.format(str(datetime.datetime.now().strftime('%Y%m%d%H%M%S')),
                                                              report_name))
        # todo: 先将任务放入后台进行处理
        config_info = {
            "report_id": report_id,
            "template_id": template_id,
            "half_document_path": half_document_path,
            "tables_dict": tables_dict,
            "template_path": template_path,
            "data_object": data_object,
            "output_report_path": output_report_path,
            "report_name": report_name
        }
        q.put(config_info)
        logger.info(config_info)

    except Exception as e:
        dict_result = {
            "status": "1",        # 处理状态 （0 成功， 1 失败）
            "result": "生成失败！+ {}".format(str(e)),
            "id": report_id,        # 报告id
            "templeteId": template_id,      # 报告模板
            "filePath": ""
        }
        # todo: 调用java的状态更新接口返回异常的结果
        payload = json.dumps(dict_result)
        headers = {
            'Content-Type': 'application/json'
        }
        """
        测试地址：http://114.115.185.13:9988/datapull/aiReport/report/callbackStatus
        正式地址：http://192.168.1.70:9988/datapull/aiReport/report/callbackStatus
        """
        # callback_url = "http://114.115.185.13:9988/datapull/aiReport/report/callbackStatus"
        r1 = requests.post(url=callback_url,
                           headers=headers, data=payload)
        r1_json = json.loads(r1.text)
        logger.info(r1_json)
        return dict_result
    return "Success"


@app.route('/gx_app', methods=['POST'])
def gx_app():
    try:
        data = request.get_json()
        text = data["content"] if "content" in data else ""
        list_result = get_list_result(text)
        dict_result = {
                          'code': 300,
                          'msg': 'success',
                          'isHandleSuccess': True,
                          'result_data': list_result
                        }
    except Exception as e:
        traceback.print_exc()
        dict_result = {
                        'code': 500,
                        'msg': 'fail' + str(e),
                        'isHandleSuccess': False,
                        'result_data': None
                  }
    return jsonify(dict_result)


@app.route('/ner_error', methods=(['POST']))
def ner_error():
    data = request.get_json()
    text = data['content']
    param = data["param"].strip()
    try:
        content, right_result = ner_correct(text, param)
    except Exception as e:
        return json.dumps({'code': '500',
                           'message': 'failure' + str(e),
                           'resultData': None})
    return json.dumps({'code': '200',
                       'message': 'success',
                       'resultData': {'contentDetails': right_result,
                                      'correctContent': content}})


@app.route('/qx_error', methods=(['POST']))
def qx_error():
    data = request.get_json()
    text = data['content']
    try:
        content, right_result = qx_correct(text)
    except Exception as e:
        return json.dumps({'code': '500',
                           'message': 'failure' + str(e),
                           'resultData': None})
    return json.dumps({'code': '200',
                       'message': 'success',
                       'resultData': {'contentDetails': right_result,
                                      'correctContent': content}})


@app.route('/extract_cover_factor', methods=['POST'])
def extract_cover_factor():
    data = request.get_json()
    file_request = data["path"]
    filename = file_request.split("/")[-1]
    if ".doc" in file_request:
        r = requests.get(file_request, stream=True)
        with open(os.path.join(UPLOAD_FOLDER, filename), "wb") as f:
            for chunk in r.iter_content(chunk_size=512):
                f.write(chunk)

        doc_path = os.path.join(UPLOAD_FOLDER, filename)
        new_path = os.path.splitext(doc_path)[0] + '.docx'

        doc2docx(doc_path, new_path)
        cover_contents, other_contents = get_cover_content_from_docx(new_path)

    elif ".docx" in file_request:
        r = requests.get(file_request, stream=True)
        with open(os.path.join(UPLOAD_FOLDER, filename), "wb") as f:
            for chunk in r.iter_content(chunk_size=512):
                f.write(chunk)

        cover_contents, other_contents = get_cover_content_from_docx(os.path.join(UPLOAD_FOLDER, filename))
    else:
        return "上传文件格式有误，当前仅支持doc 和 docx 格式，请选择正确文件重新上传！"

    cover_pattern = re.compile(r"([0-9]{0,4}).*(?=(财务报告))")
    # print(content)
    cover_group = cover_pattern.search(cover_contents)
    if cover_group:
        cover_text = cover_group.group().strip()
    else:
        cover_text = ""
    # todo: 处理其它的字段信息
    other_extract = Other_Extract()
    other_data = other_extract.extract_other_result(other_contents)
    other_data["reportTitle"] = cover_text
    # os.remove(os.path.join(UPLOAD_FOLDER, filename))
    return Response(json.dumps(other_data, ensure_ascii=False), content_type='application/json')


@app.route('/generate_final_report', methods=['POST'])
def generate_final_report():
    """
    template_path : 模板文件下载地址
    document_path: 半成品文件下载地址
    report_name: 报告名称
    data_object: 待填充数据
    :return:
    """
    data = request.get_json()
    template_url = data["template_path"]        # 第二次生成时的模板 下载链接
    half_document_url = data["document_path"]   # 第二次生成时的半成品，即第一次生成的报告 下载链接
    logger.info(template_url)
    logger.info(half_document_url)


    report_id = data["report_id"]
    report_name = data["report_name"]
    data_object = data["object"]["data_object"]
     # todo: 处理模板
    # 先判断是否是docx 格式
    template_filename = template_url.split("/")[-1]
    # 文件先下载再判断是否转换
    if str(template_filename).endswith('.doc'):
        r = requests.get(template_url, stream=True)
        my_timestamp = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
        save_path4doc = os.path.join(UPLOAD_FOLDER, '{}_{}'.format(my_timestamp, template_filename))
        with open(save_path4doc, "wb") as f:
            for chunk in r.iter_content(chunk_size=512):
                f.write(chunk)

        save_path4docx = '{}.docx'.format(os.path.splitext(save_path4doc)[0])
        doc2docx(save_path4doc, save_path4docx)
        template_path = save_path4docx  # 本地路径
    elif str(template_filename).endswith(".docx"):
        r = requests.get(template_url, stream=True)
        my_timestamp = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
        save_path4docx = os.path.join(UPLOAD_FOLDER, '{}_{}'.format(my_timestamp, template_filename))
        with open(save_path4docx, "wb") as f:
            for chunk in r.iter_content(chunk_size=512):
                f.write(chunk)
        template_path = save_path4docx
    else:
        return "上传文件格式有误，当前仅支持doc 和 docx 格式，请选择正确文件重新上传！"

    # todo: 处理半成品
    half_document_filename = os.path.split(half_document_url)[-1]   # todo: url 切分是否对？？？
    if str(half_document_filename).endswith(".doc"):
        r1 = requests.get(half_document_url, stream=True)
        my_timestamp2 = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
        save_path4doc2 = os.path.join(UPLOAD_FOLDER, '{}_{}'.format(my_timestamp2, half_document_filename))
        with open(save_path4doc2, "wb") as f1:
            for chunk in r1.iter_content(chunk_size=512):
                f1.write(chunk)

        save_path4docx2 = '{}.docx'.format(os.path.splitext(save_path4doc2)[0])
        # 将doc转换为docx
        doc2docx(save_path4doc2, save_path4docx2)
        half_document_path = save_path4docx2
    elif str(half_document_filename).endswith(".docx"):
        r1 = requests.get(half_document_url, stream=True)
        my_timestamp2 = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
        half_document_path = os.path.join(UPLOAD_FOLDER, '{}_{}'.format(my_timestamp2, half_document_filename))
        with open(half_document_path, "wb") as f1:
            for chunk in r1.iter_content(chunk_size=512):
                f1.write(chunk)
    else:
        return "上传文件格式有误，当前仅支持doc 和 docx 格式，请选择正确文件重新上传！"

    # todo: 调整为
    half_document = Document(half_document_path)
    template_document = Document(template_path)
    output_report_path = os.path.join(UPLOAD_FOLDER,
                                      '{}_{}.docx'.format(str(datetime.datetime.now().strftime('%Y%m%d%H%M%S')),
                                                          report_name))

    report_processed_path = send_regenerate_report(half_document=half_document,
                                                   template_document=template_document,
                                                   output_report_path=output_report_path,
                                                   data_object=data_object,
                                                   report_id=report_id)


    # # todo: 在第一个报告中已经处理好，此处无需继续处理
    # document = Document(temp_send_path)
    # read_document(document, "\u00A0", "")
    # final_report_name = data["report_name"] + str(1001) + ".docx"
    # send_path = os.path.join(UPLOAD_FOLDER, final_report_name)
    # document.save(send_path)
    # "data/财务报告.docx"
    ret_upload = client.upload_by_filename(report_processed_path)
    return ret_upload["Remote file_id"]


if __name__ == '__main__':
    app.config['JSON_AS_ASCII'] = False
    app.config['JSONIFY_MIMETYPE'] = "application/json;charset=utf-8"
    app.run(host='0.0.0.0', port=4000, debug=False)
