from utils.custom_modelviewset import CustomModelViewSet
from django.db import transaction
import json
import random
from rest_framework.decorators import action
from .models import *
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, permission_required
from apps.upload.models import Upload
from django.contrib.auth import get_user_model

User = get_user_model()


class DictView(APIView):
    permission_classes = [isLogin, ]

    def get(self, request):
        rows = School.objects.filter(enable=True)
        ret = {
            'school': [{'id': item.id, 'value': item.name} for item in rows]
        }
        return response_ok(ret)

class SchoolView(APIView):
    permission_classes = [isLogin, ]

    def get(self, request):
        rows = School.objects.filter(enable=True, id__in=self.request.user.get_manager_school())
        data = [{'value': item.id, 'name': item.name} for item in rows]
        return response_ok(data)

class CategoryView(APIView):
    permission_classes = [isLogin, ]

    def get(self, request):
        rows = CommodityLevel.objects.filter(level=CommodityLevel.ONE, enable=True)
        data1 = [{'id': item.id, 'value': item.name} for item in rows]
        rows2 = CommodityLevel.objects.filter(level=CommodityLevel.TWO, enable=True)
        category = [{'id': item.id, 'value': item.name} for item in rows2]
        result = {
            'level':data1,
            'category':category,
        }
        return response_ok(result)

class CategoryWXView(APIView):
    # permission_classes = [isLogin, ]

    def get(self, request):
        rows = CommodityLevel.objects.filter(enable=True, home_show=True)
        p_list = ['a','b','c','d','e',]
        data = [{'id': item.id, 'value': item.name,
                 'picture': '%s/up/%s.png' % (settings.SERVER_DOMAIN, random.choice(p_list))
                 } for item in rows]
        data.insert(0,{'id': '', 'value': '全部', 'picture': '%s/up/a.png'% (settings.SERVER_DOMAIN)})
        return response_ok(data)

class AreaTreeView(APIView):
    permission_classes = [isLogin, ]

    # @cache_response()
    def get(self, request):
        area_data = []
        provinces = Area.objects.filter(level=Area.PROVINCE, province_id__isnull=True).values('id', 'name')
        for province in provinces:
            province_item = {
                'name': province['name'],
                'value': province['id'],
                'field': 'province',
                'children': [],
            }
            citys = Area.objects.filter(level=Area.CITY, province_id=province['id'], city_id__isnull=True).values('id', 'name')
            for city in citys:
                city_item = {
                    'name': city['name'],
                    'value': city['id'],
                    'field': 'city',
                    'children': [],
                }
                province_item['children'].append(city_item)
                countys = Area.objects.filter(level=Area.COUNTY, province_id=province['id'], city_id=city['id']).values('id', 'name')
                for county in countys:
                    county_item = {
                        'name': county['name'],
                        'value': county['id'],
                        'field': 'county',
                    }
                    city_item['children'].append(county_item)
            area_data.append(province_item)

        return response_ok(area_data)

class SchoolTreeView(APIView):
    permission_classes = [isLogin, ]

    # @cache_response()
    def get(self, request):
        source_data = []
        schools = School.objects.filter(enable=True)

        schools = schools.values('id', 'name')
        for school in schools:
            school_item = {
                'title': school['name'],
                'id': school['id'],
                'field': 'school',
                'children': [],
            }
            grades = Grade.objects.filter(school_id=school['id'], count__gte=1)
            grades = grades.values('id', 'name')
            for grade in grades:
                grade_item = {
                    'title': grade['name'],
                    'id': grade['id'],
                    'field': 'grade',
                    'children': [],
                }
                school_item['children'].append(grade_item)
                clas = Classes.objects.filter(grade_id=grade['id'], enable=True)
                clas = clas.values('id', 'name')
                for cla in clas:
                    class_item = {
                        'title': cla['name'],
                        'id': cla['id'],
                        'field': 'classes',
                    }
                    grade_item['children'].append(class_item)
            source_data.append(school_item)

        return response_ok(source_data)

