# coding=utf-8
from django.conf import settings
from django.db import transaction
from rest_framework.views import APIView
from rest_framework.decorators import action
from utils.custom_modelviewset import CustomModelViewSet
from apps.log.models import BizLog
from apps.tenant.models import Tenant
from .serializers import TenantSerializer
from utils.exceptions import CustomError
from utils import response_ok, response_error
from apps.tenant.employee.models import Employee
from utils.permission import isLogin

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

    def get(self, request, *args, **kwargs):
        company_no = request.GET.get('company_no')
        tenant = Tenant.objects.filter(company_no=company_no, status=settings.PASS).first()
        if tenant:
            data = {
                'id':tenant.id,
                'company_name':tenant.company_name,
            }
            return response_ok(data)
        else:
            return response_error(u'未找到企业，请输入正确的企业编号')

class GetTenantView(APIView):
    permission_classes = [isLogin]

    def get(self, request, *args, **kwargs):
        emplayee = Employee.objects.filter(user=request.user).first()
        if emplayee:
            data = {
                'company_name':emplayee.tenant.company_name,
                'position':emplayee.position,
                'user_type_text':emplayee.get_type_display(),
            }
            return response_ok(data)
        else:
            return response_ok()

class TenantViewSet(CustomModelViewSet):
    permission_classes = [isLogin, ]
    queryset = Tenant.objects.all()
    serializer_class = TenantSerializer

    def perform_create(self, serializer):
        super(TenantViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(instance, self.request.user, BizLog.INSERT, u'申请租户[%s] id=%d' % (instance.company_name, instance.id), validated_data)

    @action(methods=['get'], detail=True)
    def bind_company(self, request, pk):
        # 绑定企业
        try:
            with transaction.atomic():
                user = self.request.user
                tenant = Tenant.getById(pk)
                Employee.objects.filter(user=user).update(tenant=tenant)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok('绑定成功！')
