# coding=utf-8
from rest_framework import serializers

from apps.WechatApplet.models import WechatApplet
from .models import *


class DeviceSerializer(serializers.ModelSerializer):
    create_user_text = serializers.CharField(source='create_user.employee.name', read_only=True)

    class Meta:
        model = DeviceModel
        fields = '__all__'

    def create(self, validated_data):
        validated_data['create_user'] = self.context['request'].user
        validated_data['tenant'] = self.context['request'].user.employee.tenant
        instance = super(DeviceSerializer, self).create(validated_data)

        id = instance.id
        applet = WechatApplet.objects.filter(authorizer_appid=settings.WEAPP['appid']).first()
        filename = applet.getDeviceCode(id)
        instance.wxapp_img = "{0}{1}".format(settings.MEDIA_URL,filename)
        instance.save()

        return instance
