import time
import datetime
import re




# 开头部分：\033[显示方式;前景色;背景色m + 结尾部分：\033[0m
# 输出红色字
def op_red(content):
    print("\033[0;31;40mcontent\033[0m")

# 输出绿色字
def op_green(content):
    print("\033[0;32;40mcontent\033[0m")

# 初始化sqllite输出以对象 (key/value)
def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

# 去掉html相关标签
def filter_tags(htmlstr):
    dr = re.compile(r'<[^>]+>', re.S)
    dd = dr.sub('', htmlstr)
    return dd.strip()


# 判断是否开市时间内
def is_open(time):
    # 返回周几
    week = int(custom_time(time, 5))
    # 过滤 周六日
    if week == 6 or week == 0:
        return 0

    # 范围时间
    start = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '9:15', '%Y-%m-%d%H:%M')
    end = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '15:30', '%Y-%m-%d%H:%M')

    _start = unix_time(start)
    _end = unix_time(end)

    # 时间范围内
    if time > _start and time < _end:
        # if time in range(int(_start), int(_end)):
        return 1
    return 0


# 断点调试
def pt(name, is_die=1):
    print(name)
    if is_die == 1:
        exit()


# 补齐 - 根据长度,不足使用空格补齐
# string name 股票名称
# int   default_len 设置符合长度,参与补齐
# int   max_leng jb 最大标题长度
def fill(name, max_leng):
    name = str(name)
    length = len(name)
    utf8_length = len(name.encode('utf-8'))
    len_name = int((utf8_length - length) / 2 + length)

    if len_name < max_leng:
        fill_num = max_leng - len_name
        return name + ' ' * fill_num
    return name


# 时间戳 -> 日期
def custom_time(timestamp, type=1):
    # 转换成localtime
    time_local = time.localtime(timestamp)
    # 转换成新的时间格式(2016-05-05 20:28:54)
    if type == 1:
        value = "%H:%M:%S"
    elif type == 2:
        value = "%m-%d %H:%M:%S"
    elif type == 3:
        value = "%Y-%m-%d 00:00:00"
    elif type == 4:
        value = "%Y-%m-%d 23:59:59"
    elif type == 5:
        # 星期（0-6），星期天为星期的开始  返回 周几
        value = "%w"
    elif type == 6:
        value = "%Y-%m-%d %H:%M:%S"

    dt = time.strftime(value, time_local)
    return dt


# 日期 -> 时间戳
def unix_time(dt, type=1):
    dt = str(dt)
    # 转换成时间数组
    if type == 1:
        timeArray = time.strptime(dt, "%Y-%m-%d %H:%M:%S")
    elif type == 2:
        timeArray = time.strptime(dt, "%Y%m%d")

    # 转换成时间戳
    timestamp = int(time.mktime(timeArray))
    return timestamp


# 获取当前时间
def get_time():
    return int(time.time())


# 获取指定日期的 00:00:00
def get_start_date(dt):
    # 转换成时间数组
    timeArray = custom_time(dt, 3)
    res = unix_time(timeArray)
    return res


# 获取指定日期 23:59:59
def get_end_date(dt):
    # 转换成时间数组
    timeArray = custom_time(dt, 4)
    res = unix_time(timeArray)
    return res


#
# 对一维数组进行统计及排序
# array lists 一维数组  如  ['ST股', '公告', '公告', 'ST股', 'ST股', 'VR&AR', 'ST股', '5G', '其他', '公告', '公告', '次新股', 'ST股', '次新股', '知识产权', '数字货币', '二胎', '智能制造', 'ST股', '油服']
# 输出
# 1 ST股:6
# 2 公告:4
# 3 次新股:2
# ...
def get_array_count(lists):
    # 统计元素出现次数，元素为key，次数为value，生成字典
    a = {}
    for i in lists:
        if i in a:
            a[i] = a[i] + 1
        else:
            a[i] = 1
    # 使用sorted对字典进行排序
    b = sorted(a.items(), key=lambda item: item[1], reverse=True)
    return b
