#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File     : tool
# @Author   : LiuYan
# @Time     : 2021/6/21 11:22
from __future__ import unicode_literals, print_function, division

import os
import re
import json
import time
import zipfile
import datetime
import xlsxwriter


def read_json(path: str) -> list:
    f = open(path, 'r', encoding='utf-8')
    examples = []
    for line in f.readlines():
        examples.append(json.loads(line))
    f.close()
    return examples


def clean_text(text: str) -> str:
    return re.sub('\n+', '\n', text.strip().replace(' ', '').replace('\t', '').replace('\r', ''))


# 打包zip
def make_zip(file_dir: str, zip_path: str) -> None:
    zip_f = zipfile.ZipFile(zip_path, 'w')
    pre_len = len(os.path.dirname(file_dir))
    for parent, dir_names, filenames in os.walk(file_dir):
        for filename in filenames:
            path_file = os.path.join(parent, filename)
            arc_name = path_file[pre_len:].strip(os.path.sep)
            zip_f.write(path_file, arc_name)
    zip_f.close()


# 删除zip
def delete_zip(zip_path: str) -> None:
    os.remove(zip_path)


def timeit(f):
    def timed(*args, **kw):
        ts = time.time()
        print('......begin     {0:8s}......'.format(f.__name__))
        result = f(*args, **kw)
        te = time.time()
        print('......finish    {0:8s}, took:{1:.4f} sec......'.format(f.__name__, te - ts))
        return result

    return timed


def list2xlsx(result_list: list, xlsx_path: str):
    """

    :param result_list: [
                            {
                                'id': 1,
                                'title': 't',
                                ...
                            }
                            ...
                        ]
    :param xlsx_path: '/home/zzsn/liuyan/result/result.xlsx'
    :return:
    """
    workbook = xlsxwriter.Workbook(xlsx_path)
    worksheet = workbook.add_worksheet('sheet1')
    worksheet.write_row(row=0, col=0, data=list(result_list[0].keys()))

    for row_index, result_dict in enumerate(result_list):
        worksheet.write_row(row=row_index + 1, col=0, data=list(
            ';'.join(result) if type(result) in [list, set] else result for result in result_dict.values()
        ))

    workbook.close()


def return_json(handle_msg: str, is_handle_success: bool, logs: str or None, result_data: object) -> dict or json:
    """

    :param handle_msg: str 处理信息：是否成功 'success' / 'failure'
    :param is_handle_success: bool 是否处理成功
    :param logs: str or None 处理过程以及结果信息
    :param result_data: object 处理结果 数据
    :return:
    """
    dict_result = {
        'handleMsg': handle_msg,
        'isHandleSuccess': is_handle_success,
        'logs': logs,
        'resultData': result_data
    }
    return dict_result
    # return json.dumps(dict_result, ensure_ascii=False)


def return_json_(handle_msg: str, is_handle_success: bool, logs: str or None, result_data: object) -> dict or json:
    """

    :param handle_msg: str 处理信息：是否成功 'success' / 'failure'
    :param is_handle_success: bool 是否处理成功
    :param logs: str or None 处理过程以及结果信息
    :param result_data: object 处理结果 数据
    :return:
    """
    dict_result = {
        'handleMsg': handle_msg,
        'ynHandleSuccess': is_handle_success,
        'logs': logs,
        'resultData': result_data
    }

    return json.dumps(dict_result, ensure_ascii=False)


def return_json_str(handle_msg: str, is_handle_success: bool, logs: str or None, result_data: object) -> dict or json:
    """

    :param handle_msg: str 处理信息：是否成功 'success' / 'failure'
    :param is_handle_success: bool 是否处理成功
    :param logs: str or None 处理过程以及结果信息
    :param result_data: object 处理结果 数据
    :return:
    """
    dict_result = {
        'handleMsg': handle_msg,
        'isHandleSuccess': is_handle_success,
        'logs': logs,
        'resultData': result_data
    }

    return json.dumps(dict_result, ensure_ascii=False)


def class_to_dict(obj):
    is_list = obj.__class__ == [].__class__
    is_set = obj.__class__ == set().__class__
    if is_list or is_set:
        obj_arr = []
        for o in obj:
            dict = {}
            a = o.__dict__
            if "_sa_instance_state" in a:
                del a['_sa_instance_state']
            dict.update(a)
            obj_arr.append(dict)
        return obj_arr
    else:
        dict = {}
        a = obj.__dict__
        if "_sa_instance_state" in a:
            del a['_sa_instance_state']
        dict.update(a)
        return dict


def class_to_dict_field(obj):
    """
    字段集合转化字典 如 db.session.query(User.created_time).all()
    :param obj:
    :return:
    """
    is_list = obj.__class__ == [].__class__
    is_set = obj.__class__ == set().__class__
    if is_list or is_set:
        obj_arr = []
        for o in obj:
            for v in dir(o):
                if isinstance(o.__getattribute__(v), datetime.datetime) and not v.startswith("__"):
                    dict = {str(v): o.__getattribute__(v).strftime('%Y-%m-%d %H:%M:%S')}
                    obj_arr.append(dict)
        return obj_arr


def class_to_dict_all(obj):
    """
    例如 GlobalRegion.query.all()
    :param obj:
    :return:
    """
    is_list = obj.__class__ == [].__class__
    is_set = obj.__class__ == set().__class__
    if is_list or is_set:
        obj_arr = []
        for o in obj:
            for k, v in vars(o).items():
                if isinstance(v, datetime.datetime):
                    o.__dict__[k] = v.strftime('%Y-%m-%d %H:%M:%S')
            dict = {}
            a = o.__dict__
            if '_sa_instance_state' in a:
                del a['_sa_instance_state']
            dict.update(a)
            obj_arr.append(dict)
        return obj_arr
    else:
        dict = {}
        for k, v in vars(obj).items():
            if isinstance(v, datetime.datetime):
                obj.__dict__[k] = v.strftime('%Y-%m-%d %H:%M:%S')
        a = obj.__dict__
        if '_sa_instance_state' in a:
            del a['_sa_instance_state']
        dict.update(a)
        return dict


def formatGMTime(timestamp):
    """
    格式化 GMT 时间
    :param timestamp:
    :return:
    """
    GMT_FORMAT = '%a, %d %b %Y %H:%M:%S GMT'
    return datetime.datetime.strptime(timestamp, GMT_FORMAT) + datetime.timedelta(hours=8)
