#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.core import serializers
import traceback, simplejson as json
from django.views.generic.base import View
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from Model.models import Device_User, Device_Info, Role, UserExModel
from Service.CommonService import CommonService
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from django.db.models import Q
from Service.ModelService import ModelService
from Object.RedisObject import RedisObject


class searchUserView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(searchUserView, self).dispatch(*args, **kwargs)

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        fieldDict = request.POST
        return self.validations(fieldDict, args, kwargs)

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        fieldDict = request.GET
        return self.validations(fieldDict, args, kwargs)

    def searchUserSQL(self, fieldDict, response, *args, **kwargs):
        if 'username' in fieldDict.keys():
            username = fieldDict.get('username', None)
            User = Device_User.objects.filter(
                Q(username=username) | Q(phone=username) | Q(userEmail=username)).order_by('-data_joined')
        elif 'userEmail' in fieldDict.keys():
            email = fieldDict.get('userEmail', None)
            User = Device_User.objects.filter(Q(userEmail=email) | Q(username=email)).order_by('-data_joined')
        elif 'userID' in fieldDict.keys():
            userID = fieldDict.get('userID', None)
            User = Device_User.objects.filter(userID=userID).order_by('-data_joined')
        elif 'roleName' in fieldDict.keys():
            roleName = fieldDict.get('roleName', None)
            User = Device_User.objects.filter(role__roleName__contains=roleName).order_by('-data_joined')
        else:
            User = Device_User.objects.filter(**fieldDict).order_by('-data_joined')
        if User.exists():
            ddUser = User[0].device_info_set.filter(isShare=False)
            sqlJSON = serializers.serialize('json', User)
            sqlList = json.loads(sqlJSON)
            if ddUser:
                sqlJSON1 = serializers.serialize('json', ddUser)
                sqlList1 = json.loads(sqlJSON1)
                device_Info_dict = {}
                device_Info_list = []
                for eachJson1 in sqlList1:
                    device_Info_dict['primaryUserID'] = eachJson1['fields']['primaryUserID']
                    device_Info_dict['Type'] = eachJson1['fields']['Type']
                    device_Info_dict['UID'] = eachJson1['fields']['UID']
                    device_Info_dict['pk'] = eachJson1['pk']

                    device_Info_dict['NickName'] = eachJson1['fields']['NickName']
                    device_Info_dict['View_Password'] = eachJson1['fields']['View_Password']
                    device_Info_dict['View_Account'] = eachJson1['fields']['View_Account']
                    device_Info_dict['Online'] = eachJson1['fields']['Online']
                    device_Info_dict['EventNotification'] = eachJson1['fields']['EventNotification']
                    device_Info_dict['ChannelIndex'] = eachJson1['fields']['ChannelIndex']
                    device_Info_dict['EventNotification'] = eachJson1['fields']['EventNotification']
                    device_Info_dict['NotificationMode'] = eachJson1['fields']['NotificationMode']
                    device_Info_list.append(device_Info_dict)
                    device_Info_dict = {}
                sqlList[0]['device_info'] = device_Info_list
            else:
                sqlList[0]['device_info'] = []
            if sqlList[0]['fields']['username'] is None:
                sqlList[0]['fields']['username'] = ''
            if sqlList[0]['fields']['userEmail'] is None:
                sqlList[0]['fields']['userEmail'] = ''
            sqlDict = dict(zip(["datas"], [sqlList]))
            return response.json(0, sqlDict)
        else:
            return response.json(102)

    def searchUserPCSQL(self, fieldDict, response):
        try:
            page = int(fieldDict['page'])
            line = int(fieldDict['line'])
            fieldDict.pop('page')
            fieldDict.pop('line')
            fieldDict.pop('type')
            if len(fieldDict) > 0:
                searchCondition = CommonService.get_kwargs(data=fieldDict)
                qs = Device_User.objects.filter(**searchCondition).order_by('-data_joined')
            else:
                qs = Device_User.objects.all().order_by('-data_joined')
        except Exception as e:
            errorInfo = traceback.format_exc()
            print('查询数据库错误: %s' % errorInfo)
            return response.json(500, {"details": repr(e)})
        else:
            if qs:
                device_user_count = qs.count()
                device_user_res = qs[(page - 1) * line:page * line]
                sqlDict = CommonService.qs_to_dict(device_user_res)
                redisObj = RedisObject(db=3)
                for k, v in enumerate(sqlDict["datas"]):
                    for val in device_user_res:
                        if v['pk'] == val.userID:
                            dvqs = val.device_info_set.filter(isShare=False)
                            device_info_list = CommonService.qs_to_dict(dvqs)
                            # device_user关联到device_info
                            sqlDict["datas"][k]['device_info'] = device_info_list
                    if len(v['fields']['role']) > 0:
                        role_query_set = Role.objects.get(rid=v['fields']['role'][0])
                        sqlDict["datas"][k]['fields']['role'].append(role_query_set.roleName)
                    if redisObj.get_data(key=v['pk']):
                        sqlDict["datas"][k]['fields']['online'] = True
                    else:
                        sqlDict["datas"][k]['fields']['online'] = False
                    ue = UserExModel.objects.filter(userID=v['pk'])
                    if ue.exists():
                        sqlDict["datas"][k]['fields']['appBundleId'] = ue[0].appBundleId
                    else:
                        sqlDict["datas"][k]['fields']['appBundleId'] = ''
                sqlDict['count'] = device_user_count
                return response.json(0, sqlDict)
            else:
                return response.json(0, {"datas": ""})

    def validations(self, fieldDict, *args, **kwargs):
        token = fieldDict.get('token', None)
        response = ResponseObject()
        tko = TokenObject(token)
        response.lang = tko.lang
        if tko.code != 0:
            return response.json(tko.code)
        fieldDict = fieldDict.dict()
        fieldDict.pop('token')
        type = fieldDict.get('type', None)
        if type == 'PC':
            return self.searchUserPCSQL(fieldDict, response)
        else:
            return self.searchUserSQL(fieldDict, response, args, kwargs)


