#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
@AUTHOR: ASJRD019
@NAME: AnsjerFormal
@software: PyCharm
@DATE: 2019/5/27 15:50
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: AliPayObject.py
@Contact: pzb3076@163.com
"""
import time
import traceback

from django.db.models import Count

from Object.RedisObject import RedisObject
import simplejson as json
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.base import View

from Model.models import UidSetModel, Device_User, Device_Info, UidPushModel, Equipment_Info, UID_Preview, UID_Bucket, \
    VodHlsModel, Order_Model, OssCrdModel, UidUserModel, UidChannelSetModel, User_Brand, ExperienceContextModel, \
    StsCrdModel, Unused_Uid_Meal, UIDMainUser
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService
from Service.ModelService import ModelService
from django.db import transaction

'''
# 管理员获取信息
http://192.168.136.39:8000/uidset/adminQuery?token=local&page=1&line=10
  管理员删除信息
http://192.168.136.39:8000/uidset/adminDelete?token=local&id=2
  管理员添加信息
http://192.168.136.39:8000/uidset/adminAdd?token=local&uid=JW3684H8BSHG9TTM111A
  管理员编辑信息
http://192.168.136.39:8000/uidset/adminUpdate?token=local&id=6&content={"uid":"9999"}
'''


# 设备信息添加
class UidSetView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(UidSetView, self).dispatch(*args, **kwargs)

    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):
        response = ResponseObject()
        if operation is None:
            return response.json(444, 'error path')
        token = request_dict.get('token', None)
        # 设备主键uid
        tko = TokenObject(token)
        response.lang = tko.lang
        if tko.code != 0:
            return response.json(tko.code)
        userID = tko.userID
        if operation == 'queryAll':
            return self.do_queryAll(request_dict, userID, response)
        elif operation == 'adminQueryAll':
            return self.do_admin_queryAll(request_dict, userID, response)
        elif operation == 'adminDelete':
            return self.do_admin_delete(request_dict, userID, response)
        elif operation == 'adminQuery':
            return self.do_admin_query(request_dict, userID, response)
        elif operation == 'adminAdd':
            return self.do_admin_add(request_dict, userID, response)
        elif operation == 'adminUpdate':
            return self.do_admin_update(request_dict, userID, response)
        elif operation == 'update':
            return self.do_update(request_dict, response)
        elif operation == 'updateSet':
            return self.do_update_set(request, request_dict, response)
        elif operation == 'updateChannel':
            return self.do_update_channel_set(request_dict, response)
        elif operation == 'setVoicePrompt':
            return self.do_set_voice(userID, request_dict, response)
        elif operation == 'vod_reset':
            return self.vod_reset(request_dict, response)
        # elif operation == 'test':
        #     return self.do_test(response)
        else:
            return response.json(444, 'error path')

    def do_queryAll(self, request_dict, userID, response):
        uid_list = Device_Info.objects.filter(userID_id=userID).values_list('UID', flat=True)
        uid_set_qs = UidSetModel.objects.filter(uid__in=uid_list).values('uid', 'detect_status', 'detect_interval',
                                                                         'version', 'ucode', 'p2p_region', 'tz',
                                                                         'video_code', 'channel', 'cloud_vod')
        
        if uid_set_qs.exists():
            return response.json(0, list(uid_set_qs))
        else:
            return response.json(0)

    def do_admin_queryAll(self, request_dict, userID, response):
        uid = request_dict.get('uid', None)
        user_search = UidPushModel.objects.filter(uid_set__uid=uid).values(
            'userID__username', 'userID__userEmail', 'userID__phone', 'userID__is_active',
            'userID__NickName', 'uid_set__video_code', 'uid_set__version', 'uid_set__ucode',
            'uid_set__tz', 'uid_set__p2p_region', 'uid_set__nickname', 'uid_set__detect_status',
            'uid_set__detect_interval', 'uid_set__cloud_vod', 'uid_set__channel', 'updTime',
            'tz', 'token_val', 'push_type', 'm_code',
            'lang', 'app_type', 'uid_set__uid', 'userID__data_joined', 'appBundleId'
        )
        qs_list = CommonService.qs_to_list(user_search)
        return response.json(0, qs_list)

    # 管理员删除
    def do_admin_delete(self, request_dict, userID, response):
        own_perm = ModelService.check_perm(userID, 10)
        if own_perm is True:
            uid = request_dict.getlist('uid', None)
            id_list = request_dict.get('id_list', None)
            # redisObj = RedisObject(db=8)
            # redisObj.del_data(key='uid_qs_' + userID)
            # 删除回滚
            with transaction.atomic():  # 上下文格式，可以在python代码的任何位置使用
                val = 1
                if 'UidSetModel' in id_list:
                    del_uid = UidSetModel.objects.filter(uid__in=uid)
                    if del_uid.exists():
                        del_uid.delete()
                        print ('删除UidSetModel')
                    else:
                        val = 1
                        print('UidSetModel表没有数据')
                if 'Equipment_Info' in id_list:
                    del_uid = Equipment_Info.objects.filter(devUid__in=uid)
                    if del_uid.exists():
                        del_uid.delete()
                        # print('删除Equipment_Info')
                    else:
                        val = val+1
                        print('Equipment_Info表没有数据')
                if 'UID_Preview' in id_list:
                    del_uid = UID_Preview.objects.filter(uid__in=uid)
                    if del_uid.exists():
                        del_uid.delete()
                        # print ('删除UID_Preview')
                    else:
                        val = val + 1
                        print('UID_Preview表没有数据')
                if 'UID_Bucket' in id_list:
                    del_uid = UID_Bucket.objects.filter(uid__in=uid)
                    if del_uid.exists():
                        del_uid.delete()
                        # print ('删除UID_Bucket')
                    else:
                        val = val + 1
                        print('UID_Bucket表没有数据')
                if 'VodHlsModel' in id_list:
                    del_uid = VodHlsModel.objects.filter(uid__in=uid)
                    if del_uid.exists():
                        # del_uid.delete()
                        print ('删除VodHlsModel')
                    else:
                        val = val + 1
                        print('VodHlsModel表没有数据')
                if 'Order_Model' in id_list:
                    del_uid = Order_Model.objects.filter(UID__in=uid)
                    if del_uid.exists():
                        del_uid.delete()
                        # print ('删除Order_Model')
                    else:
                        val = val + 1
                        print('Order_Model表没有数据')
                if 'Device_Info' in id_list:
                    del_uid = Device_Info.objects.filter(UID__in=uid)
                    if del_uid.exists():
                        del_uid.delete()
                        # print ('删除Device_Info')
                    else:
                        val = val + 1
                        print('Order_Model表没有数据')
                if 'OssCrdModel' in id_list:
                    del_uid = OssCrdModel.objects.filter(uid__in=uid)
                    if del_uid.exists():
                        del_uid.delete()
                        # print ('删除OssCrdModel')
                    else:
                        val = val + 1
                        print('OssCrdModel表没有数据')
                if 'UidUserModel' in id_list:
                    del_uid = UidUserModel.objects.filter(UID__in=uid)
                    if del_uid.exists():
                        del_uid.delete()
                        # print ('删除UidUserModel')
                    else:
                        val = val + 1
                        print('UidUserModel表没有数据')
                # 有后台管理 设备配置表UidSetModel ---uid --本身，
                # 有后台管理 设备关联用户推送表Equipment_Info --devUid --独立没有儿子的，
                # 有后台管理             设备预览图表UID_Preview ---uid---孤立，
                # 有后台管理 设备关联套餐表UID_Bucket ---uid---孤立，
                # 有后台管理            云存回放信息表VodHlsModel ---uid---孤立，
                # 有后台管理 订单信息表Order_Model --UID----独立没有儿子的，
                # 有后台管理 用户设备信息表（最多信息量的表）Device_Info ---UID---孤立，
                #           设备证书OssCrdModel ---uid---孤立
                # 有后台管理 设备ap表 UidUserModel
                # 设备绑定UidPushModel---关联表---设备配置表UidSetModel---配置表的详情有显示

                # raise DatabaseError     #测试用，检测是否能捕捉错误
                if val == 9:
                    return response.json(173)
                else:
                    return response.json(0)
        else:
            return response.json(404)

    # 管理员查询接口
    def do_admin_query(self, request_dict, userID, response):
        own_perm = ModelService.check_perm(userID, 20)
        if own_perm is True:
            page = request_dict.get('page', None)
            line = request_dict.get('line', None)
            page = int(page)
            line = int(line)
            deviceContent = request_dict.get('content', None)
            if deviceContent:
                try:
                    searchCondition = json.loads(deviceContent)
                except Exception as e:
                    return response.json(10, repr(e))
                else:
                    kwargs = CommonService.get_kwargs(data=searchCondition)
                    omqs = UidSetModel.objects.filter(**kwargs).order_by('-id')
                    if not omqs.exists():
                        return response.json(0, [])
                    count = omqs.count()
                    order_ql = omqs[(page - 1) * line:page * line]
                    uidset_json = CommonService.qs_to_dict(order_ql)
                    uidset_json['count'] = count
                    return response.json(0, uidset_json)
            else:
                omqs = UidSetModel.objects.all().order_by('-id')
                if not omqs.exists():
                    return response.json(0, [])
                count = omqs.count()
                order_ql = omqs[(page - 1) * line:page * line]
                uidset_json = CommonService.qs_to_dict(order_ql)
                uidset_json['count'] = count
                return response.json(0, uidset_json)
        else:
            return response.json(404)

    # 管理员的添加
    def do_admin_add(self, request_dict, userID, response):
        own_perm = ModelService.check_perm(userID=userID, permID=40)
        if own_perm is not True:
            return response.json(404)
        uid = request_dict.get('uid', None)
        timestamp = int(time.time())
        param_flag = CommonService.get_param_flag(
            data=[uid])
        if param_flag is not True:
            return response.json(444)
        try:
            uidset = UidSetModel(
                uid=uid,
                addTime=timestamp,
                updTime=timestamp)
            uidset.save()
            return response.json(0)
        except Exception:
            errorInfo = traceback.format_exc()
            print(errorInfo)
            return response.json(500, {'details': errorInfo})

    # 管理员的编辑
    def do_admin_update(self, request_dict, userID, response):
        own_perm = ModelService.check_perm(userID=userID, permID=50)
        if own_perm is not True:
            return response.json(404)
        deviceContent = request_dict.get('content', None)
        id = request_dict.get('id', None)
        if not deviceContent or not id:
            return response.json(444, 'content,id')
        try:
            timestamp = int(time.time())
            deviceData = json.loads(deviceContent)
            uid_set = UidSetModel.objects.filter(id=id)
            if uid_set.exists():
                uid_set.update(updTime=timestamp, **deviceData)
                return response.json(0)
            else:
                return response.json(173)
        except Exception:
            errorInfo = traceback.format_exc()
            print(errorInfo)
            return response.json(500, {'details': errorInfo})

    def do_update(self, request_dict, response):
        uid = request_dict.get('uid', None)
        region_alexa = request_dict.get('region_alexa', None)
        is_alexa = request_dict.get('is_alexa', None)
        try:
            timestamp = int(time.time())
            uid_set = UidSetModel.objects.filter(uid=uid)
            if uid_set.exists():
                if region_alexa is None:
                    uid_set.update(updTime=timestamp, is_alexa=is_alexa)
                else:
                    if is_alexa is None:
                        uid_set.update(updTime=timestamp, region_alexa=region_alexa)
                    else:
                        uid_set.update(updTime=timestamp, region_alexa=region_alexa, is_alexa=is_alexa)
                return response.json(0)
            else:
                return response.json(173)
        except Exception:
            errorInfo = traceback.format_exc()
            return response.json(500, {'details': errorInfo})

    def do_update_set(self, request, request_dict, response):
        uid = request_dict.get('uid', None)
        deviceContent = request_dict.get('content', None)
        token = request_dict.get('token', None)
        # print(deviceContent)
        if not deviceContent or not uid:
            return response.json(444, 'content,uid')
        tko = TokenObject(token)
        response.lang = tko.lang
        if tko.code != 0:
            return response.json(tko.code)
        userID = tko.userID
        if userID is None:
            return response.json(309)
        try:
            # redisObj = RedisObject(db=8)
            # redisObj.del_data(key='uid_qs_' + userID)
            deviceData = json.loads(deviceContent)
            uid_set_qs = UidSetModel.objects.filter(uid=uid)
            if not uid_set_qs.exists():
                # 由于uid_set表和device_info表设备数量不一致，所以添加以下逻辑把device_info表中的相关信息保存到uid_set表
                di_qs = Device_Info.objects.filter(UID=uid, userID=userID)
                if di_qs.exists():
                    di = di_qs[0]
                    nowTime = int(time.time())
                    uid_set_create_dict = {
                        'uid': di.UID,
                        'addTime': nowTime,
                        'updTime': nowTime,
                        'ip': CommonService.get_ip_address(request),
                        'channel': di.ChannelIndex,
                        'nickname': di.NickName,
                    }
                    for k, v in deviceData.items():
                        uid_set_create_dict[k] = v
                    UidSetModel.objects.create(**uid_set_create_dict)
                else:
                    return response.json(177)
            else:
                uid_set_qs.update(**deviceData)
            print('update success')
        except Exception as e:
            return response.json(177, repr(e))
        else:
            return response.json(0)

    def do_update_channel_set(self, request_dict, response):
        uid = request_dict.get('uid', None)
        channel = request_dict.get('channel', None)
        channelContent = request_dict.get('content', None)
        token = request_dict.get('token', None)
        print(channelContent)
        if not channelContent or not uid or not channel:
            return response.json(444, 'content,uid, chan')
        tko = TokenObject(token)
        response.lang = tko.lang
        if tko.code != 0:
            return response.json(tko.code)
        userID = tko.userID
        if userID is None:
            return response.json(309)

        channel = int(channel)
        if channel < 1:
            return response.json(444, 'channel')
        try:
            # redisObj = RedisObject(db=8)
            # redisObj.del_data(key='uid_qs_' + userID)
            deviceData = json.loads(channelContent)
            uid_channel_set_qs = UidChannelSetModel.objects.filter(uid__uid=uid, channel=channel)
            if not uid_channel_set_qs.exists():
                uidObject = UidSetModel.objects.filter(uid=uid)
                ucs = {
                    'channel': channel,
                    'uid': uidObject[0]
                }
                keys = deviceData.keys()
                for key in keys:
                    ucs[key] = deviceData[key]
                UidChannelSetModel.objects.create(**ucs)
            else:
                uid_channel_set_qs.update(**deviceData)

        except Exception as e:
            return response.json(177, repr(e))
        else:
            return response.json(0)

    def do_set_voice(self, userID, request_dict, response):
        uid = request_dict.get('uid', None)
        channel = request_dict.get('channel', None)
        enter_voice = request_dict.get('enter_voice', None)
        leave_voice = request_dict.get('leave_voice', None)
        voice_status = request_dict.get('voice_status', None)
        intelligent_mute = request_dict.get('intelligent_mute', None)
        start_x = request_dict.get('start_x', None)
        start_y = request_dict.get('start_y', None)
        end_x = request_dict.get('end_x', None)
        end_y = request_dict.get('end_y', None)
        start_time = request_dict.get('start_time', None)
        end_time = request_dict.get('end_time', None)
        repeat_day = request_dict.get('repeat_day', None)
        direction = request_dict.get('direction', None)

        if uid and channel:
            channel = int(channel)
            if channel < 1:
                return response.json(444, 'channel')
            try:
                ucs = {}
                if enter_voice:
                    ucs['voice_prompt_enter'] = enter_voice

                if leave_voice:
                    ucs['voice_prompt_leave'] = leave_voice

                if voice_status:
                    ucs['voice_prompt_status'] = voice_status

                if intelligent_mute:
                    ucs['voice_prompt_intelligent_mute'] = intelligent_mute

                if start_x:
                    ucs['voice_start_x'] = start_x

                if start_y:
                    ucs['voice_start_y'] = start_y

                if end_x:
                    ucs['voice_end_x'] = end_x

                if end_y:
                    ucs['voice_end_y'] = end_y

                if start_time:
                    ucs['voice_start_time'] = start_time

                if end_time:
                    ucs['voice_end_time'] = end_time

                if repeat_day:
                    ucs['voice_repeat_day'] = repeat_day

                if direction:
                    ucs['voice_direction'] = direction

                uid_channel_set_qs = UidChannelSetModel.objects.filter(uid__uid=uid, channel=channel)
                if not uid_channel_set_qs.exists():
                    uidObject = UidSetModel.objects.filter(uid=uid)
                    ucs['channel'] = channel
                    ucs['uid'] = uidObject[0]
                    UidChannelSetModel.objects.create(**ucs)
                else:
                    uid_channel_set_qs.update(**ucs)

            except Exception as e:
                return response.json(177, repr(e))
            else:
                return response.json(0)

    # 重置设备云存
    def vod_reset(self, request_dict, response):
        uid = request_dict.get('uid', None)
        if uid:
            try:
                with transaction.atomic():
                    # 删除和更新设备云存相关数据
                    UID_Bucket.objects.filter(uid=uid).delete()
                    Unused_Uid_Meal.objects.filter(uid=uid).delete()
                    Order_Model.objects.filter(UID=uid).delete()
                    StsCrdModel.objects.filter(uid=uid).delete()
                    VodHlsModel.objects.filter(uid=uid).delete()
                    ExperienceContextModel.objects.filter(uid=uid).delete()
                    # UIDMainUser.objects.filter(UID=uid).delete()
                    Device_Info.objects.filter(UID=uid).update(vodPrimaryUserID='', vodPrimaryMaster='')
            except Exception as e:
                print(e)
                return response.json(500, repr(e))
            else:
                return response.json(0)

    # def do_test(self, response):
    #     di_qs = Device_Info.objects.values('Type').annotate(c=Count('UID', distinct=True)).order_by()
    #     for di in di_qs:
    #         print(di)
    #
    #     # 设备总数量
    #     count = Device_Info.objects.values('UID').distinct().count()
    #     print('设备总数量：' + str(count))
    #
    #     # 设备型号统计
    #     print('设备型号统计:')
    #     us_qs = UidSetModel.objects.values('deviceModel').annotate(c=Count('id')).order_by()
    #     for us in us_qs:
    #         print(us)
    #
    #     # 手机品牌类型统计
    #     print('手机品牌类型统计:')
    #     ub_qs = User_Brand.objects.values('deviceSupplier').annotate(c=Count('id')).order_by()
    #     for ub in ub_qs:
    #         print(ub)
    #
    #     # 手机型号统计
    #     print('手机型号统计:')
    #     ub_qs = User_Brand.objects.values('deviceSupplier', 'deviceModel').annotate(c=Count('id')).order_by()
    #     for ub in ub_qs:
    #         print(ub)
    #
    #     # 区域统计
    #     print('区域统计:')
    #     di_qs = Device_Info.objects.values('area').annotate(c=Count('UID', distinct=True)).order_by()
    #     for di in di_qs:
    #         print(di)
    #
    #     # 区域设备类型统计
    #     print('区域设备类型统计:')
    #     di_qs = Device_Info.objects.values('area', 'Type').annotate(c=Count('UID', distinct=True)).order_by()
    #     for di in di_qs:
    #         print(di)
    #     return response.json(0)