# coding=utf-8
from django.conf import settings
from utils.custom_modelviewset import CustomModelViewSet
from utils.permission import IsAdministratorUser
from apps.tenant.models import Tenant
from apps.tenant.employee.models import Employee
from apps.admin import admin_log
from apps.log.models import BizLog
from .serializers import TenantSerializer
from django.db import transaction
from utils import response_ok
from utils.exceptions import CustomError
from rest_framework.decorators import action
from utils import response_ok, response_error
from apps.account.models import User
from .filters import TenantFilter

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

    def filter_queryset(self, queryset):
        f = TenantFilter(self.request.GET, queryset=queryset)
        return f.qs

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

    def perform_update(self, serializer):
        super(TenantViewSet, self).perform_update(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        admin_log(self.request.user, BizLog.INSERT, u'修改租户[%s] id=%d' % (instance.name, instance.id), validated_data)

    @action(methods=['post'], detail=True)
    def super_tenant(self,  request, pk):
        name = request.POST.get('name')
        username = request.POST.get('username')
        password = request.POST.get('password')
        try:
            with transaction.atomic():
                tenant = Tenant.objects.filter(pk=pk).first()
                if not tenant:
                    raise CustomError('当前租户无效，请刷新！')
                user = User.objects.filter(username=username).first()
                if user:
                    user.type = User.SUPER
                    user.save()
                    Employee.objects.filter(user=user).update(tenant=tenant, type=Employee.SUPER)
                else:
                    instance = Employee.create_super_admin(tenant, name, username, password)
                admin_log(request.user, BizLog.INSERT, u'租户[%s]添加超级账号[%s], id=%d' % (tenant.company_name,username, instance.id))
            return response_ok()
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))

    @action(methods=['post'], detail=True)
    def check(self, request, pk):
        # 审核
        status = request.POST.get('status')
        reject_reason = request.POST.get('reason')
        try:
            with transaction.atomic():
                instance = Tenant.getById(pk)
                # 审核
                if instance.status > settings.DEFAULT:
                    raise CustomError('当前租户已审核！')

                instance.status = status
                instance.reject_reason = reject_reason
                instance.save()
                BizLog.objects.addnew(None, request.user, BizLog.INSERT, u'审核租户[%s]状态为[%s],id=%d' % (instance.company_name, status, instance.id))
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok('审核完成！')
