# 核心工具包
import os
import random
import socket
import sys
import time

import langid
import logbook
import logbook.more
import zhconv


class BaseCore:
    # 计算耗时
    def getTimeCost(self, start, end):
        seconds = int(end - start)
        m, s = divmod(seconds, 60)
        h, m = divmod(m, 60)
        if (h > 0):
            return "%d小时%d分钟%d秒" % (h, m, s)
        elif (m > 0):
            return "%d分钟%d秒" % (m, s)
        elif (seconds > 0):
            return "%d秒" % (s)
        else:
            ms = int((end - start) * 1000)
            return "%d毫秒" % (ms)

    # 当前时间格式化
    # 1 : 2001-01-01 12:00:00 %Y-%m-%d %H:%M:%S
    # 2 : 010101120000 %y%m%d%H%M%S
    # 时间戳 3:1690179526555  精确到秒
    def getNowTime(self, type):
        now_time = ""
        if type == 1:
            now_time = time.strftime("%Y-%m-%d %H:%M:%S")
        if type == 2:
            now_time = time.strftime("%y%m%d%H%M%S")
        if type == 3:
            now_time = int(time.time() * 1000)
        return now_time

    # 日志格式
    def logFormate(self, record, handler):
        formate = "[{date}] [{level}] [{filename}] [{func_name}] [{lineno}] {msg}".format(
            date=record.time,  # 日志时间
            level=record.level_name,  # 日志等级
            filename=os.path.split(record.filename)[-1],  # 文件名
            func_name=record.func_name,  # 函数名
            lineno=record.lineno,  # 行号
            msg=record.message  # 日志内容
        )
        return formate

    # 获取logger
    def getLogger(self, fileLogFlag=True, stdOutFlag=True):
        dirname, filename = os.path.split(os.path.abspath(sys.argv[0]))
        dirname = os.path.join(dirname, "logs")
        filename = filename.replace(".py", "") + ".log"
        if not os.path.exists(dirname):
            os.mkdir(dirname)

        logbook.set_datetime_format('local')
        logger = logbook.Logger(filename)
        logger.handlers = []

        if fileLogFlag:  # 日志输出到文件
            logFile = logbook.TimedRotatingFileHandler(os.path.join(dirname, filename), date_format='%Y-%m-%d',
                                                       bubble=True, encoding='utf-8')
            logFile.formatter = self.logFormate
            logger.handlers.append(logFile)

        if stdOutFlag:  # 日志打印到屏幕
            logStd = logbook.more.ColorizedStderrHandler(bubble=True)
            logStd.formatter = self.logFormate
            logger.handlers.append(logStd)
        return logger

    # 获取随机的userAgent
    def getRandomUserAgent(self):
        return random.choice(self.__USER_AGENT_LIST)

    # 字符串截取
    def getSubStr(self, str, beginStr, endStr):
        if beginStr == '':
            pass
        else:
            begin = str.rfind(beginStr)
            if begin == -1:
                begin = 0
            str = str[begin:]
        if endStr == '':
            pass
        else:
            end = str.rfind(endStr)
            if end == -1:
                pass
            else:
                str = str[0:end + 1]
        return str

    # 繁体字转简体字
    def hant_2_hans(self, hant_str: str):
        '''
        Function: 将 hant_str 由繁体转化为简体
        '''
        return zhconv.convert(hant_str, 'zh-hans')

    # 判断字符串里是否含数字
    def str_have_num(self, str_num):
        panduan = False

        for str_1 in str_num:
            ppp = str_1.isdigit()
            if ppp:
                panduan = ppp
        return panduan

    # 获得脚本进程PID
    def getPID(self):
        PID = os.getpid()
        return PID

    # 获取本机IP
    def getIP(self):
        IP = socket.gethostbyname(socket.gethostname())
        return IP

    # 检测语言
    def detect_language(self, text):
        # 使用langid.py判断文本的语言
        result = langid.classify(text)
        if result == '':
            return 'cn'
        if result[0] == '':
            return 'cn'
        return result[0]