class CategoryTreeView(APIView):
    # permission_classes = [isLogin, ]

    # @cache_response()
    def get(self, request):
        area_data = []
        provinces = CommodityLevel.objects.filter(level=CommodityLevel.ONE, category_id__isnull=True, enable=True).values('id', 'name')
        for province in provinces:
            province_item = {
                'name': province['name'],
                'value': province['id'],
                'field': 'level',
                'children': [],
            }
            citys = CommodityLevel.objects.filter(level=CommodityLevel.TWO, category_id=province['id'], enable=True).values('id', 'name')
            for city in citys:
                city_item = {
                    'name': city['name'],
                    'value': city['id'],
                    'field': 'category',
                    'children': [],
                }
                province_item['children'].append(city_item)
                countys = CommodityLevel.objects.filter(level=CommodityLevel.THREE, category_id=city['id'], enable=True).values('id', 'name')
                for county in countys:
                    county_item = {
                        'name': county['name'],
                        'value': county['id'],
                        'field': 'subject',
                    }
                    city_item['children'].append(county_item)
            area_data.append(province_item)

        return response_ok(area_data)

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'])

                    if pay_picture:
                        upload = Upload.objects._addnew(pay_picture)
                        if upload:
                            Config.objects.filter(property='pay_picture').delete()
                            Config.objects.create(property='pay_picture', value=upload.get_picture())
                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 SchoolViewSet(CustomModelViewSet):
    permission_classes = [isLogin, ]
    queryset = School.objects.filter()
    serializer_class = SchoolSerializer

    @permission_required('option.browse_school')
    def filter_queryset(self, queryset):
        queryset = queryset.filter(id__in=self.request.user.get_manager_school())
        f = SchoolFilter(self.request.GET, queryset=queryset)
        return f.qs

    @permission_required('option.add_school')
    def perform_create(self, serializer):
        super(SchoolViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(self.request.user, BizLog.INSERT,
                              u'添加学校[%s]，id=%d' % (instance.name, instance.id), validated_data)

    @permission_required('option.add_school')
    def perform_update(self, serializer):
        super(SchoolViewSet, self).perform_update(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(self.request.user, BizLog.UPDATE,
                              u'修改学校[%s]，id=%d' % (instance.name, instance.id), validated_data)

    @permission_required('option.add_school')
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        BizLog.objects.addnew(self.request.user, BizLog.DELETE,
                              u'删除学校[%s]，id=%d' % (instance.name, instance.id))
        super(SchoolViewSet, self).perform_destroy(instance)
        return response_ok()

    @action(methods=['get'], detail=False)
    def get_school_dict(self, request):
        schools = School.objects.filter(agent_id__in=self.request.user.get_manager_range(), enable=True).values('id',
                                                                                                                'name')
        schools = [{'value': school['id'], 'label': school['name']} for school in schools]
        return response_ok(schools)


class GradeViewSet(CustomModelViewSet):
    permission_classes = [isLogin, ]
    queryset = Grade.objects.filter()
    serializer_class = GradeSerializer

    @permission_required('option.browse_school')
    def filter_queryset(self, queryset):
        queryset = queryset.filter(school_id__in=self.request.user.get_manager_school())
        f = GradeFilter(self.request.GET, queryset=queryset)
        return f.qs

    @permission_required('option.add_school')
    def perform_create(self, serializer):
        super(GradeViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(self.request.user, BizLog.INSERT,
                              u'添加年级[%s]，id=%d' % (instance.name, instance.id), validated_data)

    @permission_required('option.add_school')
    def perform_update(self, serializer):
        super(GradeViewSet, self).perform_update(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(self.request.user, BizLog.UPDATE,
                              u'修改年级[%s]，id=%d' % (instance.name, instance.id), validated_data)

    @permission_required('option.add_school')
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        BizLog.objects.addnew(self.request.user, BizLog.DELETE,
                              u'删除年级[%s]，id=%d' % (instance.name, instance.id))
        super(GradeViewSet, self).perform_destroy(instance)
        return response_ok()


class StudentViewSet(CustomModelViewSet):
    permission_classes = [isLogin, ]
    queryset = Student.objects.filter()
    serializer_class = StudentSerializer

    def filter_queryset(self, queryset):
        queryset = queryset.filter()
        if self.request.user.type == User.CUSTOMER:
            queryset = queryset.filter(create_user=self.request.user, enable=True)
        else:
            queryset = queryset.filter(school_id__in=self.request.user.get_manager_school())
        f = StudentFilter(self.request.GET, queryset=queryset)
        return f.qs

    def perform_create(self, serializer):
        super(StudentViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(self.request.user, BizLog.INSERT,
                              u'添加学生信息[%s]，id=%d' % (instance.name, instance.id), validated_data)

    def perform_update(self, serializer):
        super(StudentViewSet, self).perform_update(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(self.request.user, BizLog.UPDATE,
                              u'修改学生信息[%s]，id=%d' % (instance.name, instance.id), validated_data)

    def destroy(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                instance = self.get_object()
                instance.enable = False
                instance.save()
                BizLog.objects.addnew(self.request.user, BizLog.DELETE,
                                      u'删除学生信息[%s]，id=%d' % (instance.name, 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))

class CategoryViewSet(CustomModelViewSet):
    permission_classes = [isLogin, ]
    queryset = CommodityLevel.objects.filter()
    serializer_class = CommodityLevelSerializer

    @permission_required('option.browse_commodiey_level')
    def filter_queryset(self, queryset):
        queryset = queryset.filter()
        f = CommodityLevelFilter(self.request.GET, queryset=queryset)
        return f.qs

    @permission_required('option.browse_commodiey_level')
    def perform_create(self, serializer):
        super(CategoryViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(self.request.user, BizLog.INSERT,
                              u'添加商品分类[%s]，id=%d' % (instance.name, instance.id), validated_data)

    @permission_required('option.browse_commodiey_level')
    def perform_update(self, serializer):
        super(CategoryViewSet, self).perform_update(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(self.request.user, BizLog.UPDATE,
                              u'修改商品分类[%s]，id=%d' % (instance.name, instance.id), validated_data)
