# coding=utf-8
import json
from django.db.models import Sum, F
from django.db import transaction
from django.db.models import Q
from rest_framework.views import APIView
from rest_framework.generics import ListAPIView, CreateAPIView
from utils.custom_modelviewset import CustomModelViewSet
from .serializers import *
from .filters import *
from apps.log.models import BizLog
from utils import response_ok, response_error
from utils.permission import isLogin
from apps.order.models import Order
from rest_framework.decorators import action
from django.contrib.auth import get_user_model

User = get_user_model()
from utils.format import strftime


class ProductView(APIView):

    def get(self, request):
        data = []
        queryset = Product.objects.filter(enable=True)
        for row in queryset:
            item = {
                'id': row.id,
                'name': row.name,
                'month': row.month,
            }
            data.append(item)
        return response_ok(data)


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

    def post(self, request, *args, **kwargs):
        # 商品图片 删除
        id = request.GET.get('id')
        try:
            instance = ProductImages.getById(id)
            image = Upload.objects.filter(id=instance.image_id).first()
            with transaction.atomic():
                instance.delete()
                image.del_images()
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok()


class ProductViewSet(CustomModelViewSet):
    permission_classes = [isLogin, ]
    queryset = Product.objects.filter()
    serializer_class = ProductSerializer

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

    @action(methods=['post'], detail=True)
    def upload_image(self, request, pk):
        banner_img = request.FILES.get('banner_img')
        try:
            with transaction.atomic():
                instance = self.get_object()
                upload = Upload.objects._addnew(banner_img, 'commodity_image/')
                if upload:
                    if instance.main_image_id:
                        img = Upload.objects.filter(id=instance.main_image_id).first()
                        img.del_images()
                    instance.main_image_id = upload.id
                    instance.save()
                    return response_ok(upload.id)
                return response_error('上传失败，请重新上传！')
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))

    @action(methods=['post'], detail=True)
    def upload_detail_img(self, request, pk):
        # 上传详情、参数图片
        try:
            with transaction.atomic():
                instance = self.get_object()
                for i in range(10):
                    file = request.data.get('file{}'.format(i))
                    if file:
                        upload = Upload.objects._addnew(file, 'commodity_image/')
                        ProductImages.objects.create(product_id=instance.id,
                                                     image_id=upload.id)

                        if not upload:
                            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()

    @action(methods=['post'], detail=True)
    def query_detail_img(self, request, pk):
        # 查看 详情图片
        instance = self.get_object()
        data = []

        commodity_images = ProductImages.objects.filter(product_id=instance.id)
        for commodity_image in commodity_images:
            image = Upload.objects.filter(id=commodity_image.image_id).first()
            image_path = image.get_path()
            commodity_image_item = {
                'id': commodity_image.id,
                'name': commodity_image.name,
                'src': image_path,
            }
            data.append(commodity_image_item)
        return response_ok(data)


class ProductListView(ListAPIView):
    queryset = Product.objects.filter(enable=True, main_image__isnull=False)
    serializer_class = ProductListSerializer

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


class OrderListView(ListAPIView):
    permission_classes = [isLogin, ]
    queryset = Order.objects.filter()
    serializer_class = OrderListSerializer

    def filter_queryset(self, queryset, ):
        queryset = queryset.filter(Q(create_user_id__in=self.request.user.get_manager_users()) | Q(
            seller_id__in=self.request.user.get_manager_users()))
        f = OrderFilter(self.request.GET, queryset=queryset)
        return f.qs


class OrderCreatView(CreateAPIView):
    # 匿名用户申报
    queryset = Order.objects.filter()
    serializer_class = OrderSerializer

    def post(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                serializer = self.get_serializer(data=request.data)
                if serializer.is_valid(raise_exception=True):
                    instance = serializer.save()
                    BizLog.objects.addnew(None, BizLog.INSERT,
                                          u'添加订单[%s]，id=%d' % (instance.name, instance.id), request.data)
                    return response_ok(instance.id)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))


