#!/usr/bin/env python3  
# -*- coding: utf-8 -*-  
"""
@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
@AUTHOR: ASJRD018
@NAME: langer
@software: PyCharm
@DATE: 2019/6/3 17:29
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: User.py
@Contact: chanjunkai@163.com
"""
import json
from django.http import HttpResponse

from django.views.generic import TemplateView
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from object.ResponseObject import ResponseObject
from django.contrib.auth.hashers import make_password, check_password
from model.models import UserModel, LangSetModel, LangAreaModel, LangPermModel, ProjectPermModel, LangProjectModel
import time
from object.TokenObject import TokenObject


class registerView(TemplateView):
    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = json.loads(request.body.decode('utf-8'))
        return self.validate(request_dict)

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

    def validate(self, request_dict):
        response = ResponseObject()
        username = request_dict.get('username', None)
        password = request_dict.get('password', None)
        role_id = request_dict.get('role_id', None)
        if username and password:
            nowTime = int(time.time())
            create_dict = {
                'username': username,
                'password': make_password(password),
                'role_id': role_id,
                'addTime': nowTime,
                'updTime': nowTime}
            try:
                UserModel.objects.create(**create_dict)
            except Exception as e:
                return response.json(0, repr(e))
            else:
                return response.json(0)
        else:
            return response.json(444)


class loginView(TemplateView):
    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = json.loads(request.body.decode('utf-8'))
        return self.validate(request_dict)

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

    def validate(self, request_dict):
        response = ResponseObject()
        username = request_dict.get('username', None)
        password = request_dict.get('password', None)
        if username and password:
            user_qs = UserModel.objects.filter(username=username)
            pp_qs = ProjectPermModel.objects.filter(user__id=user_qs[0].id).values('project__id')
            pp_data = []
            for pp in pp_qs:
                pp_data.append(pp['project__id'])

            print('login')
            if not user_qs.exists():
                return response.json(401)
            if check_password(password, user_qs[0].password):
                tko = TokenObject()
                res = tko.generate({'userID': user_qs[0].id})
                res['role_id'] = user_qs[0].role_id
                res['role_type'] = user_qs[0].role_type
                res['project_perm'] = pp_data
                print(res)

                return response.json(0, res)
            else:
                return response.json(401)
        else:
            return response.json(444)


class queryView(TemplateView):
    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = json.loads(request.body.decode('utf-8'))
        return self.validate(request_dict)

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

    def validate(self, request_dict):
        response = ResponseObject()
        token = request_dict.get('token', None)
        tko = TokenObject(token)
        if tko.code == 0:
            userID = tko.userID
            user_qs = UserModel.objects.filter(id=userID, username='admin')
            if not user_qs.exists():
                return response.json(403)
            um_qs = UserModel.objects.filter().values('id', 'username', 'role_id')

            ls_qs = LangSetModel.objects.filter().values('user__id', 'lang__lang')
            lp_qs = LangPermModel.objects.filter().values('user__id', 'lang__lang')
            pp_qs = ProjectPermModel.objects.filter().values('user__id', 'project__name')
            res = []
            for um in um_qs:
                for ls in ls_qs:
                    if um['id'] == ls['user__id']:
                        if 'lang_arr' not in um:
                            um['lang_arr'] = []
                        um['lang_arr'].append(ls['lang__lang'])
                for lp in lp_qs:
                    if um['id'] == lp['user__id']:
                        if 'lp_arr' not in um:
                            um['lp_arr'] = []
                        um['lp_arr'].append(lp['lang__lang'])
                for pp in pp_qs:
                    if um['id'] == pp['user__id']:
                        if 'pp_arr' not in um:
                            um['pp_arr'] = []
                        um['pp_arr'].append(pp['project__name'])
                res.append(um)
            return response.json(0, res)
        else:
            return response.json(tko.code)


class updateView(TemplateView):
    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = json.loads(request.body.decode('utf-8'))
        return self.validate(request_dict)

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

    def validate(self, request_dict):
        response = ResponseObject()
        token = request_dict.get('token', None)
        id = request_dict.get('id', None)
        langSetArr = request_dict.get('langSetArr', None)
        langPermArr = request_dict.get('langPermArr', None)
        username = request_dict.get('username', None)
        role_id = request_dict.get('role_id', None)
        projectPermArr = request_dict.get('projectPermArr', None)
        nowTime = int(time.time())
        tko = TokenObject(token)
        if tko.code == 0:
            user = UserModel.objects.get(id=id)
            user.username = username
            user.role_id = role_id
            user.updTime = nowTime
            user.save()
            if id and langSetArr:
                LangSetModel.objects.filter(user__id=id).delete()
                LangPermModel.objects.filter(user__id=id).delete()
                ProjectPermModel.objects.filter(user__id=id).delete()
                for ls in langSetArr:
                    LangSetModel.objects.create(lang=LangAreaModel.objects.get(id=ls),
                                                user=UserModel.objects.get(id=id), addTime=nowTime, updTime=nowTime)
                for lp in langPermArr:
                    LangPermModel.objects.create(lang=LangAreaModel.objects.get(id=lp),
                                                 user=UserModel.objects.get(id=id), addTime=nowTime, updTime=nowTime)
                for pp in projectPermArr:
                    ProjectPermModel.objects.create(project=LangProjectModel.objects.get(id=pp),
                                                    user=UserModel.objects.get(id=id))
                return response.json(0)
            else:
                return response.json(0)
        else:
            return response.json(tko.code)


class deleteView(TemplateView):
    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = json.loads(request.body.decode('utf-8'))
        return self.validate(request_dict)

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

    def validate(self, request_dict):
        response = ResponseObject()
        token = request_dict.get('token', None)
        tko = TokenObject(token)
        if tko.code == 0:
            id = request_dict.get('id', None)
            if id:
                UserModel.objects.filter(id=id).delete()
                return response.json(0)
            else:
                return response.json(0)
        else:
            return response.json(tko.code)


class initView(TemplateView):
    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = json.loads(request.body.decode('utf-8'))
        return self.validate(request_dict)

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

    def validate(self, request_dict):
        response = ResponseObject()
        token = request_dict.get('token', None)
        tko = TokenObject(token)
        if tko.code == 0:
            userID = tko.userID
            user_qs = UserModel.objects.filter(id=userID, username='admin')
            if user_qs.exists():
                is_admin = 1
            else:
                is_admin = 0
            lang_perm_ql = LangPermModel.objects.filter(user__id=userID).values_list('lang__lang', flat=True)
            lang_perm_ls = list(lang_perm_ql)
            res = {
                'user_perm':is_admin,
                'lang_perm_ls': lang_perm_ls
            }
            return response.json(0, res)
        else:
            return response.json(tko.code)
