#!/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/13 17:35
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: UIDPreview.py
@Contact: chanjunkai@163.com
"""
# !/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: 2018/12/6 10:53
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: OrderContrller.py
@Contact: chanjunkai@163.com
"""
import time

import oss2
from django.views.generic.base import View
from Object.RedisObject import RedisObject
from Ansjer.config import OSS_STS_ACCESS_SECRET, OSS_STS_ACCESS_KEY
from Model.models import UID_Preview, Device_Info
from Object.ResponseObject import ResponseObject
from Service.ModelService import ModelService
from Object.TokenObject import TokenObject


# 设备信息添加
class UIDPreview(View):

    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()
        token = request_dict.get('token', None)
        # 设备主键uid
        tko = TokenObject(token)
        if tko.code == 0:
            response.lang = tko.lang
            userID = tko.userID
            if operation == 'add':
                return self.do_add(userID, request_dict, response)
            if operation == 'adminQuery':
                return self.do_admin_query(request_dict, userID, response)
            if operation == 'adminDelete':
                return self.do_admin_delete(request_dict, userID, response)
            else:
                return response.json(414)
        else:
            return response.json(tko.code)

    def do_add(self, userID, request_dict, response):
        nowTime = int(time.time())
        uid = request_dict.get('uid', None)
        channel = request_dict.get('channel', None)
        if all([uid, channel]):
            # auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
            # bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
            auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
            bucket = oss2.Bucket(auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')

            dvqs = Device_Info.objects.filter(UID=uid, userID_id=userID)
            # redisObj = RedisObject(db=8)
            # redisObj.del_data(key='uid_qs_'+userID)
            upqs = UID_Preview.objects.filter(uid=uid, channel=channel)
            if dvqs.exists():
                if upqs.exists():
                    try:
                        is_update = upqs.update(updTime=nowTime)
                    except Exception as e:
                        print(repr(e))
                        return response.json(177)
                    else:
                        if is_update:
                            obj = 'uid_preview/{uid}/channel_{channel}.png'.format(uid=uid, channel=channel)
                            # 设置此签名URL在60秒内有效。
                            url = bucket.sign_url('PUT', obj, 7200)
                            return response.json(0, url)
                        else:
                            return response.json(177)
                else:
                    create_data = {
                        'addTime': nowTime,
                        'updTime': nowTime,
                        'uid': uid,
                        'channel': channel
                    }
                    try:
                        UID_Preview.objects.create(**create_data)
                    except Exception as e:
                        print(repr(e))
                        return response.json(178)
                    else:
                        obj = 'uid_preview/{uid}/channel_{channel}.png'.format(uid=uid, channel=channel)
                        # 设置此签名URL在60秒内有效。
                        url = bucket.sign_url('PUT', obj, 7200)
                        return response.json(0, url)
            else:
                return response.json(14)
        else:
            return response.json(444, 'uid,channel')
    # 管理员查询接口
    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)
            uid = request_dict.get('uid', None)
            channel = request_dict.get('channel', None)
            page = int(page)
            line = int(line)
            omqs = UID_Preview.objects.filter()
            # 筛选指定设备id的订单
            if uid:
                omqs = omqs.filter(uid=uid)
            if channel:
                omqs = omqs.filter(channel=channel)
            if not omqs.exists():
                return response.json(0, [])
            count = omqs.count()
            order_ql = omqs[(page - 1) * line:page * line].values("id", "uid", "channel", "addTime", "updTime")
            order_list = list(order_ql)
            return response.json(0, {'data': order_list, 'count': count})
        else:
            return response.json(404)

    def do_admin_delete(self, request_dict, userID, response):
        own_perm = ModelService.check_perm(userID, 20)
        if own_perm is True:
            id = request_dict.get('id')
            # redisObj = RedisObject(db=8)
            # redisObj.del_data(key='uid_qs_' + userID)
            UID_Preview.objects.filter(id=id).delete()
            return response.json(0)
        else:
            return response.json(404)