# -*- encoding: utf-8 -*-
"""
@File    : CronCloudPhotoController.py
@Time    : 2022/11/3 10:16
@Author  : stephen
@Email   : zhangdongming@asj6.wecom.work
@Software: PyCharm
"""
import logging
import time

from django.db import transaction
from django.views import View

from Ansjer.cn_config.config_test import PUSH_CLOUD_PHOTO
from Ansjer.config import ACCESS_KEY_ID, SECRET_ACCESS_KEY, REGION_NAME
from Model.models import DeviceCloudPhotoInfo, Device_Info, CloudPhotoBGM, DevicePicturePushInfo
from Object.AWS.AmazonS3Util import AmazonS3Util
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Object.utils import LocalDateTimeUtil

LOGGER = logging.getLogger('info')


class CronCloudPhotoView(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 = TokenObject(request.META.get('HTTP_AUTHORIZATION'))
        lang = request_dict.get('lang', token.lang)
        response = ResponseObject(lang)
        if token.code != 0:
            return response.json(token.code)
        user_id = token.userID
        if operation == 'save-photo':
            return self.save_cloud_photo(user_id, request_dict, response)
        elif operation == 'bgm-list':
            return self.get_bgm_list(response)
        elif operation == 'video-list':
            return self.query_cloud_photo_page(user_id, request_dict, response)
        elif operation == 'video-del':
            return self.del_cloud_photo(request_dict, response)
        else:
            return response.json(404)

    @classmethod
    def save_cloud_photo(cls, user_id, request_dict, response):
        """
        保存云相册
        """
        try:
            with transaction.atomic():
                status = request_dict.get('status', None)
                uid = request_dict.get('uid', None)
                if not all([status, user_id]):
                    return response(444)
                status = int(status)
                device_info_qs = Device_Info.objects.filter(userID_id=user_id)
                if uid:
                    device_info_qs = device_info_qs.filter(UID=uid)
                device_info_qs = device_info_qs.values('vodPrimaryUserID', 'UID')
                if not device_info_qs.exists():
                    return response.json(14)
                for item in device_info_qs:
                    master_user_id = item['vodPrimaryUserID']
                    uid = item['UID']
                    if master_user_id == '' or master_user_id != user_id:
                        continue
                    now_time = int(time.time())
                    cloud_photo_qs = DeviceCloudPhotoInfo.objects.filter(uid=uid)
                    if not cloud_photo_qs.exists():
                        data = {'status': status, 'user_id': user_id, 'uid': uid, 'created_time': now_time,
                                'updated_time': now_time}
                        DeviceCloudPhotoInfo.objects.create(**data)
                        continue
                    cloud_photo_qs.update(status=status, updated_time=now_time)
                return response.json(0)
        except Exception as e:
            LOGGER.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
            return response.json(500)

    @classmethod
    def get_bgm_list(cls, response):
        """
        获取背景音乐列表
        """
        photo_bgm = CloudPhotoBGM.objects.filter(is_show=1).values('name', 'link').order_by('sort')
        if not photo_bgm.exists():
            return response.json(0, [])
        return response.json(0, list(photo_bgm))

    @classmethod
    def query_cloud_photo_page(cls, user_id, request_dict, response):
        """
        分页查询云相册视频
        @param user_id: 用户id
        @param request_dict: 请求参数
        @param response: 响应对象
        @return: []
        """
        try:
            device_name = request_dict.get('deviceName', None)
            start_time = request_dict.get('startTime', None)
            end_time = request_dict.get('endTime', None)
            page = request_dict.get('page', None)
            size = request_dict.get('size', None)
            if not all([page, size]):
                return response.json(444)
            page = int(page)
            size = int(size)
            video_qs = DevicePicturePushInfo.objects.filter(user_id=user_id, type=1)
            if device_name:
                name_list = device_name.split(',')
                video_qs = video_qs.filter(device_nick_name__in=name_list)
            if start_time:
                start_time = LocalDateTimeUtil.time_stamp_to_time(int(start_time), '%Y%m')
                video_qs = video_qs.filter(event_time__gte=int(start_time))
            if end_time:
                end_time = LocalDateTimeUtil.time_stamp_to_time(int(end_time), '%Y%m')
                video_qs = video_qs.filter(event_time__lte=int(end_time))
            video_qs = video_qs.values('id', 'uid', 'device_nick_name', 'event_time', 'created_time').order_by(
                '-event_time')[(page - 1) * size:page * size]
            if not video_qs.exists():
                return response.json(0, [])
            s3 = AmazonS3Util(ACCESS_KEY_ID, SECRET_ACCESS_KEY, REGION_NAME)
            res_data = []
            now_month = LocalDateTimeUtil.get_cur_month_start()
            start_time = "{} 00:00:00".format(str(now_month))
            time_array = time.strptime(start_time, "%Y-%m-%d %H:%M:%S")
            for item in video_qs:
                picture_qs = DevicePicturePushInfo.objects \
                    .filter(uid=item['uid'], event_time__gt=int(time.mktime(time_array)), type=0).order_by('event_time')
                event_time = picture_qs.first().event_time
                channel = picture_qs.first().channel
                data = {'id': item['id'], 'deviceNickname': item['device_nick_name'],
                        'createdTime': item['created_time']}
                picture_key = '{}/{}/{}.jpeg'.format(item['uid'], channel, event_time)
                picture_url = s3.generate_file_obj_url(PUSH_CLOUD_PHOTO, picture_key)
                data['picture'] = picture_url
                key = '{}/video/{}.mp4'.format(item['uid'], str(item['event_time']))
                obj_url = s3.generate_file_obj_url(PUSH_CLOUD_PHOTO, key)
                data['videoLink'] = obj_url

                res_data.append(data)
            return response.json(0, res_data)
        except Exception as e:
            LOGGER.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
            return response.json(500)

    @classmethod
    def del_cloud_photo(cls, request_dict, response):
        """
        根据id删除视频列表
        @param request_dict:
        @param response:
        @return:
        """
        try:
            ids = request_dict.get('ids', None)
            if not ids:
                return response.json(444)
            cloud_photo_qs = DevicePicturePushInfo.objects.filter(id__in=ids.split(','))
            if not cloud_photo_qs.exists():
                return response.json(173)
            s3 = AmazonS3Util(ACCESS_KEY_ID, SECRET_ACCESS_KEY, REGION_NAME)
            for item in cloud_photo_qs:
                key = '{}/video/{}.mp4'.format(item.uid, str(item.event_time))
                s3.delete_obj(PUSH_CLOUD_PHOTO, key)
            cloud_photo_qs.delete()
            return response.json(0)
        except Exception as e:
            LOGGER.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
            return response.json(500)
