# 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 and tenant != request.user.employee.tenant:
            data = {
                'company_no':tenant.company_no,
                'company_name':tenant.company_name,
            }
            return response_ok(data)
        else:
            return response_ok()

class GetTenantView(APIView):
    permission_classes = [isLogin]

    def get(self, request, *args, **kwargs):
        emplayee = Employee.objects.filter(user=request.user).first()
        if emplayee:
            data = {
                'tenant_id':emplayee.tenant.id,
                'company_no':emplayee.tenant.company_no,
                'company_name':emplayee.tenant.company_name,
                'position':emplayee.position,
                'wxapp_img':emplayee.tenant.wxapp_img,
                '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):
        # 绑定企业,pk 企业编号
        try:
            is_validity = Tenant.check_validity(pk)
            if not is_validity:
                raise CustomError('该企业认证已过期，请联系管理员续费！')
            user = self.request.user
            if user.type == Employee.SUPER:
                raise CustomError('您是企业超级管理员，不能绑定其他企业！')
            with transaction.atomic():
                user = self.request.user
                user.type = Employee.REPAIR
                user.save()
                tenant = Tenant.getByNo(pk)
                Employee.objects.filter(user=user).update(tenant=tenant, type=Employee.REPAIR,position='报修人')
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok('绑定成功！')
