# -*- coding: utf-8 -*-
# @Time : 2023/3/27 11:50
# @Author : bruxellse_li
# @File : TextRewriting.py
# @Project : 从word中提取指定表格
from datetime import datetime
from wsgiref.handlers import format_date_time
from time import mktime
import hashlib
import base64
import hmac
from urllib.parse import urlencode
import json
import requests
import ast

'''
1、文本改写 Web API 调用示例
2、运行前：请先填写Appid、APIKey、APISecret 相关信息
'''


class AssembleHeaderException(Exception):
    def __init__(self, msg):
        self.message = msg


class Url:
    def __init__(this, host, path, schema):
        this.host = host
        this.path = path
        this.schema = schema
        pass


class work_wsParam(object):
    def __init__(self, APPID, APIKey, APISecret, level, url):
        self.APPID = APPID
        self.APIKey = APIKey
        self.APISecret = APISecret
        # self.url = 'https://api.xf-yun.com/v1/private/se3acbe7f'
        self.url = url
        self.level = level

    def parse_url(self, requset_url):
        stidx = requset_url.index("://")
        host = requset_url[stidx + 3:]
        schema = requset_url[:stidx + 3]
        edidx = host.index("/")
        if edidx <= 0:
            raise AssembleHeaderException("invalid request url:" + requset_url)
        path = host[edidx:]
        host = host[:edidx]
        u = Url(host, path, schema)
        return u

    def init_header(self):
        headers = {
            'content-type': "application/json",
            'host': 'api.xf-yun.com'
        }
        return headers

    def get_body(self, text):
        data = {
            "header": {
                "app_id": self.APPID,
                "status": 3,
            },
            "parameter": {
                "se3acbe7f": {
                    "level": self.level,
                    "result": {
                        "encoding": "utf8",
                        "compress": "raw",
                        "format": "json"
                    }
                }
            },
            "payload": {
                "input1": {
                    "encoding": "utf8",
                    "compress": "raw",
                    "format": "plain",
                    "status": 3,
                    "text": str(base64.b64encode(text.encode('utf-8')), 'utf-8')
                }
            }
        }
        body = json.dumps(data)
        return body


def assemble_ws_auth_url(wsParam, requset_url, method="POST", api_key="", api_secret=""):
    u = wsParam.parse_url(requset_url)
    # u = parse_url(requset_url)
    host = u.host
    path = u.path
    now = datetime.now()
    date = format_date_time(mktime(now.timetuple()))
    # print(date)
    # date = "Thu, 12 Dec 2019 01:57:27 GMT"
    signature_origin = "host: {}\ndate: {}\n{} {} HTTP/1.1".format(host, date, method, path)
    # print("----2", signature_origin)
    signature_sha = hmac.new(api_secret.encode('utf-8'), signature_origin.encode('utf-8'),
                             digestmod=hashlib.sha256).digest()
    signature_sha = base64.b64encode(signature_sha).decode(encoding='utf-8')
    authorization_origin = "api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"" % (
        api_key, "hmac-sha256", "host date request-line", signature_sha)
    # print("----1:", authorization_origin)
    authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
    # print(authorization_origin)
    values = {
        "host": host,
        "date": date,
        "authorization": authorization
    }
    return requset_url + "?" + urlencode(values)


def get_result(wsParam, text):
    request_url = assemble_ws_auth_url(wsParam, wsParam.url, "POST", wsParam.APIKey, wsParam.APISecret)
    # request_url = assemble_ws_auth_url(url, "POST", APIKey, APISecret)
    # print("request_url:", request_url)
    response = requests.post(request_url, data=wsParam.get_body(text), headers=wsParam.init_header())
    # print("response:", response)
    str_result = response.content.decode('utf8')
    json_result = json.loads(str_result)
    # print("response-content:", json_result)
    if json_result. __contains__('header') and json_result['header']['code'] == 0:
        renew_text = json_result['payload']['result']['text']
        # print("\n改写结果：", str(base64.b64decode(renew_text), 'utf-8'))
        result_text = str(base64.b64decode(renew_text), 'utf-8')
        trans_result = ast.literal_eval(result_text)
        str_result = trans_result[0][0]
    else:
        str_result = "改写失败！请检查服务是否断开"
        # 改写结果保存到文件
        # result_file = open(".\改写结果.txt",'w',encoding='utf-8')
        # result_file.write(str(base64.b64decode(renew_text), 'utf-8'))
    return str_result


def get_list_result(text):
    APPID = "51718e1a"
    APISecret = "ZTAwYjcyZTRlZTQ3M2FmY2RlMDZiYjEx"
    APIKey = "ec11462dcbb1d8d5d8ec15612f7243e7"
    url = 'https://api.xf-yun.com/v1/private/se3acbe7f'
    # level = "<L3>"      # 改写等级 <L1>  ~  <L6>  等级越高，改写程度越深
    level_list = ["<L2>", "<L3>", "<L4>"]
    result_one = []
    for level in level_list:
        wsParam = work_wsParam(APPID, APIKey, APISecret, level, url)
        text_one = get_result(wsParam, text)
        result_one.append(text_one)
    return result_one


if __name__ == "__main__":
    text = "2021年，本单位资产实行分类管理，建立健全了资产内部管理制度；单位加强对实物资产和无形资产的管理，" \
           "明确相关部门和岗位的职责权限，强化对配置、使用和处置等关键环节的管控；明确资产使用和保管责任人，落实资产使用人在资产管理中的责任。"
    print(get_list_result(text))
#     # APPID = "51718e1a"
#     # APISecret = "ZTAwYjcyZTRlZTQ3M2FmY2RlMDZiYjEx"
#     # APIKey = "ec11462dcbb1d8d5d8ec15612f7243e7"
#     # url = 'https://api.xf-yun.com/v1/private/se3acbe7f'
#     # level = "<L3>" #改写等级 <L1>  ~  <L6>  等级越高，改写程度越深
    # text = "随着我国城市化脚步的不断加快，园林工程建设的数量也在不断上升，城市对于园林工程的质量要求也随之上升，然而就当前我国园" \
    #        "林工程管理的实践而言，就园林工程质量管理这一环节还存在许多不足之处，本文在探讨园林工程质量内涵的基础上，深入进行质量" \
    #        "管理策略探讨，目的是保障我国园林工程施工质量和提升整体发展效率。"
#
#     get_result(text)
    # wsParam = work_wsParam(APPID, APIKey, APISecret, level, url)
    # request_url = assemble_ws_auth_url(wsParam.url, "POST", wsParam.APIKey, wsParam.APISecret)
    # print(get_result(text, request_url))