class shareUserEquipmentView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(shareUserEquipmentView, self).dispatch(*args, **kwargs)

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'

        queryDict = request.POST
        return self.shareUser(queryDict, args, kwargs)

    def get(self, request, *args, **kwargs):
        request.encoding = 'gb2312'

        queryDict = request.GET
        return self.shareUser(queryDict, args, kwargs)

    def shareUser(self, queryDict, *args, **kwargs):
        token = queryDict.get('token', None)
        GuestID = queryDict.get('guestID', None)
        content = queryDict.get('content', None)
        sharedAll = queryDict.get('sharedAll', False)

        if sharedAll in ('1', '0'):
            sharedAll = bool(int(sharedAll))
        elif sharedAll in ('true', 'false'):
            if sharedAll == 'true':
                sharedAll = 1
            else:
                sharedAll = 0
        response = ResponseObject()
        if not GuestID:
            return response.json(444, 'GuestID')
        tko = TokenObject(token)
        response.lang = tko.lang
        if tko.code != 0:
            return response.json(tko.code)
        MasterID = tko.userID
        if sharedAll and MasterID != None:
            return self.shareUserSQL(MasterID, GuestID, True, response, args, kwargs)
        if content != None and MasterID != None:
            return self.shareUserSQL(MasterID, GuestID, False, response, args, content=content)
        else:
            return response.json(444, 'sharedAll or content')

    def shareUserSQL(self, MasterID, GuestID, sharedAll, response, *args, **kwargs):
        Guest = Device_User.objects.filter(userID=GuestID).order_by('-data_joined')
        Master = Device_Info.objects.filter(userID_id=MasterID).order_by('-data_joined')
        if not Master or not Guest:
            return response.json(104)
        querysetList = []
        dictLen = 0
        if sharedAll:
            for equipment in Master:
                eqDict = equipment.model_to_dict(exclude=['id', 'data_joined', 'primaryUserID'])

                shareEquipment = Device_Info.objects.filter(userID_id=GuestID, primaryUserID= \
                    MasterID, UID=eqDict.get('UID', None)).order_by('-data_joined')

                if shareEquipment:
                    dictLen += 1
                    continue
                else:
                    puserId = eqDict.pop('userID')
                    eqDict['primaryUserID'] = puserId
                    eqDict['primaryMaster'] = ModelService.get_user_name(puserId)
                    eqDict['isShare'] = True
                    eqDict['userID_id'] = GuestID
                    eqDict['id'] = CommonService.getUserID(getUser=False)
                    querysetList.append(Device_Info(**eqDict))
        else:
            content = kwargs.get('content', None)
            if content != None:
                contentDict = json.loads(content)
                uidlist = UID = contentDict.get('UID', None)
                print(uidlist)
                for equipment in Master:
                    eqDict = equipment.model_to_dict(exclude=['id', 'data_joined', 'primaryUserID'])

                    if eqDict['UID'] in uidlist:
                        UID.remove(eqDict['UID'])
                        shareEquipment = Device_Info.objects.filter(userID_id=GuestID, primaryUserID= \
                            MasterID, UID=eqDict.get('UID', None)).order_by('-data_joined')
                        if shareEquipment:
                            dictLen += 1
                        else:
                            puserId = eqDict.pop('userID')
                            eqDict['primaryUserID'] = puserId
                            eqDict['primaryMaster'] = ModelService.get_user_name(puserId)
                            eqDict['isShare'] = True
                            eqDict['userID_id'] = GuestID
                            eqDict['id'] = CommonService.getUserID(getUser=False)
                            querysetList.append(Device_Info(**eqDict))
                    else:
                        continue

        if len(querysetList) == 0:
            return response.json(174, {'error_UID': UID})
        else:
            try:
                Device_Info.objects.bulk_create(querysetList)
            except Exception as e:
                errorInfo = traceback.format_exc()
                print('添加数据库记录错误: %s' % errorInfo)
                return response.json(500, {"details": repr(e)})
            else:
                if dictLen > 0:
                    res = {'Shared': dictLen, 'Sharing': len(querysetList), 'errormsg': 'some had share'}
                else:
                    if sharedAll:
                        res = {'Sharing': len(querysetList)}
                    else:
                        if len(UID) > 0:
                            res = {'error_UID': UID, 'Sharing': len(querysetList)}
                        else:
                            res = {'Sharing': len(querysetList)}
                # redisObj = RedisObject(db=8)
                # redisObj.del_data(key='uid_qs_' + GuestID)
                return response.json(0, res)


