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

from django.db.models import Q
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt

from Model.models import UserModel
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.ModelService import ModelService


class UserView(View):

    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super(UserView, self).dispatch(request, *args, **kwargs)

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

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

    def validation(self, request_dict, operation):

        if operation == 'login':
            return self.login(request_dict)
        elif operation == 'logout':
            return self.logout(request_dict)
        else:
            token = request_dict.get('token', None)

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

            if operation == 'query':
                return self.do_query(request_dict)
            elif operation == 'modify':
                return self.do_modify_password(request_dict)
            elif operation == 'list':
                return self.do_list(request_dict)
            elif operation == 'adminAdd':
                return self.do_admin_add(token.userID, request_dict, response)
            elif operation == 'adminDelete':
                return self.do_admin_delete(token.userID, request_dict, response)
            elif operation == 'adminUpdate':
                return self.do_admin_update(token.userID, request_dict, response)
            elif operation == 'adminReset':
                return self.do_admin_reset(token.userID, request_dict, response)
            else:
                return ResponseObject().json(309)

    def login(self, request_dict):
        username = request_dict.get('username', None)
        password = request_dict.get('password', None)

        response = ResponseObject()

        if username is None or password is None:
            return response.json(444)

        user = UserModel.objects.filter(username=username)
        if user.exists():
            if user[0].password != password:
                return response.json(99)
            else:
                token = TokenObject()
                res = token.generate({'userID': user[0].id})
                res['permission'] = user[0].permission
                res['username'] = user[0].username
                user[0].online = 1
                update = {
                    'online': 1
                }
                user.update(**update)
                return response.json(0, res)
        else:
            return response.json(99)

    def do_query(self, request_dict):
        # print('do_query')
        token = TokenObject(request_dict.get('token', None))
        # page = request_dict.get('page', None)
        # line = request_dict.get('line', None)
        # username = request_dict.get('username', None)
        response = ResponseObject()

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

        # if username:
        #     user_qs = UserModel.objects.filter(username__icontains=username)
        #     if user_qs.exists():
        #         users = list(user_qs.values('username'))
        #         return response.json(0, {'data': users})
        #     else:
        #         return response.json(0, {'data': []})
        # elif page and line:
        #     print('query_page')
        #     user_qs = UserModel.objects.filter(id=token.userID)
        #     if user_qs.exists():
        #         user = user_qs[0]
        #         if user.permission == '0':
        #             return self.do_query_pagination(int(page), int(line), response)
        #         else:
        #             return response.json(404)
        #     else:
        #         return response.json(9)

        user_qs = UserModel.objects.filter(~Q(Q(permission='0'))).values('id', 'username')

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

    def do_query_pagination(self, page, line, response):
        # print('query start')
        user_qs = UserModel.objects.filter().values()
        if user_qs.exists():
            count = user_qs.count()
            start = (page - 1) * line
            end = start + line
            users = list(user_qs[start:end])
            # print('query end')
            return response.json(0, {'count': count, 'data': users})
        else:
            return response.json(0, {'count': 0, 'data': []})

    def do_modify_password(self, request_dict):
        token = request_dict.get('token', None)
        old_password = request_dict.get('oldPassword', None)
        new_password = request_dict.get('newPassword', None)
        token = TokenObject(token)

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

        if old_password and new_password:
            user_qs = UserModel.objects.filter(id=token.userID)
            if user_qs.exists():
                if user_qs[0].password != old_password:
                    return response.json(47)
                user = {
                    'password': new_password
                }
                user_qs.update(**user)
                return response.json(0)
            else:
                return response.json(9)
        else:
            return response.json(444)

    def logout(self, request_dict):
        token = request_dict.get('token', None)
        token = TokenObject(token)
        response = ResponseObject()
        if token.code != 0:
            return response.json(0)

        user_qs = UserModel.objects.filter(id=token.userID)
        if user_qs.exists():
            user = {
                'online': 0
            }
            user_qs.update(**user)
            return response.json(0)
        else:
            return response.json(0)

    def do_list(self, request_dict):
        token = request_dict.get('token', None)

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

        page = request_dict.get('page', None)
        line = request_dict.get('limit', None)

        if page and line:
            user_qs = UserModel.objects.filter()

            res = {
                'count': user_qs.count(),
                'data': []
            }
            if user_qs.exists():
                page = int(page)
                line = int(line)

                start = (page - 1) * line
                end = start + line

                user_qs = user_qs[start:end].values('id', 'username', 'permission', 'phone', 'login_time', 'add_time')

                res['data'] = list(user_qs)
            return response.json(0, res)
        else:
            return response.json(444)

    def do_admin_add(self, userID, request_dict, response):
        perm = ModelService.check_perm(userID, 0)
        if not perm:
            return response.json(309)

        print(request_dict)
        username = request_dict.get('username', None)
        password = request_dict.get('password', None)
        phone = request_dict.get('phone', None)
        role = request_dict.get('role', None)

        if username and password and role:
            user = UserModel()
            user.username = username
            user.password = password
            user.permission = role
            user.phone = phone
            user.add_time = int(time.time())
            user.save()
            return response.json(0)
        else:
            return response.json(444)

    def do_admin_delete(self, userID, request_dict, response):
        perm = ModelService.check_perm(userID, 0)
        if not perm:
            return response.json(309)

        username = request_dict.get('username', None)

        if username:
            user_qs = UserModel.objects.filter(username=username)
            if user_qs.exists():
                user_qs.delete()
                return response.json(0)
            else:
                return response.json(9)
        else:
            return response.json(444)

    def do_admin_update(self, userID, request_dict, response):
        perm = ModelService.check_perm(userID, 0)
        if not perm:
            return response.json(309)

        username = request_dict.get('username', None)
        role = request_dict.get('role', None)
        password = request_dict.get('password', None)
        phone = request_dict.get('phone', None)

        if username:
            update_data = {}

            if role:
                update_data['permission'] = role

            if password:
                update_data['password'] = password

            if phone:
                update_data['phone'] = phone

            UserModel.objects.filter(username=username).update(**update_data)
            return response.json(0)
        else:
            return response.json(444)

    def do_admin_reset(self, userID, request_dict, response):
        perm = ModelService.check_perm(userID, 0)
        if not perm:
            return response.json(309)

        username = request_dict.get('username', None)

        if username:
            user_qs = UserModel.objects.filter(username=username)
            if user_qs.exists():
                user_qs.update(password='123456')
                return response.json(0)
            else:
                return response.json(9)
        else:
            return response.json(444)