#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time

import oss2
from django.views.generic.base import View

from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET
from Model.models import AppLogModel
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService
from Service.ModelService import ModelService


class AppLogView(View):

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

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

    def validate(self, request_dict, operation):
        token = request_dict.get('token', None)
        response = ResponseObject()
        if token is None:
            return response.json(444)

        token = TokenObject(token)
        if token.code != 0:
            return response.json(token.code)

        if operation == 'getUploadUrl':
            return self.get_upload_url(token.userID, request_dict, response)
        elif operation == 'add':
            return self.do_add(token.userID, request_dict, response)
        elif operation == 'queryByAdmin':
            return self.do_query_by_admin(token.userID, request_dict, response)
        elif operation == 'deleteByAdmin':
            return self.do_delete_by_admin(token.userID, request_dict, response)
        elif operation == 'downloadByAdmin':
            return response.json(404)
        else:
            return response.json(414)

    def get_upload_url(self, userID, request_dict, response):
        upload_type = request_dict.get('upload_type', None)
        if upload_type:
            auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
            bucket = oss2.Bucket(auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')
            name = CommonService.createOrderID()
            filename = str(name) + '.' + upload_type
            obj = 'app_log/{userID}/'.format(userID=userID) + filename

            url = bucket.sign_url('PUT', obj, 7200)
            return response.json(0, {'put_url': url, 'filename': filename})
        else:
            return response.json(444)

    def do_add(self, userID, request_dict, response):
        uid = request_dict.get('uid', None)
        average_delay = request_dict.get('average_delay', None)
        status = request_dict.get('status', None)
        filename = request_dict.get('filename', None)

        if uid is None or average_delay is None or status is None or filename is None:
            return response.json(444)
        else:
            if len(uid) < 20:
                return response.json(444, 'uid')

            # ModelService.app_log_log(userID, uid)
            now_time = int(time.time())
            uid = uid.strip()
            data = {
                'uid': uid[0:20],
                'average_delay': average_delay,
                'status': status,
                'filename': filename,
                'add_time': now_time,
                'user_id': userID,
            }
            AppLogModel.objects.create(**data)
            return response.json(0)

    def do_query_by_admin(self, userID, request_dict, response):
        own_perm = ModelService.check_perm(userID, 30)
        if own_perm:
            page = request_dict.get('page', None)
            line = request_dict.get('line', None)
            status = request_dict.get('status', None)
            uid = request_dict.get('uid', None)

            if page and line:
                page = int(page)
                line = int(line)
                filter_data = {}
                if status:
                    filter_data['status'] = status
                if uid:
                    filter_data['uid'] = uid

                al_qs = AppLogModel.objects.filter(**filter_data).order_by('-add_time')

                if al_qs.exists():
                    count = al_qs.count()
                    start = (page - 1) * line
                    al_qs = al_qs[start: (start + line)].values('id', 'user__username', 'user_id', 'uid',
                                                                'average_delay', 'status', 'filename', 'add_time')

                    res = []
                    auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
                    bucket = oss2.Bucket(auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')
                    for al in al_qs:
                        filename = al['filename']
                        obj = 'app_log/' + al['user_id'] + '/' + filename
                        url = bucket.sign_url('GET', obj, 3600)
                        al['url'] = url
                        del al['filename']
                        res.append(al)

                    return response.json(0, {'datas': res, 'count': count})
                else:
                    return response.json(0, {'datas': [], 'count': 0})
            else:
                return response.json(444, 'page, line')
        else:
            return response.json(404)

    def do_delete_by_admin(self, userID, request_dict, response):
        own_perm = ModelService.check_perm(userID, 10)
        if own_perm:
            id = request_dict.get('id', None)
            if id:
                try:
                    AppLogModel.objects.filter(id=id).delete()
                except Exception as e:
                    print(repr(e))
                    return response.json(500, repr(e))
                else:
                    return response.json(0)
            else:
                return response.json(444)
        else:
            return response.json(404)

