# coding=utf-8
import json
from rest_framework.decorators import action
from rest_framework_jwt.views import ObtainJSONWebToken,VerifyJSONWebToken,RefreshJSONWebToken
from rest_framework.serializers import ValidationError
from utils.custom_modelviewset import CustomModelViewSet
from utils import response_error, response_ok
from .serializers import TenantJWTSerializer
from utils.permission import IsTenantUser, IsAdministratorUser
from .models import Tenant
from apps.admin.tenant.serializers import TenantSerializer
from apps.admin.tenant.filters import TenantFilter
from apps.log.models import BizLog

class TenantLoginView(ObtainJSONWebToken):
    serializer_class = TenantJWTSerializer

    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 TenantVerifyTokenView(VerifyJSONWebToken):
    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'登录状态失效，请重新登录[' + e.detail['error'][0] + ']')


class TenantRefreshTokenView(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'登录状态失效，请重新登录[' + e.detail['error'][0] + ']')

class CompanyViewSet(CustomModelViewSet):
    permission_classes = [IsAdministratorUser,]
    queryset = Tenant.objects.filter(delete=False)
    serializer_class = TenantSerializer

    def filter_queryset(self, queryset):
        queryset = queryset.filter(id=self.request.user.employee.tenant.id)
        f = TenantFilter(self.request.GET, queryset=queryset)
        return f.qs

    @action(methods=['post'], detail=True)
    def update_company(self,request,pk):
        name = request.POST.get('name')
        tel = request.POST.get('tel')
        Tenant.objects.filter(id=pk).update(name=name,tel=tel)
        BizLog.objects.addnew(self.request.user.employee.tenant, self.request.user, BizLog.INSERT, u'修改企业联系人，id=%s' % pk, request.POST)
        return response_ok()
