#coding=utf-8
import traceback
import json
from django.db.models import Q
from rest_framework.decorators import action
from django.db import transaction
from rest_framework.views import APIView
from rest_framework.serializers import ValidationError
from utils.permission import permission_required, isLogin, check_permission
from django.contrib.auth.models import Group, Permission
from rest_framework_jwt.views import ObtainJSONWebToken,VerifyJSONWebToken,RefreshJSONWebToken
from utils import response_error, response_ok
from django.contrib.auth import get_user_model
User = get_user_model()
from apps.account.serializers import JWTSerializer, EmployeeSerializer, GroupDictSerializer, GroupSerializer
from utils.custom_modelviewset import CustomModelViewSet
from apps.account.filters import UserFilter, GroupFilter
from apps.account.models import ManageStoreUser
from apps.log.models import BizLog
from apps.account.consts import PermissionMenu
from collections import OrderedDict
from apps.agent.models import Store, Agent

class LoginView(ObtainJSONWebToken):
    serializer_class = JWTSerializer

    def post(self, request, *args, **kwargs):
        try:
            ser = self.serializer_class(data=request.data)
            ser.request = request
            if ser.is_valid(raise_exception=True):
                return response_ok(ser.validated_data)
        except ValidationError as e:
            return response_error(e.detail['error'][0])

class RefreshTokenView(RefreshJSONWebToken):
    def post(self, request, *args, **kwargs):
        try:
            ser = self.serializer_class(data=request.data)
            if ser.is_valid(raise_exception=True):
                return response_ok({'token': ser.validated_data['token']})
        except ValidationError as e:
            return response_error(u'登录状态失效，请重新登录')

