#!/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
from time import strftime


class MenuView(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)
            if operation == 'doEdit':
                return self.doEdit(userID, request_dict, response)
            if operation == 'doDelete':
                return self.doDelete(userID, request_dict, response)
            else:
                return response.json(404)

    def getList(self, userID, request_dict, response):
        menu_qs = MenuModel.objects.filter(parentId=0)
        list = []
        for menu in menu_qs:
            list.append(
                {
                    'id': menu.id,
                    'parentId': menu.parentId,
                    'path': menu.path,
                    'name': menu.name,
                    'component': menu.component,
                    'menutype': menu.menutype,
                    'menu_code': menu.menu_code,
                    'meta': {
                        'hidden': menu.hidden,
                        'levelHidden': menu.levelHidden,
                        'title': menu.title,
                        'icon': menu.icon,
                        'isCustomSvg': menu.isCustomSvg,
                        'noKeepAlive': menu.noKeepAlive,
                        'noClosable': menu.noClosable,
                        'badge': menu.badge,
                        'tabHidden': menu.tabHidden,
                        'activeMenu': menu.activeMenu,
                        'dot': menu.dot,
                        'dynamicNewTab': menu.dynamicNewTab,
                        'sort': menu.sort
                    }
                }
            )
        menu_qs = MenuModel.objects.filter()
        menulist = []
        for objlist in list:
            menulist.append(self.menulist(menu_qs, objlist))

        return response.json(0, {'list': menulist})

    def menulist(self, menu_qs, objlist):
        if objlist is None:
            return
        for menu in menu_qs:
            if objlist['id'] == menu.parentId:
                if 'children' not in objlist:
                    objlist['children'] = []

                obj = {
                    'id': menu.id,
                    'parentId': menu.parentId,
                    'path': menu.path,
                    'name': menu.name,
                    'component': menu.component,
                    'menutype': menu.menutype,
                    'menu_code': menu.menu_code,
                    'meta': {
                        'hidden': menu.hidden,
                        'levelHidden': menu.levelHidden,
                        'title': menu.title,
                        'icon': menu.icon,
                        'isCustomSvg': menu.isCustomSvg,
                        'noKeepAlive': menu.noKeepAlive,
                        'noClosable': menu.noClosable,
                        'badge': menu.badge,
                        'tabHidden': menu.tabHidden,
                        'activeMenu': menu.activeMenu,
                        'dot': menu.dot,
                        'dynamicNewTab': menu.dynamicNewTab,
                        'sort': menu.sort
                    }
                }
                objlist['children'].append(
                    obj
                )
                self.menulist(menu_qs, obj)

        return objlist

    def doEdit(self, userID, request_dict, response):
        print('request_dict: ', request_dict)
        data_dict = CommonService.request_dict_to_dict(request_dict)

        if data_dict['isEdit']:
            # data_dict.index(76)
            data_dict.pop('isEdit')
            keys = ['parentId', 'name', 'path', 'component', 'hidden', 'alwaysShow', 'levelHidden', 'title', 'icon',
                    'isCustomSvg', 'noKeepAlive', 'badge', 'tabHidden', 'activeMenu', 'dot', 'dynamicNewTab',
                    'redirect', 'menu_code', 'menutype', 'sort']
            data = {}
            for key in keys:
                if key in data_dict:
                    data[key] = data_dict[key]

            MenuModel.objects.filter(id=data_dict['id']).update(**data)
        else:
            data_dict.pop('isEdit')
            MenuModel.objects.create(**data_dict)
        return response.json(0)

    def doDelete(self, userID, request_dict, response):
        id = request_dict.get('id', '')
        MenuModel.objects.filter(id=id).delete()
        return response.json(0)