# coding=utf-8

from utils.custom_modelviewset import CustomModelViewSet
from rest_framework.views import APIView
from django.db.models import Q
import traceback
from .models import Building
from utils.permission import IsTenantUser, permission_required
from .serializer import BuildingSerializer
from apps.log.models import BizLog
from apps.tenant import tenant_log
from .filters import BuildingFilter
from django.db import transaction
from utils.exceptions import CustomError
from utils import response_ok, response_error
from .resources import BuildingImporter
from apps.tenant.area.models import Area

class LocationSearch(APIView):
    permission_classes = [IsTenantUser, ]

    def get(self, request):
        keyword = request.GET.get('keywords')
        tenant = request.user.employee.tenant
        rows = Building.objects.filter(area__tenant=tenant)
        if keyword:
            rows = rows.filter(
                Q(building__icontains=keyword) |
                Q(location__icontains=keyword) |
                Q(floor__icontains=keyword)
            )
        serializer = BuildingSerializer(rows, many=True)
        return response_ok(serializer.data)

class BuildingViewSet(CustomModelViewSet):
    permission_classes = [IsTenantUser, ]
    queryset = Building.objects.filter()
    serializer_class = BuildingSerializer

    @permission_required('building.browse_building')
    def filter_queryset(self, queryset):
        queryset = queryset.filter(area__tenant=self.request.user.employee.tenant)
        f = BuildingFilter(self.request.GET, queryset=queryset)
        return f.qs

    @permission_required('building.add_building')
    def perform_create(self, serializer):
        super(BuildingViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        tenant_log(self.request.user.employee, BizLog.INSERT, u'添加建筑信息[%s]，id=%d' % (instance.building, instance.id),
                   validated_data)

    @permission_required('building.add_building')
    def perform_update(self, serializer):
        super(BuildingViewSet, self).perform_update(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        tenant_log(self.request.user.employee, BizLog.UPDATE, u'修改建筑信息[%s]，id=%d' % (instance.building, instance.id),
                   validated_data)

    @permission_required('building.delete_building')
    def destroy(self, request, *args, **kwargs):
        with transaction.atomic():
            instance = self.get_object()
            if instance.area.tenant != request.user.employee.tenant:
                raise CustomError(u'禁止跨租户操作！')
            super(BuildingViewSet,self).destroy(self, request, *args, **kwargs)
            tenant_log(self.request.user.employee, BizLog.DELETE, u'删除建筑信息[%s]，id=%d' % (instance.building, instance.id))
        return response_ok()

class BuildingImportView(APIView):
    permission_classes = [IsTenantUser, ]

    def post(self, request):
        if not request.user.has_perm('building.add_building'):
            raise CustomError(u"您没有[建筑信息-添加]权限，无法执行该操作，请联系管理员分配权限！")
        file = request.FILES.get('excel_file')
        try:
            line = 2
            importer = BuildingImporter()
            excel_rows = importer.getExcelData(file)
            with transaction.atomic():
                for excel_row in excel_rows:
                    try:
                        row = importer.validRow(excel_row)
                        area_name = row[u'区域']
                        area = Area.objects.filter(tenant=request.user.employee.tenant,name=area_name).first()
                        if not area :
                            raise CustomError(u'第%d行区域名称不正确:%s' % (line, area_name))
                        data = {}
                        data['area'] = area
                        data['building'] = row[u'楼宇']
                        data['floor'] = row[u'楼层']
                        data['location'] = row[u'地点']
                        data['create_user'] = request.user
                        Building.objects.create(**data)
                    except CustomError as e:
                        raise CustomError(u'第%d行:%s' % (line, e.get_error_msg()))
                    except Exception as e:
                        raise CustomError(u'第%d行:%s' % (line, str(e)))
                    line += 1
                tenant_log(self.request.user.employee, BizLog.IMPORT, u"导入建筑信息[%s]条" % (line-2))
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            traceback.print_exc()
            return response_error(u'导入失败！')
        return response_ok()
