#!/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: 2021/07/06 11:17
@Version: python3.6
@MODIFY DECORD:ansjer dev
"""
import json
import time
import urllib
import uuid
import boto3
import threading
import logging
from boto3.session import Session
from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
from django.views.generic.base import View
from Model.models import Device_Info, Role, MenuModel
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Object.UidTokenObject import UidTokenObject
from Service.CommonService import CommonService
from django.db.models import Q, F, Max
from time import strftime


class RoleView(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):
        language = request_dict.get('language', 'en')
        response = ResponseObject(language, 'pc')
        if operation == '??':
            return 0
        else:
            tko = TokenObject(request.META.get('HTTP_AUTHORIZATION'),returntpye='pc')
            if tko.code != 0:
                return response.json(tko.code)
            response.lang = tko.lang
            userID = tko.userID
            if operation == 'getList':
                return self.getList(userID, request_dict, response)
            elif operation == 'doEdit':
                return self.doEdit(userID, request_dict, response)
            elif operation == 'doDelete':
                return self.doDelete(userID, request_dict, response)
            elif operation == 'getPerms':
                return self.getPerms(userID, request_dict, response)
            elif operation == 'setPerms':
                return self.setPerms(userID, request_dict, response)
            else:
                return response.json(404)

    def getList(self, userID, request_dict, response):
        isSelect = request_dict.get('isSelect', None)   # 获取全部数据作为角色选项
        if isSelect:
            role_qs = Role.objects.all().values('rid', 'roleName', 'Description')
            return response.json(0, {'list': CommonService.qs_to_list(role_qs)})

        roleName = request_dict.get('roleName', '')
        pageNo = request_dict.get('pageNo', None)
        pageSize = request_dict.get('pageSize', None)
        if not all([pageNo, pageSize]):
            return response.json(444)

        page = int(pageNo)
        line = int(pageSize)
        if roleName:
            role_qs = Role.objects.filter(roleName__contains=roleName).values('rid', 'roleName', 'Description')
        else:
            role_qs = Role.objects.all().values('rid', 'roleName', 'Description')

        count = role_qs.count()
        role_qs = role_qs.order_by('-rid')[(page - 1) * line:page * line]
        return response.json(0, {'list': CommonService.qs_to_list(role_qs), 'total': count})

    def doEdit(self, userID, request_dict, response):

        data_dict = request_dict.dict()
        # data_dict = json.loads(data_str)
        if 'rid' in data_dict:
            Role.objects.filter(rid=data_dict['rid']).update(**data_dict)
        else:
            id = Role.objects.all().aggregate(Max('rid'))['rid__max'] + 1
            data_dict['rid'] = id
            Role.objects.create(**data_dict)
        return response.json(0)

    def doDelete(self, userID, request_dict, response):
        rid = request_dict.get('rid', '')
        if not all([rid]):
            return response.json(444)
        Role.objects.filter(rid=rid).delete()
        return response.json(0)

    def getPerms(self, userID, request_dict, response):
        rid = request_dict.get('rid', '')

        if rid:
            role_qs = Role.objects.filter(rid=rid).values('menu__id')
            return response.json(0, CommonService.qs_to_list(role_qs))

        return response.json(0)

    def setPerms(self, userID, request_dict, response):
        rid = request_dict.get('rid', '')
        permsIds = request_dict.get('permsIds', '')
        if not all([rid]):
            return response.json(444)
        Role.objects.get(rid=rid).menu.clear()
        menu_obj = MenuModel.objects.filter(id__in=permsIds.split(','))
        Role.objects.filter(rid=rid)[0].menu.add(*menu_obj)
        return response.json(0)
