# coding=utf-8
import traceback
from rest_framework.views import APIView
from rest_framework.decorators import action
from django.db import transaction
import datetime
from django.utils import timezone
from utils.custom_modelviewset import CustomModelViewSet
from utils.exceptions import CustomError
from .serializers import OrderSerializer, ProgressDetailsSerializer
from .filters import OrderFilter
from apps.log.models import BizLog
from django.db.models import Q
from utils import response_ok, response_error
from utils.permission import isLogin, check_permission, permission_required
from apps.customer.models import NewCustomer, NewCustomerRemind
from apps.order.models import Order, ProgressDetails
from apps.option.models import Option
from apps.upload.models import Upload
from apps.upload.serializers import UploadSerializer


class GetProcessView(APIView):
    permission_classes = [isLogin]

    def get(self, request):
        customer_id = request.query_params.get('customer_id')
        back = request.query_params.get('back') == '1' # 是否撤回进度
        dispatch = request.query_params.get('dispatch')  # 分配服务人员，

        instance = NewCustomer.objects.filter(id=customer_id).first()
        if not instance:
            raise CustomError('当前客户信息有误,请刷新重试！')
        if instance.stage_progress.end_stage:
            data = {
                'error_message': u'当前客户订单等待分配中，请勿重复更新！',
            }
            return response_ok(data)
        order = Order.objects.filter(customer=instance).first()
        # 分配服务人员，不做重复更新判断
        if order and order.status == Order.WAIT_DISPATCH and not dispatch:
            data = {
                'error_message': u'当前客户订单等待分配中，请勿重复更新！',
            }
            return response_ok(data)

        option = Option.objects.filter(type=instance.stage_progress.type,
                                       enable=True)
        if back:
            # 非撤回，查询下一个进度。
            option = option.filter(sort__lt=instance.stage_progress.sort,).order_by('-sort')
        else:
            option = option.filter(sort__gt=instance.stage_progress.sort,).order_by('sort')
        option = option.first()
        if option:
            data = {
                'now_process_text': instance.stage_progress.name,
                'next_process_text': option.name,
                'next_process_id': option.id,
            }
            return response_ok(data)
        else:
            data = {
                'error_message': u'未找到下个阶段进度，请联系管理员设置！',
            }
            return response_ok(data)


class OrderViewSet(CustomModelViewSet):
    permission_classes = [isLogin]
    queryset = Order.objects.filter()
    serializer_class = OrderSerializer

    @permission_required('order.view_order')
    def filter_queryset(self, queryset):
        queryset = queryset.filter(
            Q(store_id__in=self.request.user.get_manager_range()) |
            Q(service_user=self.request.user) |
            Q(customer__create_user=self.request.user)
        )
        f = OrderFilter(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 dispatch_service(self, request, pk):
        # 订单分配服务人员
        check_permission(request, 'order.order_process_dispatch')
        next_process = request.POST.get('next_process')
        service = request.POST.get('service')

        try:
            with transaction.atomic():
                stage_progress = Option.objects.filter(id=next_process, enable=True).order_by('sort').first()
                if not stage_progress:
                    raise CustomError('阶段进度有误，请刷新重试！')
                if not stage_progress.track_day:
                    raise CustomError('下一阶段进度，没有可用跟踪天数，请联系管理员设置！')
                Order.objects.filter(id=pk).update(stage_progress=stage_progress, service_user_id=service,
                                                   status=Order.NORMAL)

                next_time = (timezone.now() + datetime.timedelta(days=stage_progress.track_day)).strftime('%Y-%m-%d')
                # 更新进度，删除上一个跟踪人提醒
                order = self.get_object()
                NewCustomerRemind.objects.filter(customer=order.customer, remind_user=order.customer.track_user).delete()
                NewCustomer.objects.filter(id=order.customer_id).update(
                    stage_progress=stage_progress,
                    track_user_id=service,
                    next_time=next_time,
                )
                if not stage_progress.end_stage:
                    NewCustomerRemind.objects.create(customer=order.customer, store=order.customer.store, remind_user_id=service, next_time=next_time)
                operation = u'{} 分配服务人员为：{}'.format(stage_progress.name, order.service_user.name)
                ProgressDetails.objects.create(order=order, user=request.user, operation=operation,)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok()

    @action(methods=['post'], detail=True)
    def uncheck(self, request, pk):
        # 撤销进度审核
        stage_progress = request.POST.get('stage_progress')
        reason = request.POST.get('reason')
        try:
            with transaction.atomic():
                stage_progress = Option.objects.filter(id=stage_progress, enable=True).first()
                if not stage_progress:
                    raise CustomError('撤回进度不存在，请刷新重试！')
                if stage_progress.sort == 1:
                    # 撤回的进度排序为1，把订单删除
                    instance = Order.objects.filter(id=pk).first()
                    # TODO 删除数据库钱，先删除图片文件
                    Upload.objects.filter(progress_details__order=instance).delete()
                    ProgressDetails.objects.filter(order=instance).delete()
                    instance.delete()
                    return response_ok()

                instance = Order.objects.filter(id=pk).first()
                if not instance:
                    raise CustomError('订单不存在')
                instance.status = Order.NORMAL
                instance.save()

                operation = u'撤回进度为：{}。'.format(stage_progress.name)
                ProgressDetails.objects.create(order=instance, user=request.user, operation=operation,notes=reason )
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok(u'撤销完成！')


class GetDetailsView(APIView):
    permission_classes = [isLogin]

    def get(self, request):
        # 进度明细
        order_id = request.GET.get('order_id')
        details = ProgressDetails.objects.filter(order_id=order_id).order_by('-operation_time')
        data = ProgressDetailsSerializer(details, many=True).data
        return response_ok(data)


class GetFilesView(APIView):
    permission_classes = [isLogin]

    def get(self, request):
        # 附件内容
        id = request.GET.get('id')
        images = Upload.objects.filter(progress_details_id=id)
        img_data = UploadSerializer(images, many=True).data
        return response_ok(img_data)
