#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
@AUTHOR: ASJRD018
@NAME: AnsjerFormal
@software: PyCharm
@DATE: 2019/5/18 10:45
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: SysMsg.py
@Contact: chanjunkai@163.com
"""
import time
import re

from django.views.generic.base import View

from Model.models import SysMsgModel, FeedBackModel, SysMassModel, UserExModel, UidSetModel
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService
from Service.ModelService import ModelService


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

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

    def validation(self, request_dict, operation):
        response = ResponseObject()
        token = request_dict.get('token', None)
        tko = TokenObject(token)
        if tko.code == 0:
            userID = tko.userID
            if operation == 'pushFeedBack':
                return self.do_push_msg_feed_back(userID, request_dict, response)
            elif operation == 'query':
                return self.do_query(userID, request_dict, response)
            elif operation == 'queryByAdmin':
                return self.do_query_by_admin(userID, request_dict, response)
            elif operation == 'update':
                return self.do_update(userID, request_dict, response)
            elif operation == 'delete':
                return self.do_delete(userID, request_dict, response)
            elif operation == 'deleteByAdmin':
                return self.do_delete_by_admin(userID, request_dict, response)
            elif operation == 'massPush':
                return self.do_mass_push(userID, request_dict, response)
            elif operation == 'queryMassPush':
                return self.do_query_mass_push(userID, request_dict, response)
            else:
                return response.json(414)
        else:
            return response.json(tko.code)

    def do_query_mass_push(self, userID, request_dict, response):
        own_perm = ModelService.check_perm(userID, 30)
        sender = request_dict.get('sender', None)
        page = int(request_dict.get('page', None))
        line = int(request_dict.get('line', None))
        if own_perm:
            smss_qs = SysMassModel.objects.filter()
            if sender:
                smss_qs.filter(sender__username=sender)
            count = smss_qs.count()
            smss_qs = smss_qs.values('id', 'sender__username', 'addTime', 'updTime', 'lang', 'recever', 'msg',
                                     'platform')
            smss_qs = smss_qs[(page - 1) * line:page * line]
            return response.json(0, {'count': count, 'datas': list(smss_qs)})
        else:
            return response.json(404)

    def do_mass_push(self, userID, request_dict, response):
        own_perm = ModelService.check_perm(userID, 10)
        if own_perm:
            app_str = request_dict.get('app_list', None)
            msg = request_dict.get('msg', None)
            region_str = request_dict.get('region', None)
            platform = request_dict.get('platform', None)
            app_list = app_str.split(',')
            region = region_str.split(',')
            nowTime = int(time.time())
            ue_filter = UserExModel.objects.filter()
            if app_list:
                ue_filter = ue_filter.filter(appBundleId__in=app_list)
            if region:
                ue_filter = ue_filter.filter(region__in=region)
            ue_count = ue_filter.count()
            # range_count = math.ceil(ue_count / 5000)
            SysMassModel.objects.create(
                sender_id=userID,
                lang=region_str,
                recever=app_str,
                msg=msg,
                addTime=nowTime,
                updTime=nowTime,
                platform=platform
            )
            querysetlist = []
            userID_list = ue_filter.values_list('userID_id', flat=True)
            for urd in userID_list:
                querysetlist.append(SysMsgModel(userID_id=urd, msg=msg, addTime=nowTime, updTime=nowTime))
                if len(querysetlist) > 5000:
                    is_y = SysMsgModel.objects.bulk_create(querysetlist)
                    print(is_y)
                    querysetlist = []
            SysMsgModel.objects.bulk_create(querysetlist)

            return response.json(0)
        else:
            return response.json(404)

    def do_push_msg_feed_back(self, userID, request_dict, response):
        own_perm = ModelService.check_perm(userID, 10)
        if own_perm:
            fid = request_dict.get('fid', None)
            msg = request_dict.get('msg', None)
            if all([fid, msg]):
                nowTime = int(time.time())
                fb_qs = FeedBackModel.objects.filter(id=fid)
                fb_list = fb_qs.values('userID_id')
                if fb_qs.exists():
                    create_data = {'userID_id': fb_list[0]['userID_id'], 'msg': msg, 'addTime': nowTime,
                                   'updTime': nowTime}
                    try:
                        SysMsgModel.objects.create(**create_data)
                        fb_qs.update(status=1)
                    except Exception as e:
                        return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
                    else:
                        return response.json(0, {'status': 1, 'updTime': nowTime})
                else:
                    return response.json(173)
            else:
                return response.json(444, 'fid,msg')
        else:
            return response.json(404)

    def do_query(self, userID, request_dict, response):
        page = request_dict.get('page', None)
        line = request_dict.get('line', None)
        if not all([page, line]):
            return response.json(444, 'page,line')
        page = int(page)
        line = int(line)
        sm_qs = SysMsgModel.objects.filter(userID_id=userID)
        try:
            # 如果没有系统消息,周视ios用户暂时生成消息并返回
            if not sm_qs.exists():
                user_ex_qs = UserExModel.objects.filter(userID_id=userID, appBundleId='com.ansjer.zccloud').values(
                    'region')
                if not user_ex_qs.exists():
                    return response.json(0, [])
                now_time = int(time.time())
                region = user_ex_qs[0]['region']
                if region == 'en':
                    msg = "Note: If you have upgraded iPhone system version to iOS 16 or above, there will be a situation where you cannot return to the portrait orientation after turning the live and playback page to landscape. We are sorry for the inconvenience caused. The following is the solution: you can swipe down from the top right corner of your screen to open control center, turn on the portrait orientation lock to prevent the system from automatically switching between landscape and portrait. We will solve the issue in the next version. Wish you a happy life."
                elif region == 'fr':
                    msg = "Remarque : Si vous avez mis à jour votre iPhone vers iOS 16 ou une version supérieur, il arrive que l'écran de lecture en direct ne revienne pas à l'écran vertical après être passé à l'écran horizontal.\nNous nous excusons pour le dérangement.\nLa solution est celle-ci :\nLorsque le téléphone est en mode portrait, faites glisser le coin supérieur droit de l'écran pour ouvrir le centre de contrôle et activez l'icône de verrouillage de l'écran pour empêcher le système de modifier automatiquement l'orientation de l'écran.\nSoyez assuré que nous corrigerons ce problème dans la prochaine version.\nTous mes vœux! "
                elif region == 'ru':
                    msg = "Напоминание: если вы обновите версию системы iPhone до iOS 16 или выше, вы не сможете вернуться к вертикальному экрану после переключения на горизонтальный экран интерфейса воспроизведения в реальном времени. Приносим свои извинения за неудобства. Вот решение: вы можете провести пальцем вниз в правом верхнем углу экрана, чтобы вызвать центр управления, подсветить значок блокировки портретной ориентации и запретить системе автоматическое переключение между альбомной и портретной ориентацией. Мы полностью решим эту проблему в следующей версии, желаем вам счастливой жизни!"
                elif region == 'es':
                    msg = "Nota: Si la versión de tu iPhone es iOS 16 o superior, habrá un problema cuando vuelva a la orientación vertical después de cambiar la interfaz en vivo y reproducción a horizontal.\n Disculpe mucho los inconvenientes, aquí está la solución: puede deslizar hacia abajo desde la esquina superior derecha de la pantalla para abrir el centro de control, activa el bloqueo de orientación vertical para evitar que el sistema cambie automáticamente entre horizontal y vertical. Resolveremos este problema en la próxima versión. ¡Qué tenga un buen día!"
                elif region == 'ja':
                    msg = "ご注意: iPhoneのバージョンを iOS16以上に更新すると、ライブ再生インターフェイスの横画面に切り替えた後、横画面から縦画面に切り替えができません、ご不便をおかけして申し訳ありません。 　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　次の手順にって調整ください：画面の右上隅を下にスワイプしてコントロールセンターに表示され、画面縦向きのロックアイコンをクリックして、ロックアイコンがオンにすればシステムが横画面と縦画面を切り替えません。次のバージョンいごにこの問題を解決しますのでご迷惑をおかけして申し訳ありません、よろしくお願いします。"
                elif region == 'de':
                    msg = "Hinweis: Wenn Sie Ihr iPhone auf iOS 16 oder höher aktualisiert haben, könnte das Problem bestehen, dass der Live-Wiedergabebildschirm nach dem Umschalten auf den horizontalen Bildschirm nicht zum vertikalen Bildschirm zurückkehrt.\nWir entschuldigen uns für die Unannehmlichkeiten.\nDie Lösung ist folgende:\nWenn das Telefon im Hochformat ist, schieben Sie bitte die obere rechte Ecke des Bildschirms nach unten, um das Kontrollzentrum aufzurufen, und aktivieren Sie das Symbol für die Bildschirmsperre, um zu verhindern, dass das System automatisch die Bildschirmausrichtung ändert.\nBitte seien Sie versichert, dass wir dieses Problem in der nächsten Version lösen werden.\nAlles gute!"
                elif region == 'cn':
                    msg = "温馨提示：若您将iPhone系统版本升级为iOS 16及以上，会出现切换直播回放界面横屏后无法回到竖屏。我们很抱歉，给您带来不便。以下是解决方案：您可以在屏幕右上角下滑，调出控制中心，点亮竖屏锁定图标，禁止系统自动切换横竖屏。我们将在下一个版本彻底解决这个问题，祝您生活愉快！"
                else:
                    msg = "Note: If you have upgraded iPhone system version to iOS 16 or above, there will be a situation where you cannot return to the portrait orientation after turning the live and playback page to landscape. We are sorry for the inconvenience caused. The following is the solution: you can swipe down from the top right corner of your screen to open control center, turn on the portrait orientation lock to prevent the system from automatically switching between landscape and portrait. We will solve the issue in the next version. Wish you a happy life."

                SysMsgModel.objects.create(userID_id=userID, msg=msg, addTime=now_time, updTime=now_time)
                sys_msg_qs = SysMsgModel.objects.filter(userID_id=userID).values()
                return response.json(0, {'data': CommonService.qs_to_list(sys_msg_qs), 'count': 1})

            count = sm_qs.count()
            sm_qs = sm_qs[(page - 1) * line:page * line]. \
                values('status', 'id', 'msg', 'addTime', 'updTime', 'uid', 'eventType')
            data_res = []
            uid_list = []

            for sm_q in sm_qs:
                sm_q['jumpLink'] = ''
                if sm_q['eventType'] > 0:
                    uid_list.append(sm_q['uid'])
                if sm_q['eventType'] == 2:
                    msg = sm_q['msg']
                    number_list = re.findall('\d+', msg)
                    for number in number_list:
                        if len(number) == 6:
                            sm_q['code'] = number
                data_res.append(sm_q)
            if uid_list:
                uid_set_qs = UidSetModel.objects.filter(uid__in=uid_list).values('uid', 'nickname')
                data_res = []
                for sm_q in sm_qs:
                    for uid_set_q in uid_set_qs:
                        if uid_set_q['uid'] == sm_q['uid']:
                            sm_q['devNickName'] = uid_set_q['nickname']
                    data_res.append(sm_q)
            return response.json(0, {'data': data_res, 'count': count})
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    def do_query_by_admin(self, userID, request_dict, response):
        own_perm = ModelService.check_perm(userID, 30)
        if own_perm:
            page = request_dict.get('page', None)
            line = request_dict.get('line', None)
            username = request_dict.get('username', None)
            if page and line:
                page = int(page)
                line = int(line)
                sm_qs = SysMsgModel.objects.filter()
                if username:
                    userID_list = ModelService.get_user_list_by_username(username)
                    sm_qs = sm_qs.filter(userID_id__in=userID_list)
                count = sm_qs.count()
                sm_qs = sm_qs[(page - 1) * line:page * line]. \
                    values('status', 'id', 'msg', 'addTime', 'updTime', 'userID__username', 'userID__userEmail',
                           'userID__phone')
                for k, v in enumerate(sm_qs):

                    if sm_qs[k]['userID__username'] == '':
                        sm_qs[k]['userID__username'] = sm_qs[k]['userID__userEmail']
                    if sm_qs[k]['userID__username'] == '':
                        sm_qs[k]['userID__username'] = sm_qs[k]['userID__phone']
                    sm_qs[k].pop('userID__userEmail')
                    sm_qs[k].pop('userID__phone')
                return response.json(0, {'datas': list(sm_qs), 'count': count})
            else:
                return response.json(444, 'page,line')
        else:
            return response.json(404)

    def do_update(self, userID, request_dict, response):
        sid = request_dict.get('sid', None)
        if sid:
            sm_qs = SysMsgModel.objects.filter(userID_id=userID, id=sid)
            if sm_qs.exists():
                sm_qs.update(status=1)
                return response.json(0)
            else:
                return response.json(173)
        else:
            sm_qs = SysMsgModel.objects.filter(userID_id=userID).update(status=1)
            return response.json(0)

    def do_delete(self, userID, request_dict, response):
        sid = request_dict.get('sid', None)
        sid_list = sid.split(',')
        if sid:
            sm_qs = SysMsgModel.objects.filter(userID_id=userID, id__in=sid_list)
            if sm_qs.exists():
                sm_qs.delete()
                return response.json(0)
            else:
                return response.json(173)
        else:
            sm_qs = SysMsgModel.objects.filter(userID_id=userID)
            if sm_qs.exists():
                sm_qs.delete()
                return response.json(0)
            else:
                return response.json(173)

    def do_delete_by_admin(self, userID, request_dict, response):
        own_perm = ModelService.check_perm(userID, 10)
        if not own_perm:
            return response.json(404)
        sid = request_dict.get('sid', None)
        if sid:
            sm_qs = SysMsgModel.objects.filter(id=sid)
            if sm_qs.exists():
                sm_qs.delete()
                return response.json(0)
            else:
                return response.json(173)
        else:
            return response.json(444, 'sid')
# 回复记录
