# coding=utf-8
from rest_framework.views import APIView
from django.db import transaction
import traceback
from .serializers import DeviceSerializer
from utils.exceptions import CustomError
from utils.permission import IsTenantUser
from .filters import DeviceFilter, DeviceModel
from utils.custom_modelviewset import CustomModelViewSet
from apps.log.models import BizLog
from apps.tenant import tenant_log
from utils import response_ok, response_error
from .resources import DeviceImporter

# Create your views here.
class DeviceViewSet(CustomModelViewSet):
    permission_classes = [IsTenantUser]
    queryset = DeviceModel.objects.all()
    serializer_class = DeviceSerializer

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

    def perfrom_create(self, serializer):
        super(DeviceViewSet, 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.name, instance.id),
                   validated_data)

    def perform_update(self, serializer):
        #更新
        super(DeviceViewSet, self).perform_update(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        tenant_log(self.request.user.employee, BizLog.INSERT, u'修改设备信息[%s]，id=%d' % (instance.name, instance.id),
                   validated_data)

    def perform_destroy(self, instance):
        #删除
        if instance.tenant != self.request.user.employee.tenant:
            raise CustomError(u'禁止跨租户操作！')
        tenant_log(self.request.user.employee, BizLog.DELETE, u'删除设备信息[%s]，id=%d' % (instance.name, instance.id))
        super(DeviceViewSet, self).perform_destroy(instance)

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

    def post(self, request):
        file = request.FILES.get('excel_file')
        try:
            line = 2
            importer = DeviceImporter()
            excel_rows = importer.getExcelData(file)
            with transaction.atomic():
                for excel_row in excel_rows:
                    try:
                        row = importer.validRow(excel_row)
                        data = {}
                        data['name'] = row[u'名称']
                        data['device_no'] = row[u'编号']
                        data['device_model'] = row[u'设备型号']
                        data['branch'] = row[u'小地点']
                        data['address'] = row[u'大地点']
                        data['create_user'] = request.user
                        data['tenant'] = request.user.employee.tenant
                        DeviceModel.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()