class OrderUploadView(CreateAPIView):
    # 匿名用户申报上传图片
    queryset = Order.objects.filter()
    serializer_class = OrderSerializer

    def post(self, request, *args, **kwargs):
        file = self.request.FILES.get('file')
        id = self.request.POST.get('id')
        type = self.request.POST.get('type')
        # 上传图片，order_id必填。更新图片时，upload_id必填
        # / order / 2 / upload_image /
        # post
        # file
        # type 0身份证, 1驾驶证, 2收入类, 3流水类, 4营业执照, 5挂靠协议
        # order_id 订单id
        # upload_id 图片id
        try:
            instance = Order.objects.filter(id=id).first()
            if not instance:
                raise CustomError('客户信息错误')
            if instance.status == order.ONE:
                raise CustomError('该客户信息已审核通过，禁止操作')
            elif instance.status == order.THREE:
                raise CustomError('该客户信息被拒绝审批，禁止操作')
            with transaction.atomic():
                if type:
                    # 上传图片时，把不在使用的同类别图片删除。
                    images = OrderImages.objects.filter(order=instance, type=type, enable=False)
                    for image in images:
                        image.image.del_images()
                        image.delete()
                path = instance.get_path(type)
                upload = Upload.objects._addnew(file, path)
                if upload:
                    OrderImages.objects.create(order=instance, type=type, image=upload, )
                    edit = OrderDetailEdit.objects.filter(type=OrderDetailEdit.ONE, order=instance,
                                                          value=type).first()
                    if edit:
                        edit.edit_time = datetime.datetime.now()
                        edit.save()
                    dict = {
                        'id': upload.id,
                        'path': upload.get_path(),
                    }
                    return response_ok(dict)
                return response_error('上传失败，请重新上传！')
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))


class OrderDeleteImgView(CreateAPIView):
    # 匿名用户申报上传图片
    queryset = Order.objects.filter()
    serializer_class = OrderSerializer

    def post(self, request, *args, **kwargs):
        order_id = request.POST.get('order_id')
        upload_id = request.POST.get('upload_id')
        try:
            instance = Order.objects.filter(id=order_id).first()
            if not instance:
                raise CustomError('客户信息错误')
            if instance.status == order.ONE:
                raise CustomError('该客户信息已审核通过，禁止操作')
            if instance.status == order.THREE:
                raise CustomError('该客户信息被拒绝审批，禁止操作')
            with transaction.atomic():
                if upload_id:
                    upload = Upload.objects.filter(id=upload_id).first()
                    if upload:
                        OrderImages.objects.filter(order=instance, image_id=upload_id).delete()
                        upload.del_images()
                        return response_ok()
                return response_error('图片参数错误，删除失败')
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))

