from datetime import datetime
import numpy as np
from fastapi.responses import JSONResponse

import re
import os
import logging

# 获取日志记录器
logger = logging.getLogger(__name__)

from app.tools.effective_date import effective_date


# files是通过os.listdir拿到的目标文件夹里的所有文件
def get_time(files, time_type):
    try:
        logger.info("开始获取日报需分析的时间段")

        # 拿到文件夹下所有文件名
        # folder_path = r'E:\work_data\work\三工单日报\三工单\20250306\源数据'
        #
        # files = os.listdir(folder_path)

        # 获取生成日报的时间
        pattern_time = r"\d{1,2}月\d{1,2}日"
        # 另一个时间
        pattern_time2 = r"(\d{4})(\.doc|\.xls|-[^\d]|[\)）])"

        time_list = []

        for filename in files:
            print(filename)
            time_temp1 = re.search(pattern_time, filename)
            time_temp2 = re.search(pattern_time2, filename)

            if time_temp1:
                time_list.append(time_temp1.group())
            if time_temp2:
                temp_month = re.sub(r"^0", "", time_temp2.group(1)[:2])
                temp_day = re.sub(r"^0", "", time_temp2.group(1)[2:])
                time_list.append(temp_month + "月" + temp_day + "日")

        print(time_list)

        if (
            len(time_list) > 3
            and time_list[0] == time_list[1] == time_list[2] == time_list[3]
        ):
            # 把x月x日按照‘月’进行拆分
            date_list = time_list[0].split("月")

            # 获取到今天的年月日信息
            year = str(datetime.now().year)
            month = date_list[0]
            day = date_list[1].replace("日", "")

            # 调用自己写的方法获取昨天的年月日
            # 昨天
            year_before, month_before, day_before = effective_date(year, month, day)
            # 前天
            year_before2, month_before2, day_before2 = effective_date(
                str(year_before), str(month_before), str(day_before)
            )

            # 先设置时间的默认值，然后根据统计时间类型进行区分
            start_time = None
            end_time = None
            before_start_time = None

            if time_type == 0:
                # ！！！旧版，拿到生成日报的开始时间和结束时间
                # 当天17点开始时间/前一天17点结束时间
                start_time = datetime(year_before, month_before, day_before, 17, 0, 0)
                # 当天结束时间
                end_time = datetime(int(year), int(month), int(day), 17, 0, 0)
                # 前一天开始时间
                before_start_time = datetime(
                    year_before2, month_before2, day_before2, 17, 0, 0
                )

            elif time_type == 1:
                # --------------------------------20250429修改-------------------------------------------------
                # 从0点开始计算到23:59:59
                start_time = datetime(int(year), int(month), int(day), 0, 0, 0)
                # 当天结束时间
                end_time = datetime(int(year), int(month), int(day), 23, 59, 59)
                # 前一天开始时间
                before_start_time = datetime(
                    year_before, month_before, day_before, 0, 0, 0
                )
                # --------------------------------20250429修改-------------------------------------------------

            return (
                start_time,
                end_time,
                before_start_time,
                year,
                month,
                day,
                day_before,
                month_before,
            )
        else:
            raise Exception("请确认各文件是否为同一天的")

    except Exception as e:
        logger.exception(f"获取日报时间失败：{e}")
        print(f"获取日报时间失败：{e}")


# if __name__ == '__main__':
# get_time()