class EmployeeViewSet(CustomModelViewSet):
    permission_classes = [isLogin, ]
    queryset = User.objects.filter()
    serializer_class = EmployeeSerializer

    @permission_required('account.browse_user')
    def filter_queryset(self, queryset):
        queryset = queryset.filter()
        user = self.request.user
        queryset = queryset.filter(
            Q(store_id__in=self.request.user.get_manager_range()) |
            Q(id=user.id) |
            Q(create_user=user))

        f = UserFilter(self.request.GET, queryset=queryset)
        return f.qs

    @permission_required('account.add_user')
    def perform_create(self, serializer):
        super(EmployeeViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(self.request.user, BizLog.INSERT,
                              u'添加用户[%s]，id=%d' % (instance.name, instance.id), validated_data)

    @permission_required('account.add_user')
    def perform_update(self, serializer):
        super(EmployeeViewSet, self).perform_update(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(self.request.user, BizLog.UPDATE,
                              u'修改用户[%s]，id=%d' % (instance.name, instance.id), validated_data)

    @permission_required('account.delete_user')
    def perform_destroy(self, instance):
        ManageStoreUser.objects.filter(manage_user=instance).delete()
        BizLog.objects.filter(user=instance).delete()
        BizLog.objects.addnew(self.request.user, BizLog.DELETE,
                              u'删除账号[%s]，id=%d' % (instance.username, instance.id))
        super(EmployeeViewSet, self).perform_destroy(instance)

    @action(methods=['post'], detail=True)
    def join(self, request, pk):
        check_permission(request, 'account.check_user')
        try:
            with transaction.atomic():
                instance = self.get_object()
                instance.check_user = request.user
                instance.status = User.INSERVICE
                instance.save()
                BizLog.objects.addnew(self.request.user, BizLog.INSERT,
                                      u'员工[%s]入职，id=%d' % (instance.name, instance.id))
            return response_ok()
        except Exception as e:
            traceback.print_exc()
            return response_error(u'入职失败')

    @permission_required('account.manager_store')
    @action(methods=['post'], detail=True)
    def branch(self, request, pk):
        data = json.loads(request.POST.get('sotres'))
        try:
            with transaction.atomic():
                instance = self.get_object()
                ManageStoreUser.objects.filter(manage_user_id=pk).delete()
                for row in data:
                    ManageStoreUser.objects.create(store_id=row, manage_user_id=pk)
                BizLog.objects.addnew(self.request.user, BizLog.INSERT,
                                      u'设置账号[%s]管理门店，id=%d' % (instance.username, instance.id),data)
            return response_ok()
        except Exception as e:
            traceback.print_exc()
            return response_error(u'保存失败')

class GroupsViewSet(CustomModelViewSet):
    permission_classes = [isLogin, ]
    queryset = Group.objects.filter()
    serializer_class = GroupSerializer

    @permission_required('account.manager_permissions')
    def filter_queryset(self, queryset):
        if not self.request.user.is_superuser:
            groups =  self.request.user.groups.all()
            queryset =queryset.filter(id__in=[g.id for g in groups])
        f = GroupFilter(self.request.GET, queryset=queryset)
        return f.qs

    @permission_required('account.manager_permissions')
    def perform_create(self, serializer):
        super(GroupsViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(self.request.user, BizLog.INSERT,
                              u'添加权限组[%s]，id=%d' % (instance.name, instance.id), validated_data)

    @permission_required('account.manager_permissions')
    def perform_update(self, serializer):
        super(GroupsViewSet, self).perform_update(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(self.request.user, BizLog.UPDATE,
                              u'修改权限组[%s]，id=%d' % (instance.name, instance.id), validated_data)

    @permission_required('account.manager_permissions')
    def destroy(self, request, *args, **kwargs):
        with transaction.atomic():
            instance = self.get_object()
            # user_count = instance.user_set.all().count()
            # if user_count:
            #     raise CustomError(u'该权限组已分配给用户，禁止删除！')

            BizLog.objects.addnew(self.request.user, BizLog.DELETE,
                                  u'删除权限组[%s]，id=%d' % (instance.name, instance.id))
            instance.delete()
        return response_ok()

class PermissionsListView(APIView):
    permission_classes = [isLogin, ]

    @permission_required('account.manager_permissions')
    def get(self, request):
        rows = Permission.objects.all().exclude(name__startswith='Can')
        perms_menus = PermissionMenu()
        rows = perms_menus.sort_perms(rows)
        menus = OrderedDict()
        for row in rows:
            item = {'id': row.id, 'name': row.name}
            mn = perms_menus.get_menuname_of_contenttype(row.content_type.app_label, row.content_type.model)
            if mn in menus:
                permissions = menus[mn]
            else:
                permissions = menus[mn] = OrderedDict()
            if row.content_type.name in permissions:
                if not item in permissions[row.content_type.name]:
                    permissions[row.content_type.name].append(item)
            else:
                permissions[row.content_type.name] = [item, ]
        return response_ok(menus)

class PermissionDictView(APIView):
    permission_classes = [isLogin, ]

    @permission_required('account.add_user')
    def get(self, request):
        rows = Group.objects.filter()
        if not request.user.is_superuser:
            groups = request.user.groups.all()
            rows =rows.filter(id__in=[g.id for g in groups])
        serializer = GroupDictSerializer(rows, many=True)
        return response_ok(serializer.data)


class StoreTreeView(APIView):
    permission_classes = [isLogin, ]

    @permission_required('account.manager_store')
    def get(self, request):
        id = request.GET.get('id')
        store_data = []

        # 查询当前用户的代理商和管理的门店
        agents = Agent.objects.filter()
        if not request.user.is_superuser:
            agents = agents.filter(id=request.user.agent_id)
        agents = agents.values('id','name')
        for agent in agents:
            item = {
                'title':agent['name'],
                'id':agent['id'],
                'field':'agent',
                'children': [],
            }
            stores = Store.objects.filter(agent_id=agent['id'], enable=True).values('id','name')
            for store in stores:
                manage_store = ManageStoreUser.objects.filter(manage_user_id=id, store_id=store['id']).first()
                checked = manage_store and True or False
                store_item = {
                    'title': store['name'],
                    'id': store['id'],
                    'checked': checked,
                    'field': 'store_{}'.format(store['id']),
                }
                item['checked'] = checked
                item['children'].append(store_item)
            store_data.append(item)

        return response_ok(store_data)