class unsharedUserEquipmentView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(unsharedUserEquipmentView, self).dispatch(*args, **kwargs)

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'

        queryset = request.POST
        return self.unsharedUserEquipment(queryset, args, kwargs)

    def get(self, request, *args, **kwargs):
        request.encoding = 'gb2312'

        queryset = request.GET
        return self.unsharedUserEquipment(queryset, args, kwargs)

    def unsharedUserEquipment(self, queryset, *args, **kwargs):
        token = queryset.get('token', None)
        GuestID = queryset.get('guestID', None)
        content = queryset.get('content', None)
        unsharedAll = queryset.get('unsharedAll', False)
        response = ResponseObject()

        if unsharedAll in ('1', '0'):
            unsharedAll = bool(int(unsharedAll))
        elif unsharedAll in ('true', 'false'):
            if unsharedAll == 'true':
                unsharedAll = 1
            else:
                unsharedAll = 0

        if token != None and GuestID != None and len(GuestID) > 0:
            tko = TokenObject(token)
            response.lang = tko.lang
            if tko.code == 0:
                MasterID = tko.userID
                if unsharedAll and MasterID != None:
                    return self.unsharedUserEquipmentSQL(MasterID, GuestID, True, response, args, kwargs)
                else:
                    if content != None and MasterID != None:
                        return self.unsharedUserEquipmentSQL(MasterID, GuestID, False, response, args, content=content)
                    else:
                        return response.json(444, 'content or unsharedAll')
            else:
                return response.json(tko.code)
        else:
            return response.json(800)

    def unsharedUserEquipmentSQL(self, MasterID, GuestID, unsharedAll, response, *args, **kwargs):
        if unsharedAll:
            ec = Device_Info.objects.filter(userID_id=GuestID, primaryUserID=MasterID).delete()
            return response.json(0, {'removeCount': ec[0]})
        else:
            content = kwargs.get('content', None)
            if content != None:
                removeCount = 0
                errorRemove = []
                errorUID = []
                contentDict = json.loads(content)
                uidlist = contentDict.get('UID', None)
                for index in range(len(uidlist)):
                    uid = uidlist[index]
                    try:
                        equipment = Device_Info.objects.filter(userID_id=GuestID, primaryUserID=MasterID, UID=uid)
                        if equipment:
                            equipmentCount = equipment.delete()
                        else:
                            errorUID.append(uid)
                            continue
                    except Exception as e:
                        errorInfo = traceback.format_exc()
                        print('查询数据库错误: %s' % errorInfo)

                        errorRemove.append(uid)
                        continue
                    else:
                        removeCount += equipmentCount[0]
                if len(errorRemove) > 0:
                    return response.json(176, {'removeCount': removeCount, 'error_UID': errorRemove})
                else:
                    if len(errorUID) > 0:
                        return response.json(173, {'removeCount': removeCount, 'error_UID': errorUID})
                    else:
                        return response.json(0, {'removeCount': removeCount})
