from utils.custom_modelviewset import CustomModelViewSet
from django.db import transaction
import json
from django.db.models import Sum
from rest_framework.decorators import action
from .serializers import *
from .filters import *
from rest_framework.views import APIView
from apps.log.models import BizLog
from utils import response_ok, response_error
from utils.exceptions import CustomError
from utils.permission import isLogin
from django.contrib.auth import get_user_model
User = get_user_model()
from utils.file_operation import attachment_save

class ConfigViewSet(CustomModelViewSet):
    permission_classes = [isLogin, ]
    queryset = Config.objects.filter()
    serializer_class = ConfigSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return response_ok(serializer.data)

    def create(self, request, *args, **kwargs):
        try:
            data = json.loads(request.POST.get('data'))
            pay_picture = request.FILES.get('pay_picture')
            keys = ['leave_lead_time', ]
            with transaction.atomic():
                for item in data:
                    config = Config.objects.filter(property=item['key']).first()
                    if item['value']:
                        if item['key'] not in keys:
                            raise CustomError(u'综合设置属性[%s]不存在' % item['key'])
                        else:
                            item['value'] = item['value'].strip()
                        if config:
                            config.value = item['value']
                            config.save()
                        else:
                            Config.objects.create(property=item['key'], value=item['value'])

                BizLog.objects.addnew(self.request.user, BizLog.INSERT, u'修改系统配置', data)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok()

class BalanceViewSet(CustomModelViewSet):
    permission_classes = [isLogin, ]
    queryset = Balance.objects.filter()
    serializer_class = BalanceSerializer

    def filter_queryset(self, queryset):
        queryset = queryset.filter()
        if self.request.user.type == User.CUSTOMER:
            queryset = queryset.filter(create_user=self.request.user)
        return queryset

    @action(methods=['post'], detail=False)
    def clear_balance(self, request):
        create_user = request.GET.get('create_user')
        reason = request.POST.get('reason')
        instance = Balance.objects.filter(create_user_id=create_user).first()
        try:
            if not reason:
                raise CustomError('请填写清空原因！')
            if not instance:
                raise CustomError('学生信息错误，请刷新重试！')
            with transaction.atomic():
                if instance.balance <= 0:
                    raise CustomError('余额为0，不能清空！')
                desc = '清空余额，原因：{}'.format(reason)
                Balance.update_balance(instance.create_user, -instance.balance, desc)
                instance.balance = 0
                instance.save()
                BizLog.objects.addnew(self.request.user, BizLog.INSERT, u'清空[{}]余额, id={}'.
                                      format(instance.create_user.username, 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()

class BalanceLogViewSet(CustomModelViewSet):
    permission_classes = [isLogin, ]
    queryset = BalanceLog.objects.filter()
    serializer_class = BalanceLogSerializer

    def filter_queryset(self, queryset):
        description = self.request.GET.get('description')
        queryset = queryset.filter()
        if self.request.user.type == User.CUSTOMER:
            queryset = queryset.filter(create_user=self.request.user)
        if description:
            queryset = queryset.filter(description__icontains=description)
        return queryset

class PosterView(APIView):

    def get(self, request):
        data = []
        queryset = Poster.objects.filter()
        for row in queryset:
            data.append(settings.SERVER_DOMAIN + row.image)
        return response_ok(data)

class PosterViewSet(CustomModelViewSet):
    permission_classes = [isLogin, ]
    queryset = Poster.objects.filter()
    serializer_class = PosterSerializer

    def create(self, request, *args, **kwargs):
        banner_img = request.FILES.get('banner_img')
        try:
            with transaction.atomic():
                poster = Poster.objects.create(create_user=request.user)
                poster._add_img(banner_img)
                BizLog.objects.addnew(self.request.user, BizLog.INSERT, u'添加轮播信息, id={}'.
                                      format(poster.id), )
            return response_ok()
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
