#!/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/3/4 16:30
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: DeviceShare.py
@Contact: chanjunkai@163.com
"""

import json
import time

from django.views.generic.base import View
from Object.RedisObject import RedisObject
from Ansjer.config import SERVER_DOMAIN
from Model.models import Device_Info, Device_User
from Model.models import UID_Bucket
from Object.RedisObject import RedisObject
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService


class DeviceShareView(View):

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

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

    def validation(self, request_dict, operation):
        response = ResponseObject()
        token = request_dict.get('token', None)
        if token:
            tko = TokenObject(token)
            response.lang = tko.lang
            if tko.code == 0:
                userID = tko.userID
                if operation == 'generateTokenUrl':
                    return self.do_generate_token_url(userID, request_dict, response)
                elif operation == 'showShareInfo':
                    return self.do_show_share_info(request_dict, response)
                elif operation == 'confirm':
                    return self.do_confirm(userID, request_dict, response)
                elif operation == 'queryUser':
                    return self.do_query_user(userID, request_dict, response)
                elif operation == 'deleteUser':
                    return self.do_delete_user(userID, request_dict, response)
                elif operation == 'deleteUserV2':
                    return self.do_delete_userV2(userID, request_dict, response)
                else:
                    return response.json(414)
            else:
                return response.json(tko.code)
        else:
            return response.json(444, {'param': 'token'})

    def do_generate_token_url(self, userID, request_dict, response):
        UID = request_dict.get('UID', None)
        dvqs = Device_Info.objects.filter(UID=UID, userID_id=userID, isShare=False).values('NickName')
        userqs = Device_User.objects.filter(userID=userID).values('username', 'userEmail', 'phone', 'userIconPath')
        if dvqs:
            data = {'sharer': userID, 'UID': UID}
            # -----------------
            # share_token = jwt.encode(data, '.#^^&', algorithm='HS256').decode('utf-8')
            # +++++++++++++++++
            redisObj = RedisObject()
            share_token = str(int(time.time())) + CommonService.RandomStr(8)
            if not redisObj.set_data(key=share_token, val=json.dumps(data), expire=3600):
                return response.json(10, '生成失败')
            # =================
            if userqs[0]['username']:
                share_user = userqs[0]['username']
            elif userqs[0]['userEmail']:
                share_user = userqs[0]['userEmail']
            elif userqs[0]['phone']:
                share_user = userqs[0]['phone']
            else:
                share_user = ''

            userIconPath = userqs[0]['userIconPath']
            if userIconPath:
                if userIconPath.find('static/') != -1:
                    userIconPath = userIconPath.replace('static/', '').replace('\\', '/')
                    userIconUrl = SERVER_DOMAIN + 'account/getAvatar/' + userIconPath

            return response.json(0, {
                'shareToken': share_token,
                'deviceName': dvqs[0]['NickName'],
                'shareUser': share_user,
                'userIconPath': userIconPath
            })

        else:
            return response.json(12)

    def do_show_share_info(self, request_dict, response):
        shareToken = request_dict.get('shareToken', None)
        if shareToken is not None:
            redisObj = RedisObject()
            data_str = redisObj.get_data(key=shareToken)
            if data_str:
                data = json.loads(data_str)
                # 分享者userID
                sharer = data.get('sharer', None)
                # 分享的uid
                UID = data.get('UID', None)
                sharerDvqs = Device_Info.objects.filter(userID_id=sharer, UID=UID, isShare=False). \
                    values('NickName', 'Type')
                if sharerDvqs.exists():
                    sharerDuqs = Device_User.objects.filter(userID=sharer).values('username', 'userEmail', 'phone')
                    if sharerDuqs[0]['username']:
                        share_user = sharerDuqs[0]['username']
                    elif sharerDuqs[0]['userEmail']:
                        share_user = sharerDuqs[0]['userEmail']
                    elif sharerDuqs[0]['phone']:
                        share_user = sharerDuqs[0]['phone']
                    else:
                        share_user = ''
                    return response.json(0, {
                        'deviceName': sharerDvqs[0]['NickName'],
                        'deviceType': sharerDvqs[0]['Type'],
                        'shareUser': share_user,
                    })
                else:
                    return response.json(173)
            else:
                return response.json(119)
        else:
            return response.json(414)

    def do_confirm(self, userID, request_dict, response):
        shareToken = request_dict.get('shareToken', None)
        if shareToken is not None:
            # try:
            #     data = jwt.decode(shareToken, '.#^^&', algorithms='HS256')
            # except Exception as e:
            #     return response.json(10, repr(e))
            redisObj = RedisObject()
            data_str = redisObj.get_data(key=shareToken)
            if not data_str:
                return response.json(119)
            data = json.loads(data_str)
            # 分享者userID
            sharer = data.get('sharer', None)
            # 分享的uid
            UID = data.get('UID', None)
            dval = Device_Info.objects.filter(userID_id=userID, UID=UID)
            if not dval.exists():
                try:
                    sharerUser = Device_User.objects.get(userID=sharer)
                    sharerDvqs = Device_Info.objects.get(userID_id=sharer, UID=UID)
                    deviceId = CommonService.getUserID(getUser=False)
                    sharerDvqs.id = deviceId
                    sharerDvqs.userID_id = userID
                    sharerDvqs.isShare = True
                    sharerDvqs.primaryUserID = sharer
                    if sharerUser.username:
                        primaryMaster = sharerUser.username
                    elif sharerUser.userEmail:
                        primaryMaster = sharerUser.userEmail
                    elif sharerUser.phone:
                        primaryMaster = sharerUser.phone
                    else:
                        return response.json(178)
                    print(primaryMaster)
                    sharerDvqs.primaryMaster = primaryMaster
                    sharerDvqs.data_joined = None
                    sharerDvqs.save()
                    # redisObj = RedisObject(db=8)
                    # redisObj.del_data(key='uid_qs_' + userID)
                except Exception as e:
                    return response.json(10, repr(e))
                else:
                    dvqs = Device_Info.objects.filter(id=deviceId).values('id', 'userID', 'NickName', 'UID',
                                                                          'View_Account',
                                                                          'View_Password', 'ChannelIndex', 'Type',
                                                                          'isShare',
                                                                          'primaryUserID', 'primaryMaster',
                                                                          'data_joined', 'version',
                                                                          'isVod', 'isExist')
                    dvql = CommonService.qs_to_list(dvqs)
                    ubqs = UID_Bucket.objects.filter(uid=UID). \
                        values('bucket__content', 'status', 'channel', 'endTime', 'uid')
                    res = dvql[0]
                    res['vod'] = list(ubqs)
                    # redisObj.del_data(key=shareToken)
                    return response.json(0, res)
            else:
                return response.json(174)
        else:
            return response.json(444, {'param': 'shareToken'})

    # 1,这个用户的分享出去的设备
    # 2,获得上面个的设备拥有者
    #  http://192.168.136.39:8000/deviceShare/queryEq?token=XXX&UID=jLBDSU9547NTRSMF111A
    def do_query_user(self, userID, request_dict, response):
        UID = request_dict.get('UID', None)
        if UID is not None:
            # 查询分享获得的用户
            qs = Device_Info.objects.filter(UID=UID, isShare=True, primaryUserID=userID, isExist=1). \
                values('userID__NickName', 'userID__username', 'userID__userEmail', 'userID__phone', 'id',
                       'userID__userIconPath')
            data = []
            # print(qs)
            for q in qs:
                d = {'id': q['id']}
                if q['userID__NickName']:
                    d['user'] = q['userID__NickName']
                elif q['userID__username']:
                    d['user'] = q['userID__username']
                elif q['userID__userEmail']:
                    d['user'] = q['userID__userEmail']
                elif q['userID__phone']:
                    d['user'] = q['userID__phone']
                userIconPath = q['userID__userIconPath']
                if userIconPath:
                    if userIconPath.find('static/') != -1:
                        userIconPath = userIconPath.replace('static/', '').replace('\\', '/')
                        d['userIconUrl'] = SERVER_DOMAIN + 'account/getAvatar/' + userIconPath
                data.append(d)
            return response.json(0, data)
        else:
            return response.json(444, {'param': 'UID'})

    def do_delete_user(self, userID, request_dict, response):
        id = request_dict.get('id', None)
        if id:
            try:
                # redisObj = RedisObject(db=8)
                # redisObj.del_data(key='uid_qs_' + userID)
                Device_Info.objects.filter(id=id, primaryUserID=userID).update(isExist=0)
            except Exception as e:
                return response.json(10, repr(e))
            else:
                return response.json(0)
        else:
            return response.json(444, 'id')

    def do_delete_userV2(self, userID, request_dict, response):
        ids = request_dict.get('ids', None)
        if id:
            try:
                # redisObj = RedisObject(db=8)
                # redisObj.del_data(key='uid_qs_' + userID)
                Device_Info.objects.filter(id__in=ids, primaryUserID=userID).update(isExist=0)
            except Exception as e:
                return response.json(10, repr(e))
            else:
                return response.json(0)
        else:
            return response.json(444, 'id')
