# coding=utf-8
from rest_framework.views import APIView
from django.db.models import Q
import traceback
import datetime
from rest_framework.serializers import ValidationError
from django.utils import timezone
from rest_framework.decorators import action
from utils.permission import isLogin, permission_required, check_permission
from utils.custom_modelviewset import CustomModelViewSet
from utils import response_ok, response_error
from utils.exceptions import CustomError
from apps.log.models import BizLog
from apps.option.models import Option
from apps.option.serializers import OptionComboboxSerializer
from .models import ReportCustomer,NewCustomer,Review
from .serializers import ReportCustomerSerializer,NewCustomerSerializer, ReviewSerializer
from .filters import ReportCustomerFilter,NewCustomerFilter,ReviewFilter
from django.contrib.auth import get_user_model
User = get_user_model()

class ReportCustomerViewSet(CustomModelViewSet):
    permission_classes = [isLogin]
    queryset = ReportCustomer.objects.filter()
    serializer_class = ReportCustomerSerializer

    @permission_required('customer.view_report_customer')
    def filter_queryset(self, queryset):
        queryset = queryset.filter(
            Q(store_id__in=self.request.user.get_manager_range()) |
            Q(create_user=self.request.user))
        f = ReportCustomerFilter(self.request.GET, queryset=queryset)
        return f.qs

    @permission_required('customer.add_report_customer')
    def perform_create(self, serializer):
        super(ReportCustomerViewSet, 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('customer.add_report_customer')
    def perform_update(self, serializer):
        super(ReportCustomerViewSet, 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('customer.delete_report_customer')
    def perform_destroy(self, instance):
        BizLog.objects.addnew(self.request.user, BizLog.DELETE,
                              u'删除客户报备[%s]，id=%d' % (instance.name, instance.id))
        super(ReportCustomerViewSet, self).perform_destroy(instance)

    @action(methods=['post'], detail=True)
    def dispatch_customer(self, request, pk):
        check_permission(request, 'customer.check_report_customer')
        # 审核
        user_id = request.POST.get('user')
        try:
            instance = ReportCustomer.objects.filter(id=pk).first()
            if not instance:
                raise CustomError('当前客户报备信息有误,请刷新重试！')
            instance.check_user = self.request.user
            instance.report_status = ReportCustomer.CHECKED
            instance.check_time = timezone.now()
            instance.save()
            BizLog.objects.addnew(request.user, BizLog.INSERT,
                                  u'分配客户报备[%s],id=%d' % (instance.name,  instance.id))
            # 创建潜客跟踪表
            potential_level = Option.objects.filter(type=Option.POTENTIAL_LEVEL, enable=True).order_by('sort').first()
            stage_progress = Option.objects.filter(type=Option.STAGE_PROGRESS, enable=True).order_by('sort').first()
            if not potential_level.track_day:
                raise CustomError('当前潜客级别，没有可用跟踪天数！')
            next_time = (timezone.now() + datetime.timedelta(days=potential_level.track_day)).strftime('%Y-%m-%d')
            NewCustomer.objects.create(report_customer=instance, potential_level=potential_level,
                                       track_user_id=user_id, next_time=next_time, stage_progress=stage_progress,
                                       create_user=instance.create_user,
                                       )
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok()


class ReportCustomerDictView(APIView):
    permission_classes = [isLogin]

    def get(self, request):
        source = Option.objects.filter(type=Option.CUSTOMER_SOURCE, enable=True)
        project = Option.objects.filter(type=Option.CATEGORY, enable=True)
        level = Option.objects.filter(type=Option.POTENTIAL_LEVEL, enable=True)
        serializer_source = OptionComboboxSerializer(source, many=True)
        serializer_project = OptionComboboxSerializer(project, many=True)
        serializer_level = OptionComboboxSerializer(level, many=True)

        return response_ok({
            'source': serializer_source.data,
            'project': serializer_project.data,
            'level': serializer_level.data,
        })

class UserDictView(APIView):
    permission_classes = [isLogin]

    def get(self, request):
        store = request.user.store
        if not store:
            return response_error('当前账号未绑定门店，禁止分配客户！')
        users = User.objects.filter(store=store).values('id', 'name')
        users = [{'value': user['id'], 'lable': user['name']} for user in users]
        return response_ok(users)


class NewCustomerViewSet(CustomModelViewSet):
    permission_classes = []
    queryset = NewCustomer.objects.filter()
    serializer_class = NewCustomerSerializer

    def filter_queryset(self, queryset):
        queryset = queryset.filter()
        f = NewCustomerFilter(self.request.GET, queryset=queryset)
        return f.qs

    def paginate_queryset(self, queryset):
        if self.paginator is None or self.request.GET.get('export'):
            return None
        return self.paginator.paginate_queryset(queryset, self.request, view=self)

    @action(methods=['post'], detail=True)
    def add_review(self, request, pk):
        check_permission(request, 'customer.add_review')
        description = request.POST.get('description')
        instruction = request.POST.get('instruction')
        is_entry = request.POST.get('is_entry') == '1'
        is_giveup = request.POST.get('is_giveup') == '1'
        potential_level = request.POST.get('potential_level')
        next_time = request.POST.get('next_time')
        try:
            instance = NewCustomer.objects.filter(id=pk).first()
            if not instance:
                raise CustomError('当前客户信息有误,请刷新重试！')
            data = {
                'customer':instance.id,
                'store':request.user.store.id,
                'create_user':request.user.id,
                'description':description,
                'instruction':instruction,
                'is_entry':is_entry,
                'is_giveup':is_giveup,
            }
            serializer = ReviewSerializer(data=data)
            if serializer.is_valid(raise_exception=True):
                serializer.save()

            data = {
                'potential_level':potential_level,
                'next_time':next_time,
                'end_time':timezone.now(),
                'stage_progress':instance.stage_progress.id,
            }
            ser = self.serializer_class(instance, data=data, partial=True)
            if ser.is_valid(raise_exception=True):
                ser.save()

        except ValidationError as e:
            traceback.print_exc()
            return response_error('数据格式有误')
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok()

class StageCountView(APIView):
    permission_classes = [isLogin]

    def get(self,request):
        data = []
        stage_progress = Option.objects.filter(type=Option.STAGE_PROGRESS, enable=True).order_by('sort')
        user = request.user
        time_now = timezone.now().strftime('%Y-%m-%d')
        for stage in stage_progress:
            new_customers = NewCustomer.objects.filter(Q(track_user=user) |
                                                       Q(track_user__store_id__in=request.user.get_manager_range()),
                                                       stage_progress=stage)
            stage_count = {
                'stage_id': stage.id,    # 阶段名称
                'stage': stage.name,    # 阶段名称
                'total_count': new_customers.count(),   # 总人数
                'today_count': new_customers.filter(next_time=time_now).count(),  # 今日人数
                'overdue_count': new_customers.filter(next_time__lt=time_now).count()  # 逾期人数
            }
            data.append(stage_count)
        return response_ok(data)

class ReviewViewSet(CustomModelViewSet):
    permission_classes = []
    queryset = Review.objects.filter()
    serializer_class = ReviewSerializer

    def filter_queryset(self, queryset):
        queryset = queryset.filter()
        f = ReviewFilter(self.request.GET, queryset=queryset)
        return f.qs

    @action(methods=['post'], detail=True)
    def track_review(self, request, pk):
        # 跟踪审核
        check_status = request.POST.get('check_status')
        check_comment = request.POST.get('check_comment')
        next_time = request.POST.get('next_time')
        try:
            instance = Review.objects.filter(id=pk).first()
            if int(check_status) == Review.KEEPUP:
                instance.check_user = request.user
                instance.check_status = check_status
                instance.check_comment = check_comment
                instance.next_time = next_time
                instance.check_time = timezone.now()
                instance.save()
            if int(check_status) == Review.ABANDON:
                instance.check_user = request.user
                instance.check_status = check_status
                instance.check_comment = check_comment
                instance.check_time = timezone.now()
                instance.is_giveup = True
                instance.save()
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok()








