import datetime
import hashlib
import random
import re
import time
import requests
import jwt
import yaml
from flask import jsonify, request
import os

from configs.config import CONFIG_YAML
from src.libs.log_utils import Logger

os.environ["GIT_PYTHON_REFRESH"] = "quiet"
from werkzeug.security import generate_password_hash, check_password_hash


def decode_token(token, secret='temp'):
    try:
        data = jwt.decode(token, secret, algorithms=['HS256'])
        return data
    except Exception as e:
        return False


def result_format(code: object = 200, data: object = None, **kwargs):
    if data is None:
        data = ''
    r = {
        'code': code,
        'data': data,
        **kwargs
    }
    return jsonify(r)


def create_token(infos, secret='temp'):
    """
    生成token
    """
    ip = request.remote_addr
    payload = {
        'name': infos.username,
        'ip': ip,
        'id': infos.id,
        'label': infos.label,
        'iat': datetime.datetime.now()
    }
    encoded = jwt.encode(payload, secret, algorithm='HS256')
    # token_str = str(encoded, encoding='ascii')   #是否需要转为字符串
    return infos.id, encoded


def time_to_datetime(sp):
    str_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(sp))
    datetime_time = datetime.datetime.strptime(str_time, '%Y-%m-%d %H:%M:%S')
    return datetime_time


def paginate_info(paginate, items):
    """分页信息"""
    result = {
        'total': paginate.total,
        'page': paginate.page,
        'max_page': paginate.pages,
        'results': items
    }
    return result


def result_data(items, **kwargs):
    result = {
        'data': {"count": len(items),
                 'results': items, **kwargs}
    }
    return result


def task_data(items, data):
    result = []
    for item in items:
        for dic in data:
            if item.get("cron_id") == dic.id:
                item['cron_list'] = dic.serialization()
                result.append(item)
            result.append(item)
    return result


def generate_password(word):
    password = generate_password_hash(word)

    return password


def check_password(password_hash, password) -> bool:
    """检验用户输入的原始密码
    :param raw: 用户输入的原始密码
    """
    return check_password_hash(password_hash, password)


def listToJson(data):
    datas = []
    for i in range(len(data)):
        json_data = {}
        json_data['index'] = i
        json_data['name'] = data[i]
        datas.append(json_data)
    return datas


db_total = [
    {"host": '120.78.6.232', "user": "root", "passwd": "cbb95f03a38973da"}
]


def find_loca(host):
    for db_list in db_total:
        db_local = {}
        if db_list.get('host') == host:
            db_local['host'] = db_list.get('host')
            db_local['user'] = db_list.get('user')
            db_local['passwd'] = db_list.get('passwd')
        return db_local


import json


class MyEncoder(json.JSONEncoder):

    def default(self, obj):
        """
        只要检查到了是bytes类型的数据就把它转为str类型
        :param obj:
        :return:
        #
        """
        print(type(obj))
        if isinstance(obj, bytes):
            return str(obj, encoding='utf-8')
        return json.JSONEncoder.default(self, obj)


"""
树形结构处理
"""


def treeone(tag):
    pl = []
    for i in tag:
        if i['parent_id'] == 0:
            i['children'] = treetwo(tag, i)
            pl.append(i)
    return pl


def treetwo(tag, parent):
    cl = []
    for i in tag:
        if i['parent_id'] == parent['id']:
            cl.append(i)
            i['children'] = treetwo(tag, i)
    return cl


"""
列表數據轉換
"""


def get_handle(data):
    dabs = []
    for item in data:
        dabs.append(item[0])
    return dabs


def get_lxml(data):
    committed = re.findall('.*', data)
    data = [x for x in committed if x != '']
    for i in range(len(data)):
        if '  (use' in data[i]:
            get_list(i, data)


def get_list(number, datas):
    result = datas[number + 1:]
    return result


def data_format(data):
    dats = []
    id = 0
    for item in data:
        id += 1
        item['host_id'] = id
        item.pop("password")
        item.pop("remark")
        item.pop("provider")
        dats.append(item)
    return dats


def get_server_config(data, ip):
    for item in data:
        if item.get("host") == ip:
            return item
        else:
            pass
    return ''
