#!/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/11/15 16:45
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: UserUid.py
@Contact: chanjunkai@163.com
"""
# 添加设备字段
import oss2
import re
import time
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 Ansjer.config import OSS_STS_ACCESS_SECRET, OSS_STS_ACCESS_KEY
from Model.models import UID_Bucket, UID_Preview, UidSetModel
from Model.models import UidUserModel
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService
from Service.ModelService import ModelService
from Object.RedisObject import RedisObject
import base64
from Controller.CheckUserData import RandomStr
'''
http://192.168.136.40:8077/uiduser/add?token=local&UID=z123asdfqwerzxcvqw12&NickName=xxoxox&View_Account=user&View_Password=password&ChannelIndex=8&is_ap=1&Type=5&NickName=1234zcxv
http://192.168.136.40:8077/uiduser/query?token=local&page=1&line=10&is_ap=1&NickName=1234zcxv&uid=zxcvasdfqwerzxcvqwer
http://192.168.136.40:8077/uiduser/delete?token=local&id=138001380001573884997393980&is_ap=1
'''


# 添加设备字段
def addInterface(request):
    request.encoding = 'utf-8'
    response = ResponseObject()
    if request.method == 'POST':
        request_dict = request.POST
    elif request.method == 'GET':
        request_dict = request.GET
    else:
        return response.json(444)
    token = request_dict.get('token', None)
    UID = request_dict.get('UID', None)
    NickName = request_dict.get('NickName', None)
    View_Account = request_dict.get('View_Account', None)
    View_Password = request_dict.get('View_Password', '')
    Type = request_dict.get('Type', None)
    ChannelIndex = request_dict.get('ChannelIndex', None)
    is_ap = request_dict.get('is_ap', None)
    if all([UID, NickName, View_Account, Type, ChannelIndex]):
        tko = TokenObject(token)
        response.lang = tko.lang
        if tko.code == 0:
            userID = tko.userID
            re_uid = re.compile(r'^[A-Za-z0-9]{20}$')
            if re_uid.match(UID):
                is_ap = int(is_ap)
                is_exist = UidUserModel.objects.filter(UID=UID, userID_id=userID, is_ap=is_ap)
                if is_exist:
                    return response.json(174)
                else:
                    try:
                        pk = CommonService.getUserID(getUser=False)
                        create_data = {
                            'id': pk, 'userID_id': userID, 'UID': UID,
                            'NickName': NickName, 'View_Account': View_Account,
                            'View_Password': View_Password, 'Type': Type, 'ChannelIndex': ChannelIndex
                        }
                        UidUserModel.objects.create(**create_data)
                        # 判断影子信息
                        nowTime = int(time.time())
                        us_qs = UidSetModel.objects.filter(uid=UID)
                        if not us_qs.exists():
                            uid_set_create_dict = {
                                'uid': UID,
                                'addTime': nowTime,
                                'updTime': nowTime,
                                'ip': CommonService.get_ip_address(request),
                                'channel': ChannelIndex,
                                'nickname': NickName}
                            UidSetModel.objects.create(**uid_set_create_dict)
                    except Exception as e:
                        return response.json(10, repr(e))
                    else:
                        uid_user_qs = UidUserModel.objects.filter(id=pk). \
                            values('id', 'userID', 'NickName', 'UID', 'View_Account', 'View_Password',
                                   'ChannelIndex', 'Type', 'isShare', 'primaryUserID', 'primaryMaster',
                                   'data_joined', 'version', 'isVod', 'isExist','is_ap')
                        uid_user_ql = CommonService.qs_to_list(uid_user_qs)
                        ubqs = UID_Bucket.objects.filter(uid=UID). \
                            values('bucket__content', 'status', 'channel', 'endTime', 'uid')
                        res = uid_user_ql[0]
                        res['vod'] = list(ubqs)
                        return response.json(0, res)
            else:
                return response.json(444, {'param': 'UID'})
        else:
            return response.json(tko.code)
    else:
        return response.json(444, {'param': 'UID,NickName,View_Account,View_Password,Type,ChannelIndex'})


# 新查询设备字段
def queryInterface(request):
    request.encoding = 'utf-8'
    response = ResponseObject()
    if request.method == 'POST':
        request_dict = request.POST
    elif request.method == 'GET':
        request_dict = request.GET
    else:
        return response.json(444)
    token = request_dict.get('token', None)
    page = request_dict.get('page', None)
    line = request_dict.get('line', None)
    NickName = request_dict.get('NickName', None)
    uid = request_dict.get('uid', None)
    is_ap = request_dict.get('is_ap', None)
    page = int(page)
    line = int(line)
    tko = TokenObject(token)
    response.lang = tko.lang
    if page <= 0:
        return response.json(0)

    if tko.code == 0:
        userID = tko.userID
        # redisObj = RedisObject(db=8)
        # redisObj.del_data(key='uid_qs_' + userID)
        uid_user_qs = UidUserModel.objects.filter(userID_id=userID)
        if is_ap:
            is_ap = int(is_ap)
            uid_user_qs = uid_user_qs.filter(is_ap=is_ap)
        if NickName:
            uid_user_qs = uid_user_qs.filter(NickName__icontains=NickName)
        if uid:
            uid_user_qs = uid_user_qs.filter(UID=uid)
        uid_user_ql = uid_user_qs[(page - 1) * line:page * line]. \
            values('id', 'userID', 'NickName', 'UID', 'View_Account',
                   'View_Password', 'ChannelIndex', 'Type', 'isShare',
                   'primaryUserID', 'primaryMaster', 'data_joined', 'version',
                   'isVod', 'isExist', 'NotificationMode','is_ap')
        uid_user_ls = CommonService.qs_to_list(uid_user_ql)
        uid_list = []
        for uid_user in uid_user_ls:
            uid_list.append(uid_user['UID'])
        ubqs = UID_Bucket.objects.filter(uid__in=uid_list). \
            values('bucket__content', 'status', 'channel', 'endTime', 'uid')
        upqs = UID_Preview.objects.filter(uid__in=uid_list).order_by('channel').values('id', 'uid', 'channel')
        auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
        bucket = oss2.Bucket(auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')
        nowTime = int(time.time())
        data = []
        # 设备拓展信息表
        us_qs = UidSetModel.objects.filter(uid__in=uid_list).values('uid', 'version', 'nickname')
        uv_dict = {}
        for us in us_qs:
            uv_dict[us['uid']] = {'version': us['version'], 'nickname': us['nickname']}
        for p in uid_user_ls:
            p['vod'] = []
            for dm in ubqs:
                if p['UID'] == dm['uid']:
                    if dm['endTime'] > nowTime:
                        p['vod'].append(dm)
            p['preview'] = []
            for up in upqs:
                if p['UID'] == up['uid']:
                    obj = 'uid_preview/{uid}/channel_{channel}.png'.format(uid=up['uid'], channel=up['channel'])
                    img_sign = bucket.sign_url('GET', obj, 300)
                    p['preview'].append(img_sign)
            p_uid = p['UID']
            if p_uid in uv_dict:
                # 设备版本号
                p['uid_version'] = uv_dict[p_uid]['version']
                # 设备昵称
                if uv_dict[p_uid]['nickname']:
                    p['NickName'] = uv_dict[p_uid]['nickname']
            else:
                # 设备版本号
                p['uid_version'] = ''
            data.append(p)
        return response.json(0, data)
    else:
        return response.json(tko.code)


# http://192.168.136.40:8077/uiduser/update?token=local&id=138001380001573885065588328&View_Account=12&View_Password=555&NickName=555

# 添加设备字段
def updateInterface(request):
    request.encoding = 'utf-8'
    response = ResponseObject()
    if request.method == 'POST':
        request_dict = request.POST
    elif request.method == 'GET':
        request_dict = request.GET
    else:
        return response.json(444)
    token = request_dict.get('token', None)
    NickName = request_dict.get('NickName', None)
    View_Account = request_dict.get('View_Account', None)
    View_Password = request_dict.get('View_Password', None)
    Type = request_dict.get('Type', None)
    tko = TokenObject(token)
    response.lang = tko.lang
    if tko.code == 0:
        userID = tko.userID
        uid_user_qs = UidUserModel.objects.filter(userID_id=userID,)
        if uid_user_qs.exists():
            update_dict = {}
            if NickName:
                update_dict['NickName'] = NickName
            if View_Account is not None:
                update_dict['View_Account'] = View_Account
            if View_Password is not None:
                update_dict['View_Password'] = View_Password
            if Type is not None:
                update_dict['Type'] = Type
            is_update = uid_user_qs.update(**update_dict)
            if is_update:
                return response.json(0)
            else:
                return response.json(177)
        else:
            return response.json(174)
    else:
        return response.json(tko.code)


# 新删除设备
def deleteInterface(request):
    '''
    删除用户设备
    :param request:
    :return:
    '''
    response = ResponseObject()
    request.encoding = 'utf-8'
    if request.method == 'POST':
        request_dict = request.POST
    elif request.method == 'GET':
        request_dict = request.GET
    else:
        return response.json(444)
    token = request_dict.get('token', None)
    id = request_dict.get('id', None)
    is_ap = request_dict.get('is_ap', None)
    if all([token, id, is_ap]):
        tko = TokenObject(token)
        response.lang = tko.lang
        if tko.code == 0:
            userID = tko.userID
            # redisObj = RedisObject(db=8)
            # redisObj.del_data(key='uid_qs_' + userID)
            uid_user_qs = UidUserModel.objects.filter(userID_id=userID, id=id)
            if uid_user_qs.exists():
                uid_user_qs.delete()
                return response.json(0)
            else:
                return response.json(173)
        else:
            return response.json(tko.code)
    else:
        return response.json(444, {'param': 'token,id,is_ap'})


# 设备信息添加
class UidUserView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(UidUserView, 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 == 'adminDelete':
            return self.do_admin_delete(request_dict, userID, response)
        elif operation == 'adminQuery':
            return self.do_admin_query(request_dict, userID, response)
        else:
            return response.json(444, 'error path')

    # 管理员删除
    def do_admin_delete(self, request_dict, userID, response):
        own_perm = ModelService.check_perm(userID, 20)
        if own_perm is True:
            id = request_dict.getlist('id', None)
            uid_user_qs = UidUserModel.objects.filter(id__in=id)
            if uid_user_qs.exists():
                uid_user_qs.delete()
                return response.json(0)
            else:
                return response.json(173)
        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)
                    uid_user_qs = UidUserModel.objects.filter(**kwargs).order_by('-id')
                    if not uid_user_qs.exists():
                        return response.json(0, [])
                    count = uid_user_qs.count()
                    uid_user_ql = uid_user_qs[(page - 1) * line:page * line]. \
                        values('id', 'userID', 'userID__username', 'userID__userEmail', 'userID__NickName' 'NickName',
                               'UID', 'View_Account',
                               'View_Password', 'ChannelIndex', 'Type', 'isShare',
                               'primaryUserID', 'primaryMaster', 'data_joined', 'version',
                               'isVod', 'isExist', 'NotificationMode', 'is_ap')
                    uid_user_ls = CommonService.qs_to_list(uid_user_ql)
                    return response.json(0, {'datas': uid_user_ls, 'count': count})
            else:
                uid_user_qs = UidUserModel.objects.all().order_by('-id')
                if not uid_user_qs.exists():
                    return response.json(0, [])
                count = uid_user_qs.count()
                uid_user_ql = uid_user_qs[(page - 1) * line:page * line]. \
                    values('id', 'userID', 'userID__username', 'userID__userEmail', 'userID__NickName', 'NickName',
                           'UID', 'View_Account',
                           'View_Password', 'ChannelIndex', 'Type', 'isShare',
                           'primaryUserID', 'primaryMaster', 'data_joined', 'version',
                           'isVod', 'isExist', 'NotificationMode', 'is_ap')
                uid_user_ls = CommonService.qs_to_list(uid_user_ql)
                return response.json(0, {'datas' : uid_user_ls, 'count': count})
        else:
            return response.json(404)




# v3添加设备字段
def v3addInterface(request):
    request.encoding = 'utf-8'
    response = ResponseObject()
    if request.method == 'POST':
        request_dict = request.POST
    elif request.method == 'GET':
        request_dict = request.GET
    else:
        return response.json(444)
    token = request_dict.get('token', None)
    UID = request_dict.get('UID', None)
    NickName = request_dict.get('NickName', None)
    View_Account = request_dict.get('View_Account', None)
    View_Password = request_dict.get('View_Password', '')
    Type = request_dict.get('Type', None)
    ChannelIndex = request_dict.get('ChannelIndex', None)
    is_ap = request_dict.get('is_ap', None)
    try:
        for i in range(1, 4):
            if i == 1:
                View_Password = base64.b64decode(View_Password)
                View_Password = View_Password.decode('utf-8')
                View_Password = View_Password[1:-1]
            if i == 2:
                View_Password = base64.b64decode(View_Password)
                View_Password = View_Password.decode('utf-8')
                View_Password = View_Password[2:-2]
            if i == 3:
                View_Password = base64.b64decode(View_Password)
                View_Password = View_Password.decode('utf-8')
                View_Password = View_Password[3:-3]
        print(View_Password)
    except Exception as e:
        return response.json(111)
    if not View_Password:
        return response.json(424)
    if all([UID, NickName, View_Account, Type, ChannelIndex]):
        tko = TokenObject(token)
        response.lang = tko.lang
        if tko.code == 0:
            userID = tko.userID
            re_uid = re.compile(r'^[A-Za-z0-9]{20}$')
            if re_uid.match(UID):
                is_ap = int(is_ap)
                is_exist = UidUserModel.objects.filter(UID=UID, userID_id=userID, is_ap=is_ap)
                if is_exist:
                    return response.json(174)
                else:
                    try:
                        pk = CommonService.getUserID(getUser=False)
                        create_data = {
                            'id': pk, 'userID_id': userID, 'UID': UID,
                            'NickName': NickName, 'View_Account': View_Account,
                            'View_Password': View_Password, 'Type': Type, 'ChannelIndex': ChannelIndex
                        }
                        UidUserModel.objects.create(**create_data)
                        # 判断影子信息
                        nowTime = int(time.time())
                        us_qs = UidSetModel.objects.filter(uid=UID)
                        if not us_qs.exists():
                            uid_set_create_dict = {
                                'uid': UID,
                                'addTime': nowTime,
                                'updTime': nowTime,
                                'ip': CommonService.get_ip_address(request),
                                'channel': ChannelIndex,
                                'nickname': NickName}
                            UidSetModel.objects.create(**uid_set_create_dict)
                    except Exception as e:
                        return response.json(10, repr(e))
                    else:
                        uid_user_qs = UidUserModel.objects.filter(id=pk). \
                            values('id', 'userID', 'NickName', 'UID', 'View_Account', 'View_Password',
                                   'ChannelIndex', 'Type', 'isShare', 'primaryUserID', 'primaryMaster',
                                   'data_joined', 'version', 'isVod', 'isExist','is_ap')
                        uid_user_ql = CommonService.qs_to_list(uid_user_qs)
                        ubqs = UID_Bucket.objects.filter(uid=UID). \
                            values('bucket__content', 'status', 'channel', 'endTime', 'uid')
                        res = uid_user_ql[0]
                        res['vod'] = list(ubqs)
                        return response.json(0, res)
            else:
                return response.json(444, {'param': 'UID'})
        else:
            return response.json(tko.code)
    else:
        return response.json(444, {'param': 'UID,NickName,View_Account,View_Password,Type,ChannelIndex'})


# v3新查询设备字段
def v3queryInterface(request):
    request.encoding = 'utf-8'
    response = ResponseObject()
    if request.method == 'POST':
        request_dict = request.POST
    elif request.method == 'GET':
        request_dict = request.GET
    else:
        return response.json(444)
    token = request_dict.get('token', None)
    page = request_dict.get('page', None)
    line = request_dict.get('line', None)
    NickName = request_dict.get('NickName', None)
    uid = request_dict.get('uid', None)
    is_ap = request_dict.get('is_ap', None)
    page = int(page)
    line = int(line)
    tko = TokenObject(token)
    response.lang = tko.lang
    if page <= 0:
        return response.json(0)
    if tko.code == 0:
        userID = tko.userID
        # redisObj = RedisObject(db=8)
        # redisObj.del_data(key='uid_qs_' + userID)
        uid_user_qs = UidUserModel.objects.filter(userID_id=userID)
        if is_ap:
            is_ap = int(is_ap)
            uid_user_qs = uid_user_qs.filter(is_ap=is_ap)
        if NickName:
            uid_user_qs = uid_user_qs.filter(NickName__icontains=NickName)
        if uid:
            uid_user_qs = uid_user_qs.filter(UID=uid)
        uid_user_ql = uid_user_qs[(page - 1) * line:page * line]. \
            values('id', 'userID', 'NickName', 'UID', 'View_Account',
                   'View_Password', 'ChannelIndex', 'Type', 'isShare',
                   'primaryUserID', 'primaryMaster', 'data_joined', 'version',
                   'isVod', 'isExist', 'NotificationMode','is_ap')
        uid_user_ls = CommonService.qs_to_list(uid_user_ql)
        uid_list = []
        for uid_user in uid_user_ls:
            uid_list.append(uid_user['UID'])
        ubqs = UID_Bucket.objects.filter(uid__in=uid_list). \
            values('bucket__content', 'status', 'channel', 'endTime', 'uid')
        upqs = UID_Preview.objects.filter(uid__in=uid_list).order_by('channel').values('id', 'uid', 'channel')
        auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
        bucket = oss2.Bucket(auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')
        nowTime = int(time.time())
        data = []
        # 设备拓展信息表
        us_qs = UidSetModel.objects.filter(uid__in=uid_list).values('uid', 'version', 'nickname')
        uv_dict = {}
        for us in us_qs:
            uv_dict[us['uid']] = {'version': us['version'], 'nickname': us['nickname']}
        for p in uid_user_ls:
            p['vod'] = []
            for dm in ubqs:
                if p['UID'] == dm['uid']:
                    if dm['endTime'] > nowTime:
                        p['vod'].append(dm)
            p['preview'] = []
            p['View_Password'] = encrypt_pwd(p['View_Password'])
            for up in upqs:
                if p['UID'] == up['uid']:
                    obj = 'uid_preview/{uid}/channel_{channel}.png'.format(uid=up['uid'], channel=up['channel'])
                    img_sign = bucket.sign_url('GET', obj, 300)
                    p['preview'].append(img_sign)
            p_uid = p['UID']
            if p_uid in uv_dict:
                # 设备版本号
                p['uid_version'] = uv_dict[p_uid]['version']
                # 设备昵称
                if uv_dict[p_uid]['nickname']:
                    p['NickName'] = uv_dict[p_uid]['nickname']
            else:
                # 设备版本号
                p['uid_version'] = ''
            data.append(p)
        return response.json(0, data)
    else:
        return response.json(tko.code)

# #加密
def encrypt_pwd(userPwd):
    for i in range(1, 4):
        if i == 1:
            userPwd = RandomStr(3, False)+userPwd+RandomStr(3, False)
            userPwd = base64.b64encode(str(userPwd).encode("utf-8")).decode('utf8')
        if i == 2:
            userPwd = RandomStr(2, False)+str(userPwd)+RandomStr(2, False)
            userPwd = base64.b64encode(str(userPwd).encode("utf-8")).decode('utf8')
        if i == 3:
            userPwd = RandomStr(1, False)+str(userPwd)+RandomStr(1, False)
            userPwd = base64.b64encode(str(userPwd).encode("utf-8")).decode('utf8')
    return userPwd