class GetNewView(APIView):
    # 获取新订单

    def get(self, request, *args, **kwargs):
        minutes = request.GET.get('minutes')
        time = datetime.datetime.now() - datetime.timedelta(minutes=int(minutes))
        orders = Order.objects.filter(create_time__gte=time, category=order.ONE)
        return response_ok(orders.count())


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

    def filter_queryset(self, queryset, ):
        # 非管理者，只能查看自己的客户
        queryset = queryset.filter(Q(create_user_id__in=self.request.user.get_manager_users()) | Q(seller_id__in=self.request.user.get_manager_users()))
        f = OrderFilter(self.request.GET, queryset=queryset)
        return f.qs

    def retrieve(self, request, *args, **kwargs):
        # 小程序草稿箱、已上报修改，调用明细
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        # 草稿的数据
        if instance.category == order.ZERO:
            edit_file2 = []
            images = OrderImages.objects.filter(order=instance)
            for image in images:
                item2 = {
                    'upload_id': image.image.id,
                    'url': image.image.get_path(),
                    'type': image.type,
                }
                edit_file2.append(item2)
            result = {
                'data': serializer.data,
                'edit_file2': edit_file2,
            }
            return response_ok(result)
        else:
            # 已上报修改，返回需要修改的字段列表
            edit_data = []
            edit_file = []
            edit_file2 = []
            edit_values = OrderDetailEdit.objects.filter(order=instance).values('value', 'reason', 'type')
            for r in edit_values:
                item = {
                    'name': r['value'],
                    'reason': r['reason'],
                }
                if r['type'] == OrderDetailEdit.ZERO:
                    edit_data.append(item)
                else:
                    edit_file.append(item)
            # 待审核，加载图片使用
            # if instance.status == order.ZERO:
            images = OrderImages.objects.filter(order=instance)
            for image in images:
                item2 = {
                    'upload_id': image.image.id,
                    'url': image.image.get_path(),
                    'type': image.type,
                }
                edit_file2.append(item2)
            result = {
                'data': serializer.data,
                'edit_values': edit_data,
                'edit_file': edit_file,
                'edit_file2': edit_file2,
            }
            return response_ok(result)

    def create(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                serializer = self.get_serializer(data=request.data)
                if serializer.is_valid(raise_exception=True):
                    instance = serializer.save()
                    BizLog.objects.addnew(self.request.user, BizLog.INSERT,
                                          u'添加订单[%s]，id=%d' % (instance.name, instance.id), request.data)
                    return response_ok(instance.id)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))

    def update(self, request, *args, **kwargs):
        data = request.POST
        try:
            instance = self.get_object()
            if instance.status == order.ONE:
                raise CustomError('该客户信息已审核通过，禁止操作')
            if instance.status == order.THREE:
                raise CustomError('该客户信息被拒绝审批，禁止操作')
            with transaction.atomic():
                serializer = self.get_serializer(instance, data=request.data)
                if serializer.is_valid(raise_exception=True):
                    instance = serializer.save()
                    instance.create_user = request.user
                    instance.save()
                    # 已上报的，修改，记录修改时间
                    if instance.category == order.ONE:
                        for key in data:
                            edit = OrderDetailEdit.objects.filter(type=OrderDetailEdit.ZERO, order=instance,
                                                                  value=key).first()
                            if edit:
                                edit.edit_time = datetime.datetime.now()
                                edit.save()
                        instance.status = order.ZERO
                        instance.create_time = datetime.datetime.now()
                        instance.save()
                    BizLog.objects.addnew(request.user, BizLog.INSERT,
                                          u'修改订单[%s]，id=%d' % (instance.name, instance.id), request.data)
                    return response_ok(instance.id)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))

    @action(methods=['post'], detail=True)
    def checkEdit(self, request, pk):
        data = request.POST.get('items')
        reason = request.POST.get('reason')
        status = request.GET.get('statu')

        try:
            if request.user.type != User.EMPLOYEE:
                raise CustomError('当前用户无权限，禁止操作')
            instance = self.get_object()
            if instance.category == order.ZERO:
                raise CustomError('草稿件，禁止操作')
            if instance.status == order.ONE:
                raise CustomError('该客户信息已审核通过，禁止操作')
            if instance.status == order.THREE:
                raise CustomError('该客户信息被拒绝审批，禁止操作')
            with transaction.atomic():
                if status == '1':
                    # 审核通过， 删除修改信息
                    instance.status = order.ONE
                    OrderDetailEdit.objects.filter(order=instance).delete()
                elif status == '3':
                    # 拒绝审批
                    instance.status = order.THREE
                    instance.cancel_reason = reason
                else:
                    # 返回修改
                    if not len(data):
                        raise CustomError('请填写返回修改原因')
                    # 删除已修改过的历史修改信息
                    rowss = OrderDetailEdit.objects.filter(order=instance, edit_time__isnull=False)
                    rowss.delete()
                    for item in json.loads(data):
                        edit = OrderDetailEdit.objects.filter(order=instance, value=item['name'], type=item['type'])
                        if edit:
                            edit.update(reason=item['reason'], edit_time=None)
                        else:
                            OrderDetailEdit.objects.create(order=instance, value=item['name'], reason=item['reason'],
                                                       type=item['type'])
                        if int(item['type']) == OrderDetailEdit.ONE:
                            OrderImages.objects.filter(order=instance, type=item['name']).update(enable=False)
                    instance.status = order.TOW
                instance.save()
                BizLog.objects.addnew(self.request.user, BizLog.INSERT,
                                      u'审批订单[%s],状态=%s，id=%d' % (instance.name, status, instance.id), request.data)
                return response_ok()
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))

    @action(methods=['post'], detail=True)
    def upload_image(self, request, pk):
        file = self.request.FILES.get('file')
        type = self.request.POST.get('type')
        # 上传图片，order_id必填。更新图片时，upload_id必填
        # / order / 2 / upload_image /
        # post
        # file
        # type 0身份证, 1驾驶证, 2收入类, 3流水类, 4营业执照, 5挂靠协议
        # order_id 订单id
        # upload_id 图片id
        try:
            instance = self.get_object()
            if instance.status == order.ONE:
                raise CustomError('该客户信息已审核通过，禁止操作')
            if instance.status == order.THREE:
                raise CustomError('该客户信息被拒绝审批，禁止操作')
            with transaction.atomic():
                if type:
                    # 上传图片时，把不在使用的同类别图片删除。
                    images = OrderImages.objects.filter(order=instance, type=type, enable=False)
                    for image in images:
                        image.image.del_images()
                        image.delete()
                path = instance.get_path(type)
                upload = Upload.objects._addnew(file, path)
                if upload:
                    OrderImages.objects.create(order=instance, type=type, image=upload, )
                    edit = OrderDetailEdit.objects.filter(type=OrderDetailEdit.ONE, order=instance,
                                                          value=type).first()
                    if edit:
                        edit.edit_time = datetime.datetime.now()
                        edit.save()
                    dict = {
                        'id': upload.id,
                        'path': upload.get_path(),
                    }
                    return response_ok(dict)
                return response_error('上传失败，请重新上传！')
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))

    @action(methods=['post'], detail=True)
    def deleteImage(self, request, pk):
        upload_id = request.POST.get('id')

        try:
            instance = self.get_object()
            if instance.status == order.ONE:
                raise CustomError('该客户信息已审核通过，禁止操作')
            if instance.status == order.THREE:
                raise CustomError('该客户信息被拒绝审批，禁止操作')
            with transaction.atomic():
                if upload_id:
                    upload = Upload.objects.filter(id=upload_id).first()
                    if upload:
                        OrderImages.objects.filter(order=instance, image_id=upload_id).delete()
                        upload.del_images()
                        return response_ok()
                return response_error('图片参数错误，删除失败')
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))

    @action(methods=['get'], detail=True)
    def get_detail(self, request, pk):
        # 后端审核业务，获取客户信息和部分字段修改时间
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        # y已上报修改，返回需要修改的字段列表
        # 不显示字段
        show = [
            'seller_text','vmodel', 'invioce', 'ptax', 'insurance', 'boutique', 'wextension', 'upkeep', 'dpratio', 'lamount',
            'laompany_text', 'laompany_month', 'name', 'sex_text', 'bdate', 'rpr_text', 'nationality_text', 'ntype_text', 'inumber',
            'dincome', 'mstatus_text',
            'elevel_text', 'naddress', 'hptype_text', 'maddress_text', 'email', 'wx', 'phone', 'tel', 'wname', 'wphone',
            'waddress', 'itype_text', 'otype_text', 'position', 'wbst_text', 'bstname', 'bstcode', 'bsttel',
            'bstaddress',
            'cname', 'ctel', 'relation_text', 'caddress', 'ctname', 'cttel', 'thesame_text', 'tsname', 'tsbdate',
            'tsitype_text', 'tsinumber', 'tstel', 'tsrelation_text', 'tsnaddress', 'tsmaddress_text', 'tsemail', 'tswx',
            'tswname', 'tswphone', 'tswaddress', 'tsmincome', 'notes',
        ]
        result = []
        for s in show:
            key = serializer[s]
            edit_values = OrderDetailEdit.objects.filter(order=instance, type=OrderDetailEdit.ZERO,
                                                         value=key.name).first()
            edit_time = reason = ''
            if edit_values:
                edit_time = edit_values.edit_time and strftime(edit_values.edit_time) or ''
                reason = edit_values.reason
            item = {
                'name': key.name,  # tel
                'label': key.label,  # 电话
                'value': key.value,  # 13566
                'edit_time': edit_time,
                'reason': reason,
                'type': '0',
            }
            result.append(item)

        files = []
        types = OrderImages.TYPE_CHOICE
        for t in types:
            edit_values = OrderDetailEdit.objects.filter(order=instance, type=OrderDetailEdit.ONE,
                                                         value=t[0]).first()
            edit_time = reason = ''
            if edit_values:
                edit_time = edit_values.edit_time and strftime(edit_values.edit_time) or ''
                reason = edit_values.reason

            item = {
                'name': t[0],  # 身份证
                'label': t[1],  # 身份证
                'images': [],  # 1
                'edit_time': edit_time,
                'reason': reason,
                'type': '1',
            }
            images = OrderImages.objects.filter(order=instance, type=t[0])
            for image in images:
                item['images'].append(image.image.get_path())
            files.append(item)
        edit_dict = {
            'order_info': result,
            'image_info': files,
        }
        return response_ok(edit_dict)

    def destroy(self, request, *args, **kwargs):
        try:
            instance = self.get_object()
            if instance.category == order.ONE:
                raise CustomError('已上报信息，禁止删除!')
            if instance.status == order.THREE:
                raise CustomError('该客户信息被拒绝审批，禁止操作')
            with transaction.atomic():
                OrderDetailEdit.objects.filter(order=instance).delete()
                images = OrderImages.objects.filter(order=instance)
                for image in images:
                    upload = Upload.objects.filter(id=image.image.id).first()
                    upload.del_images()
                images.delete()
                super(OrderViewSet, self).destroy(request, *args, **kwargs)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok()
