# -*- encoding: utf-8 -*-
"""
@File    : BabyController.py
@Time    : 2024-10-7 14:37:30
@Author  : peng
@Email   :
@Software: PyCharm
"""

import time

from django.db import transaction
from django.views import View
from Ansjer.cn_config.config_formal import SECRET_ACCESS_KEY, ACCESS_KEY_ID, REGION_NAME
from Model.models import Device_Info

from Object.AWS.AmazonS3Util import AmazonS3Util
from Roomumy.models import BabyUser, BabyGrowthStandard, DevelopmentalPoints
from Service.CommonService import CommonService
from Ansjer.config import LOGGER


class BabyView(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 == 'addOrEdit':  # 添加修改宝宝信息
            return self.add_or_edit_baby(request, request_dict, user_id, response)
        elif operation == 'query':  # 获取宝宝信息
            return self.query_baby_info(request_dict, user_id, response)
        elif operation == 'delete':  # 删除宝宝信息
            return self.delete_baby(request_dict, user_id, response)
        elif operation == 'getDevelopmentalPoints':  # 获取发育要点
            return self.get_developmental_points(request_dict, response)
        else:
            return response.json(414)

    @classmethod
    def add_or_edit_baby(cls, request, request_dict, user_id, response):
        """
        添加或修改宝宝信息
        @param request_dict: 请求参数
        @param request: 请求
        @param user_id: 用户id
        @request_dict serial_no: 设备序列号
        @request_dict baby_id: 宝宝id
        @request_dict nick_name: 昵称
        @request_dict sex: 性别
        @request_dict birthday: 生日
        @request_dict icon: 头像
        @request_dict is_default: 是否默认
        @param response: 响应对象
        @return: response
        """
        serial_no = request_dict.get('serial_no', '')
        baby_id = request_dict.get('baby_id', None)
        nick_name = request_dict.get('nick_name', None)
        sex = request_dict.get('sex', None)
        birthday = request_dict.get('birthday', None)
        icon = request.FILES.get('icon', None)
        is_default = request_dict.get('is_default', 0)
        if not all([nick_name, sex, birthday]):
            return response.json(404)
        now_time = int(time.time())
        bucket = "ansjerfilemanager"
        s3_url = 'https://{}.s3.{}.amazonaws.com.cn/'.format(bucket, REGION_NAME)
        LOGGER.info(f"添加或修改宝宝信息打印参数{request_dict}, user_id:{user_id}，icon:{icon}")
        try:
            with transaction.atomic():
                device_id = ""
                if serial_no:
                    device_info_qs = Device_Info.objects.filter(userID=user_id, serial_number=serial_no)
                    if not device_info_qs.exists():
                        return response.json(14)
                    device_id = CommonService.query_uid_with_serial(serial_no)
                if baby_id:
                    BabyUser.objects.filter(id=baby_id, user_id=user_id).update(is_default=is_default,
                                                                                birthday=birthday,
                                                                                nick_name=nick_name, sex=sex,
                                                                                device_id=device_id,
                                                                                serial_no=serial_no,
                                                                                updated_time=now_time)
                else:
                    if sex == '1':
                        icon_url = s3_url + 'Roomumy/boy.jpg'
                    else:
                        icon_url = s3_url + 'Roomumy/girl.jpg'
                    baby_qs = BabyUser.objects.create(user_id=user_id, is_default=is_default, birthday=birthday,
                                                      nick_name=nick_name, sex=sex, device_id=device_id, serial_no=serial_no,
                                                      created_time=now_time, updated_time=now_time, icon_url=icon_url)
                    baby_id = baby_qs.id
                if icon:
                    s3_obj = AmazonS3Util(ACCESS_KEY_ID, SECRET_ACCESS_KEY, REGION_NAME)
                    icon_path = 'Roomumy/icon_{}.jpg'.format(baby_id)
                    s3_obj.upload_file_obj(
                        bucket,
                        icon_path,
                        icon,
                        {"ContentType": icon.content_type, "ACL": "public-read"},
                    )
                    icon_url = s3_url + icon_path
                    BabyUser.objects.filter(id=baby_id, user_id=user_id).update(icon_url=icon_url)
                if is_default == '1':
                    BabyUser.objects.filter(user_id=user_id).exclude(id=baby_id).update(is_default=False)
            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 query_baby_info(cls, request_dict, user_id, response):
        """
        获取宝宝信息
        """
        baby_id = request_dict.get('baby_id', None)

        try:
            baby_qs = BabyUser.objects.filter(user_id=user_id)
            if baby_id:
                baby_qs = baby_qs.filter(id=baby_id)
            count = baby_qs.count()
            baby_list = list(
                baby_qs.values('id', 'nick_name', 'sex', 'birthday', 'icon_url', 'device_id', 'is_default', 'serial_no'))

            current_time = int(time.time())  # 获取当前时间戳

            for baby in baby_list:
                birthday = baby.get('birthday', 0)
                baby['growth_standard'] = None  # 初始化字段

                # 仅处理有效生日数据
                if birthday > 0:
                    age_days = (current_time - birthday) // 86400  # 计算年龄天数

                    # 查询成长标准数据
                    standards = BabyGrowthStandard.objects.filter(
                        age_min__lte=age_days,
                        age_max__gte=age_days,
                        gender=baby.get('sex', 0)  # 默认性别为女
                    ).first()  # 直接获取第一条匹配记录

                    if standards:
                        baby['growth_standard'] = {
                            'height': {'min': standards.height_min, 'max': standards.height_max},
                            'weight': {'min': standards.weight_min, 'max': standards.weight_max},
                            'head_circumference': {
                                'min': standards.head_circumference_min,
                                'max': standards.head_circumference_max
                            }
                        }
                    else:
                        baby['growth_standard'] = {
                            'height': {'min': None, 'max': None},
                            'weight': {'min': None, 'max': None},
                            'head_circumference': {'min': None, 'max': None}
                        }
            return response.json(0, {'total': count, 'baby_list': baby_list})
        except Exception as e:
            return response.json(500, f'error_line:{e.__traceback__.tb_lineno}, error_msg:{repr(e)}')

    @classmethod
    def delete_baby(cls, request_dict, user_id, response):
        """
        删除宝宝信息
        @param request_dict: 请求参数
        @param user_id: 用户id
        @request_dict baby_id: 宝宝id
        @param response: 响应对象
        @return: response
        """
        baby_id = request_dict.get('baby_id', None)

        try:
            BabyUser.objects.filter(user_id=user_id, 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)))

    @staticmethod
    def get_developmental_points(request_dict, response):
        """
        获取喂养要点
        @param request_dict: 请求参数
        @request_dict month: 月份信息
        @param response: 响应对象
        @return: response
        """
        month = request_dict.get('month', None)

        try:
            if not month:
                return response.json(444)
            developmental_points_qs = DevelopmentalPoints.objects.filter(month=month).values()
            if not developmental_points_qs.exists():
                return response.json(173)
            title = developmental_points_qs[0]['title']
            weight = developmental_points_qs[0]['weight']
            height = developmental_points_qs[0]['height']
            head_circumference = developmental_points_qs[0]['head_circumference']
            content = developmental_points_qs[0]['content']

            res = {
                'title': title,
                'weight': weight,
                'height': height,
                'head_circumference': head_circumference,
                'content': content
            }
            return response.json(0, res)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
