# -*- encoding: utf-8 -*-
"""
@File    : FeedDiaryController.py
@Time    : 2024-10-7 14:37:30
@Author  : peng
@Email   :
@Software: PyCharm
"""
from datetime import datetime, timedelta
import json
import time

from django.db.models import F, Q, Count
from django.views import View

from Object.ResponseObject import ResponseObject
from Roomumy.models import FeedDiary, FeedType
from Service.CommonService import CommonService


class FeedDiaryView(View):
    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation')
        return self.validation(request.GET, request, operation)

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation')
        return self.validation(request.POST, request, operation)

    def validation(self, request_dict, request, operation):
        token_code, user_id, response = CommonService.verify_token_get_user_id(request_dict, request)
        if token_code != 0:
            return response.json(token_code)
        if operation == 'query':  # 查询喂养记录
            return self.get_feed_diary_data(request_dict, response)
        elif operation == 'queryStatistics':  # 查询喂养统计
            return self.get_statistics_data(request_dict, response)
        elif operation == 'addOrEdit':  # 添加或编辑喂养日记
            return self.add_or_edit_feed_diary(request_dict, response)
        elif operation == 'delete':  # 删除喂养日记
            return self.delete_feed_diary(request_dict, response)
        elif operation == 'getFeedList':  # 查询喂养类型列表
            return self.get_feed_list(request_dict, response)
        elif operation == 'feedTypeConfig':
            return self.feed_type_config(request_dict, response)
        elif operation == 'getDailyRecordStatus':  # 查询天数记录
            return self.get_daily_record_status(request_dict, response)
        else:
            return response.json(414)

    @classmethod
    def get_feed_diary_data(cls, request_dict, response):
        """
        查询喂养记录
        @param request_dict: 请求参数
        @request_dict start_time: 开始时间戳
        @request_dict end_time: 结束时间戳
        @request_dict baby_id: 宝宝id
        @request_dict event_type: 喂养类型
        @param response: 响应对象
        @return: response
        """
        start_time = request_dict.get('start_time', None)
        end_time = request_dict.get('end_time', None)
        baby_id = request_dict.get('baby_id', None)
        feed_type = request_dict.get('feed_type', None)
        if not all([start_time, end_time, baby_id]):
            return response.json(444, {'error param': 'start_time, end_time or baby_id'})
        try:
            feed_diary = FeedDiary.objects.filter(date_time__gte=start_time, date_time__lte=end_time,
                                                  baby_id=baby_id)
            if feed_type:
                feed_diary = feed_diary.filter(feed_type=feed_type)
            feed_diary = feed_diary.values('feed_type__name', 'feed_type__icon_url', 'feed_content', 'date_time',
                                           'id', 'feed_type')
            feed_diary = list(feed_diary)

            # 统计各类型的喂养次数
            feed_statistics = {}
            for item in feed_diary:
                feed_type_id = item['feed_type']
                feed_type_name = item['feed_type__name']

                # 初始化统计项
                if feed_type_id not in feed_statistics:
                    feed_statistics[feed_type_id] = {
                        "feed_type_name": feed_type_name,
                        "frequency": 0,
                        "total": 0  # 仅对类型1/2/3有效
                    }

                # 更新统计
                feed_statistics[feed_type_id]["frequency"] += 1

                # 仅对类型1/2/3计算total
                if item['feed_type'] in [1, 2, 3] and "total" in item.get("feed_content", {}):
                    feed_statistics[feed_type_id]["total"] += item["feed_content"]["total"]

            # 转换统计结果为列表
            feed_statistics_list = [
                {
                    "feed_type": feed_type_id,
                    "feed_type_name": data["feed_type_name"],
                    "frequency": str(data["frequency"]),
                    "total": str(data["total"])
                }
                for feed_type_id, data in feed_statistics.items()
            ]

            return response.json(0, {
                'feed_diary': feed_diary,
                'feed_statistics': feed_statistics_list  # 改为列表形式，更清晰
            })
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @classmethod
    def get_statistics_data(cls, request_dict, response):
        """
        查询喂养记录
        @param request_dict: 请求参数
        @request_dict start_time: 开始时间戳
        @request_dict end_time: 结束时间戳
        @request_dict baby_id: 宝宝id
        @request_dict event_type: 喂养类型
        @request_dict sub_event_type: 喂养子类型
        @param response: 响应对象
        @return: response
        """
        start_time = request_dict.get('start_time', None)
        end_time = request_dict.get('end_time', None)
        baby_id = request_dict.get('baby_id', None)
        feed_type = request_dict.get('feed_type', None)
        sub_feed_type = request_dict.get('sub_feed_type', None)
        if not all([start_time, end_time, baby_id, feed_type]):
            return response.json(444, {'error param': 'start_time, end_time, event_type or baby_id'})
        s_time = datetime.datetime.fromtimestamp(int(start_time))
        e_time = datetime.datetime.fromtimestamp(int(end_time))
        time_list = CommonService.cutting_time(s_time, e_time, 'day')
        try:
            result_list = []
            for time_range in time_list:
                content_list = []
                feed_diary = FeedDiary.objects.filter(created_time__gte=time_range[0], created_time__lt=time_range[1],
                                                      baby_id=baby_id, feed_type_id=feed_type).values_list(
                    'feed_content', flat=True)
                count = 0
                if feed_type == '5' and sub_feed_type:  # 换尿布
                    sub_feed_type = int(sub_feed_type)
                    for item in feed_diary:
                        if item['sub_feed_type'] in [sub_feed_type, 3]:  # 1：嘘嘘 2：臭臭 3：嘘嘘+臭臭 4：干爽
                            count += 1
                            content_list.append(item)
                else:
                    count = feed_diary.count()
                    content_list = list(feed_diary)
                result_list.append({
                    'date_time': time_range[0],
                    'count': count,
                    'feed_content': content_list
                })
            return response.json(0, result_list)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @classmethod
    def add_or_edit_feed_diary(cls, request_dict, response):
        """
        添加编辑喂养记录
        @param request_dict: 请求参数
        @request_dict date_time: 喂养时间戳
        @request_dict baby_id: 宝宝id
        @request_dict feed_id: 记录id
        @request_dict event_type: 喂养类型
        @request_dict event_content: 喂养事件
        @param response: 响应对象
        @return: response
        """
        date_time = request_dict.get('date_time', None)
        baby_id = request_dict.get('baby_id', None)
        feed_id = request_dict.get('feed_id', None)
        feed_type = request_dict.get('feed_type', None)
        feed_content = request_dict.get('feed_content', None)
        if not all([date_time, baby_id, feed_type, feed_content]):
            return response.json(444, {'error param': 'date_time, feed_content, feed_type or baby_id'})
        feed_content = eval(feed_content)
        try:
            now_time = int(time.time())
            feed_type_qs = FeedType.objects.filter(id=feed_type)
            if not feed_type_qs:
                return response.json(444, {'error param': 'feed_type'})
            if feed_id:
                FeedDiary.objects.filter(id=feed_id, baby_id=baby_id).update(date_time=date_time,
                                                                             updated_time=now_time,
                                                                             feed_content=feed_content)
            else:
                FeedDiary.objects.create(baby_id=baby_id, feed_type_id=feed_type, feed_content=feed_content,
                                         date_time=date_time, created_time=now_time, updated_time=now_time)
            return response.json(0)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @classmethod
    def delete_feed_diary(cls, request_dict, response):
        """
        删除喂养记录
        @param request_dict: 请求参数
        @request_dict baby_id: 宝宝id
        @request_dict feed_id: 记录id
        @param response: 响应对象
        @return: response
        """
        baby_id = request_dict.get('baby_id', None)
        feed_id = request_dict.get('feed_id', None)
        if not all([feed_id, baby_id]):
            return response.json(444, {'error param': 'feed_id or baby_id'})
        try:
            FeedDiary.objects.filter(id=feed_id, baby_id=baby_id).delete()
            return response.json(0)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @classmethod
    def get_feed_list(cls, request_dict, response):
        """
        获取喂养列表
        @param request_dict: 请求参数
        @param response: 响应对象
        @return: response
        """
        try:
            feed_type = FeedType.objects.filter(is_show=True).values('id', 'name', 'icon_url', 'sort').order_by('sort')
            return response.json(0, list(feed_type))
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @classmethod
    def feed_type_config(cls, request_dict, response):
        """
        根据喂养类型返回文本列表
        @param request_dict: 请求参数
        @param response: 响应对象
        @return: response
        """
        try:
            feed_type = request_dict.get('feed_type_id', None)
            if feed_type == '4':#辅食
                feed_type_text = [
                    "米粉", "面条", "红薯", "山药", "南瓜",
                    "胡萝卜", "菠菜", "番茄", "土豆", "猪肉",
                    "猪肝", "鱼肉", "鸡肉", "牛肉", "虾",
                    "鸡蛋", "苹果", "香蕉", "猕猴桃", "火龙果"
                ]

            elif feed_type == '5':
                feed_type_text = ["嘘嘘", "臭臭", "嘘嘘+臭臭", "干爽"]

            elif feed_type == '10':
                feed_type_text = ["额温", "耳温", "腋温", "口温", "肛温"]

            else:
                feed_type_text = []
            return response.json(0, {"feed_type_text": feed_type_text})
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @classmethod
    def get_daily_record_status(cls, request_dict, response):
        """
        获取记录的日期
        @param request_dict: 请求参数
        @request_dict baby_id: 宝宝id
        @request_dict timestamp: 时间戳
        @param response: 响应对象
        @return: response
        """
        baby_id = request_dict.get('baby_id')
        start_time = request_dict.get('start_time')
        end_time = request_dict.get('end_time')

        if not all([baby_id, start_time, end_time]):
            return response.json(444, {'error': '缺少baby_id、start_time或end_time参数'})

        try:
            # 转换为整数
            start_time = int(start_time)
            end_time = int(end_time)

            records = FeedDiary.objects.filter(
                baby_id=baby_id,
                date_time__gte=start_time,
                date_time__lte=end_time
            ).values('date_time')
            record_dates = {
                datetime.fromtimestamp(r['date_time']).strftime('%Y-%m-%d')
                for r in records
            }
            # 生成时间段内所有日期
            all_dates = []
            current_date = datetime.fromtimestamp(start_time).date()
            end_date = datetime.fromtimestamp(end_time).date()

            while current_date <= end_date:
                all_dates.append(current_date.strftime('%Y-%m-%d'))
                current_date += timedelta(days=1)

            # 构建返回结果
            result = []
            for date in all_dates:
                result.append({
                    'date': date,
                    'has_record': date in record_dates
                })

            return response.json(0, {
                'baby_id': baby_id,
                'days': result
            })

        except ValueError as e:
            return response.json(444, {'error': '时间戳格式不正确'})
        except Exception as e:
            return response.json(500, {'error': f'服务器错误: {str(e)}'})
