#!/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

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.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, 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 page and line:
            page = int(page)
            line = int(line)
            sm_qs = SysMsgModel.objects.filter(userID_id=userID)
            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:
                if sm_q['eventType'] > 0:
                    uid_list.append(sm_q['uid'])
                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)
            if sm_qs.exists():
                return response.json(0, {'data': data_res, 'count': count})
            else:
                return response.json(0, [])
        else:
            return response.json(444, 'page,line')

    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')
# 回复记录
