# coding=utf-8

import traceback
import json
from django.views.decorators.csrf import csrf_exempt
from django.db import transaction
from apps.account.decorators import token_required, permission_required, valid_permission, isHasPermissions
from apps.account.models import User
from apps.order.models import SaleOrder, SaleOrderDetail, GoodsDeliver, GoodsDeliverDetail, GoodsDeliverReturn,GoodsDeliverReturnDetail, SaleOrderMessage
from django.db.models import Q, F, Sum
from django.utils import timezone

from apps.goods.models import GoodsGodownEntryDetail
from apps.warehouse.biz import BizWarehouse, GetWarehouseSrockRecord
from apps.warehouse.models import Warehouse, WarehouseStock, WarehouseRecord, InventoryDetail
from libs.http import JSONResponse, JSONError, DataGridJSONResponse
from _mysql_exceptions import IntegrityError
from django.db.models import ProtectedError
from libs import utils
from apps.exceptions import CustomError, ExportChange
from apps.order.filters import SaleOrderFilter, GoodsDeliverFilter, GoodsDeliverReturnFilter
from apps.order.serializers import SaleOrderSerializer, SaleOrderDetailSerializer, GoodsDeliverSerializer, \
    GoodsDeliverDetailSerializer, GoodsDeliverReturnViewSerializer, GoodsDeliverReturnSerializer, \
    GoodsDeliverReturnDetailSerializer
from apps.goods.models import Goods
from apps.product.models import ProductBase
from apps.base import Formater
from django.conf import settings
from apps.foundation.models import BizLog, Option
from resources import SaleOrderResource, SaleOrderDetailResource, GoodsDeliverDetailResource, GoodsDeliverResource, \
    GoodsDeliverQueryResource, GoodsDeliverReturnQueryResource, SaleOrderEntryImporter
from apps.finance.models import dbFinanceIncome
from apps.finance.serializers import FinanceIncomeSerializer
from apps.customer.models import Customer

@csrf_exempt
@permission_required('order.view_sale_order')
def sale_order_list(request):
    department_ids = request.user.getSubDepartmentIds()
    user_ids = request.user.getSubEmployeeIds()
    rows = SaleOrder.objects.filter(Q(department_id__in=department_ids) | Q(create_user_id__in=user_ids) | Q(create_user=request.user))
    f = SaleOrderFilter(request.GET, queryset=rows)
    total_row = f.qs.aggregate(
        sum_count=Sum('count'),
        sum_amount=Sum('amount'),
        sum_receive_count=Sum('receive_count'),
        sum_receive_amount=Sum('receive_amount'),
        sum_pay_amount=Sum('pay_amount'),
        sum_put_amount=Sum('put_amount'),
        sum_fare_amount=Sum('fare_amount'),
        sum_loss_amount=Sum('loss_amount')
    )
    more = {
        'sum_count': Formater.formatCountShow(total_row['sum_count']),
        'sum_amount': Formater.formatAmountShow(total_row['sum_amount']),
        'sum_receive_count': Formater.formatCountShow(total_row['sum_receive_count']),
        'sum_receive_amount': Formater.formatAmountShow(total_row['sum_receive_amount']),
        'sum_pay_amount': Formater.formatAmountShow(total_row['sum_pay_amount']),
        'sum_put_amount': Formater.formatAmountShow(total_row['sum_put_amount']),
        'sum_fare_amount': Formater.formatAmountShow(total_row['sum_fare_amount']),
        'sum_loss_amount': Formater.formatAmountShow(total_row['sum_loss_amount']),
        'sum_total_amount': Formater.formatAmountShow((total_row['sum_receive_amount'] or 0)-(total_row['sum_loss_amount'] or 0)),
    }
    rows, total = utils.get_page_data(request, f.qs)
    serializer = SaleOrderSerializer(rows, many=True)
    return DataGridJSONResponse(serializer.data, total, more)


@csrf_exempt
@permission_required('order.export_sale_order')
def sale_order_export(request):
    department_ids = request.user.getSubDepartmentIds()
    user_ids = request.user.getSubEmployeeIds()
    rows = SaleOrder.objects.filter(Q(department_id__in=department_ids) | Q(create_user_id__in=user_ids) | Q(create_user=request.user))
    f = SaleOrderFilter(request.GET, queryset=rows)
    serializer = SaleOrderSerializer(f.qs, many=True)
    export_data = ExportChange.dict_to_obj(serializer)
    export_data = SaleOrderResource().export(export_data)
    filename = utils.attachment_save(export_data)
    BizLog.objects.addnew(request.user, BizLog.EXPORT, u"导出销售单")
    return JSONResponse({'filename': filename})

@csrf_exempt
@permission_required('order.add_sale_order')
def sale_order_save(request):
    source = request.GET.get('source')
    id = request.GET.get('id')
    # detail_id:添加保存，销售计划直接保存，不需要添加明细detail_id=-1，添加明细保存默认detail_id=0，修改保存，detail_id=明细id
    detail_id = -1
    if source == 'touch':
        detail_id = json.loads(request.body)['detail']
    data = json.loads(request.body)

    try:
        with transaction.atomic():
            pb = SaleOrderSerializer.factory(request.user, data['order_data'],id)
            if pb.instance and pb.instance.status == settings.PASS:
                raise CustomError(u'该订单已审核, 不允许修改')
            pb = pb.validSave()
            if source == 'touch' and detail_id >= 0:
                # 手机端保存，如果是修改，先删除要修改的明细
                SaleOrderDetail.objects.filter(id=int(detail_id)).delete()
                for item in data['items']:
                    item['main'] = pb.id
                    pbd = SaleOrderDetailSerializer.factory(request.user, item)
                    pbd.validSave()
            else:
                SaleOrderDetail.objects.filter(main_id=pb.id).delete()
                for item in data['items']:
                    item['main'] = pb.id
                    pbd = SaleOrderDetailSerializer.factory(request.user, item)
                    pbd.validSave()

            pb.updateAmount()

    except CustomError, e:
        return JSONError(e.get_error_msg())
    except Exception, e:
        traceback.print_exc()
        return JSONError(u'保存失败')
    return JSONResponse(pb.id)

@csrf_exempt
@token_required
def sale_order_detail(request):
    id = request.GET.get('id')
    warehouse_id = request.GET.get('warehouse_id')
    sale_order = SaleOrder.getById(id)
    rows = SaleOrderDetail.objects.filter(main_id=id)
    company = SaleOrder.getById(id).department.getCompany()
    if sale_order.status == settings.PASS:
        check_status = u'已审核'
    else:
        check_status = u'待审核'
    main_data = {
        'id': sale_order.id,
        'no': sale_order.no,
        'total_count': Formater.formatCountShow(sale_order.count),
        'total_amount': Formater.formatAmountShow(sale_order.amount),
        'loss_amount': Formater.formatAmountShow(sale_order.loss_amount),
        'name': sale_order.customer.name,
        'mobile': sale_order.customer.mobile,
        'customer_id': sale_order.customer.id,
        'status': check_status,
        'status_id': sale_order.status,
        'check_user': sale_order.check_user and sale_order.check_user.name or '',
        'create_user': sale_order.create_user and sale_order.create_user.name or '',
        'check_time': sale_order.check_time and Formater.formatStrTime(sale_order.check_time) or '',
        'create_time': Formater.formatStrTime(sale_order.create_time),
        'notes': sale_order.notes or '',
        'loss_notes': sale_order.loss_notes or '',
    }
    data = {
        'main_data':main_data,
        'company': company.name,
        'items_data': []
    }
    for row in rows:
        item = {
            'id': row.id,
            'goods_id': row.goods_id,
            'product_id': row.goods.product_base_id,
            'unit': row.goods.product_base.unit,
            'name': row.goods.product_base.name,
            'model': row.goods.product_base.model,
            'quality_request': row.quality_request and row.quality_request.id or '',
            'quality_request_text': row.quality_request and row.quality_request.name or '',
            'warehouse_place': row.goods.product_base.warehouse_place,
            'count': Formater.formatCountShow(row.count),
            'receive_count': Formater.formatCountShow(row.receive_count),
            'price': Formater.formatPriceShow(row.price),
            'amount': Formater.formatAmountShow(row.amount)
        }
        if warehouse_id:
            record_data = GetWarehouseSrockRecord.getRecord(row.goods.product_base.id, warehouse_id)
            item['record_data'] = record_data
        data['items_data'].append(item)
    return JSONResponse(data)

@csrf_exempt
@permission_required('order.delete_sale_order')
def sale_order_delete(request):
    id = int(request.GET.get('id'))
    try:
        with transaction.atomic():
            order = SaleOrder.getById(id)
            if order.status != settings.DEFAULT:
                raise CustomError(u'该订单已审核, 不允许删除')
            BizLog.objects.addnew(request.user, BizLog.DELETE, u"删除销售订单[%s]，id=%d" % (order.no, order.id))
            SaleOrderDetail.objects.filter(main=order).delete()
            SaleOrderMessage.objects.filter(main=order).delete()
            order.delete()
    except CustomError, e:
        return JSONError(e.get_error_msg())
    except ProtectedError:
        return JSONError(u'该销售订单已被引用，禁止删除！')
    except IntegrityError:
        return JSONError(u'该销售订单已被引用，禁止删除！')
    except Exception, e:
        traceback.print_exc()
        return JSONError(u'删除失败！')

    return JSONResponse({})

@csrf_exempt
@permission_required('order.check_sale_order')
def sale_order_check(request):
    id = request.GET.get('id')
    status = int(request.GET.get('status'))

    try:
        with transaction.atomic():
            order = SaleOrder.getById(id)
            if status == settings.PASS:
                if order.status != settings.DEFAULT:
                    raise CustomError(u'该订单已审核')
                order.status = settings.PASS
                order.check_user = request.user
                order.check_time = timezone.now()

                SaleOrderDetail.objects.filter(main_id=order.id).update(receive_count=F('count'))

                order.updateReceiveAmount()

                BizLog.objects.addnew(
                    request.user,
                    BizLog.CHECK,
                    u"审核销售订单[%s]，id=%d" % (order.no, order.id),
                )
            else:
                if order.status == settings.DEFAULT:
                    raise CustomError(u'该订单尚未审核')
                deliver = GoodsDeliver.objects.filter(sale_order=order).first()
                if deliver:
                    raise CustomError(u'该订单已转出库, 不允许撤销审核')
                order.status = settings.DEFAULT
                order.check_user = None
                order.check_time = None

                SaleOrderDetail.objects.filter(main_id=order.id).update(receive_count=0)
                order.updateReceiveAmount()

                BizLog.objects.addnew(
                    request.user,
                    BizLog.CHECK,
                    u"取消审核销售订单[%s]，id=%d" % (order.no, order.id),
                )
            order.save()
    except CustomError, e:
        return JSONError(e.get_error_msg())
    except Exception, e:
        traceback.print_exc()
        return JSONError(u'审核失败')
    return JSONResponse({})

@csrf_exempt
@permission_required('order.loss_sale_order')
def sale_order_loss_save(request):
    id = request.GET.get('id')
    data = json.loads(request.body)

    try:
        with transaction.atomic():
            order = SaleOrder.getById(id)
            if order.status == settings.DEFAULT:
                raise CustomError(u'该订单尚未审核')
            loss_amount = data['order_data']['amount']
            loss_notes = data['order_data']['notes']
            for item in data['items']:
                detail = SaleOrderDetail.objects.filter(id=item['detail_id']).first()
                detail.receive_count = Formater.formatCount(item['receive_count'])
                detail.save()

            order.updateReceiveAmount()
            order.loss_amount = Formater.formatAmount(loss_amount)
            order.loss_notes = loss_notes
            order.save()
            BizLog.objects.addnew(
                request.user,
                BizLog.UPDATE,
                u"销售订单[%s]扣减，id=%d" % (order.no, order.id),
            )

    except CustomError, e:
        return JSONError(e.get_error_msg())
    except Exception, e:
        traceback.print_exc()
        return JSONError(u'保存失败')
    return JSONResponse({})


@csrf_exempt
@permission_required('order.pay_sale_order')
def sale_order_pay(request):
    id = request.GET.get('id')
    data = json.loads(request.body)

    try:
        with transaction.atomic():
            order = SaleOrder.getById(id)
            if order.status == settings.DEFAULT:
                raise CustomError(u'该订单尚未审核')
            if order.cleared:
                raise CustomError(u'该订单已结清')

            order.pay_amount += Formater.formatAmount(data['actual_amount'])
            order.save()
            total_amount = order.receive_amount - order.loss_amount

            if order.pay_amount >= total_amount:
                order.cleared = True
                order.save()

            income_data = {
                'referer_no': order.no,
                'type': dbFinanceIncome.SALE_ENTRY_PAY,
                'amount': data['actual_amount'],
                'account': data['account'],
                'check_status': settings.PASS,
                'check_user':request.user.id,
                'department':request.user.department_id,
                'check_time': timezone.now(),
                'notes': data['notes']
            }

            income = FinanceIncomeSerializer.factory(request.user, income_data)
            income.validSave()

    except CustomError, e:
        return JSONError(e.get_error_msg())
    except Exception, e:
        traceback.print_exc()
        return JSONError(u'保存失败')
    return JSONResponse({})


@csrf_exempt
@permission_required('order.pay_sale_order')
def sale_order_fare_save(request):
    id = request.GET.get('id')
    data = json.loads(request.body)

    try:
        with transaction.atomic():
            order = SaleOrder.getById(id)
            fare_amount = data['fare_amount']
            fare_account = data['fare_account']
            put_amount = data['put_amount']
            put_account = data['put_account']

            if fare_amount != 0:
                if not fare_account:
                    raise CustomError(u'请选择运费账户')
                fare_amount = Formater.formatAmount(fare_amount)
                order.fare_amount += fare_amount

                income_data = {
                    'referer_no': order.no,
                    'type': dbFinanceIncome.SALE_ENTRY_FARE,
                    'amount': -data['fare_amount'],
                    'account': fare_account,
                    'check_status': settings.PASS,
                    'check_user': request.user.id,
                    'department': request.user.department_id,
                    'check_time': timezone.now()
                }

                pb = FinanceIncomeSerializer.factory(request.user, income_data)
                pb.validSave()

            if put_amount != 0:
                if not put_account:
                    raise CustomError(u'请选择装车费账户')
                put_amount = Formater.formatAmount(put_amount)
                order.put_amount += put_amount

                income_data = {
                    'referer_no': order.no,
                    'type': dbFinanceIncome.SALE_ENTRY_UNLOAD,
                    'amount': -data['put_amount'],
                    'account': put_account,
                    'check_status': settings.PASS,
                    'check_user': request.user.id,
                    'department': request.user.department_id,
                    'check_time': timezone.now()
                }

                pb = FinanceIncomeSerializer.factory(request.user, income_data)
                pb.validSave()

            order.save()

    except CustomError, e:
        return JSONError(e.get_error_msg())
    except Exception, e:
        traceback.print_exc()
        return JSONError(u'保存失败')
    return JSONResponse({})


@csrf_exempt
@permission_required('order.pay_sale_order')
def sale_order_clear(request):
    id = request.GET.get('id')

    try:
        with transaction.atomic():
            order = SaleOrder.getById(id)
            if order.status == settings.DEFAULT:
                raise CustomError(u'该订单未审核')

            if order.cleared:
                raise CustomError(u'该订单已结清')

            order.cleared = True
            order.save()
            BizLog.objects.addnew(
                request.user,
                BizLog.CHECK,
                u"销售订单[%s]结清，id=%d" % (order.no, order.id),
            )

    except CustomError, e:
        return JSONError(e.get_error_msg())
    except Exception, e:
        traceback.print_exc()
        return JSONError(u'结清失败')
    return JSONResponse({})


@csrf_exempt
@permission_required('order.view_sale_order')
def sale_order_msg_save(request):
    id = request.GET.get('id')
    data = json.loads(request.body)

    try:
        with transaction.atomic():
            order = SaleOrder.getById(id)
            SaleOrderMessage.objects.filter(main=order).delete()
            options = Option.objects.filter(type=Option.SALE_MESSAGE, enabled=True)
            for option in options:
                content = data[str(int(option.id))]
                if content:
                    SaleOrderMessage.objects.create(main=order, item_id=option.id, content=content)

    except CustomError, e:
        return JSONError(e.get_error_msg())
    except Exception, e:
        traceback.print_exc()
        return JSONError(u'完善失败')
    return JSONResponse({})


@csrf_exempt
@permission_required('order.view_sale_order')
def sale_order_msg(request):
    id = request.GET.get('id')

    rows = Option.objects.filter(type=Option.SALE_MESSAGE, enabled=True)
    data = []
    for row in rows:
        item = {
            'id': row.id,
            'name': row.name,
            'content': ''
        }

        msg_row = SaleOrderMessage.objects.filter(main_id=id, item_id=row.id).first()
        if msg_row:
            item['content'] = msg_row.content

        data.append(item)

    return JSONResponse(data)

@csrf_exempt
@permission_required('order.export_sale_order')
def sale_order_export_detail(request):
    id = request.GET.get('id')
    serializer = SaleOrderDetailSerializer(SaleOrderDetail.objects.filter(main_id=id), many=True)
    export_data = ExportChange.dict_to_obj(serializer)
    export_data = SaleOrderDetailResource().export(export_data)
    filename = utils.attachment_save(export_data)
    BizLog.objects.addnew(request.user, BizLog.EXPORT, u"导出销售单明细")
    return JSONResponse({'filename': filename})

@csrf_exempt
@permission_required('order.export_sale_order')
def sale_order_import(request):
    file = request.FILES.get('excel_file')

    try:
        line = 2
        importer = SaleOrderEntryImporter()
        excel_rows = importer.getExcelData(file)
        with transaction.atomic():
            for excel_row in excel_rows:
                try:
                    row = importer.validRow(excel_row)
                    name = row[u'客户姓名']
                    tel = row[u'客户电话']
                    notes = row[u'备注'] or ''
                    count = int(row[u'数量'])
                    price = row[u'单价']
                    customer = Customer.objects.filter(Q(mobile=tel) | Q(company_tel=tel)).first()
                    if not customer:
                        customer = Customer.objects.create(
                            mobile=tel,
                            company_tel=tel,
                            name=name,
                            company_name=name,
                            create_user=request.user,
                        )
                    main_data = {
                        'customer':customer.id,
                        'notes':notes,
                        'create_user':request.user,
                        'count':0,
                        'price':0,
                    }
                    serializer = SaleOrderSerializer.factory(request.user, main_data)
                    serializer = serializer.validSave()
                    product = row[u'产品名称']
                    model = row[u'产品代码']
                    goods = Goods.objects.filter(product_base__model=model, product_base__type=ProductBase.GOODS)
                    if goods.count() == 0:
                        raise CustomError(u'产品代码不存在')
                    elif goods.count() > 1:
                        raise CustomError(u'产品代码重复，前往基础数据设置修改')
                    else:
                        goods = goods.first()
                    items_data = {}
                    items_data['goods'] = goods.id
                    items_data['main'] = serializer.id
                    items_data['price'] = price
                    items_data['count'] = count
                    detail_serializer = SaleOrderDetailSerializer.factory(request.user, items_data)
                    detail_serializer.validSave()
                    serializer.updateAmount()
                except CustomError, e:
                    raise CustomError(u'第%d行:%s' % (line, e.get_error_msg()))
                except Exception, e:
                    raise CustomError(u'第%d行:%s' % (line, unicode(e)))
                line += 1
            BizLog.objects.addnew(request.user, BizLog.IMPORT, u"导入销售订单[%s]，id=%d" % (serializer.no, serializer.id))
    except CustomError, e:
        return JSONError(e.get_error_msg())
    except Exception, e:
        traceback.print_exc()
        return JSONError(u'导入失败！')
    return JSONResponse()

@token_required
def sale_order_select(request):
    param = request.GET.get('keywords')
    rows = SaleOrder.objects.filter()
    if param:
        rows = rows.filter(no__icontains=param)
        serializer = SaleOrderSerializer(rows, many=True)
        return JSONResponse(serializer.data)


@csrf_exempt
@permission_required('order.view_goods_deliver')
def deliver_list(request):
    product_notes = request.GET.get('product_notes')
    warehouses_ids = Warehouse.getManagerWarehouses(request.user)
    department_ids = request.user.getSubDepartmentIds()
    user_ids = request.user.getSubEmployeeIds()
    rows = GoodsDeliver.objects.filter(warehouse_id__in=warehouses_ids)
    rows = rows.filter(
        Q(department_id__in=department_ids) | Q(create_user_id__in=user_ids) | Q(create_user=request.user))

    if product_notes:
        g_ids = rows.values_list('id')
        d_ids = GoodsDeliverDetail.objects.filter(main_id__in=g_ids, notes__icontains=product_notes).values_list('main_id')
        rows = rows.filter(id__in=d_ids)
    f = GoodsDeliverFilter(request.GET, queryset=rows)
    total_row = f.qs.aggregate(total_count=Sum('total_count'), total_cost=Sum('total_cost'),
                               total_amount=Sum('total_amount'))
    more = {
        'total_count': Formater.formatCountShow(total_row['total_count']),
        'total_cost': Formater.formatAmountShow(total_row['total_cost']),
        'return_count': Formater.formatAmountShow(total_row['total_amount']),
    }
    rows, total = utils.get_page_data(request, f.qs)
    serializer = GoodsDeliverSerializer(rows, many=True)
    return DataGridJSONResponse(serializer.data, total, more)


@csrf_exempt
@permission_required('order.export_goods_deliver')
def deliver_export(request):
    id = request.GET.get('id')
    try:
        perm = 'goods.view_goods_cost'
        is_show_cost = isHasPermissions(request.user, perm)
        if id:
            instance = GoodsDeliver.getById(id)
            deliver_detail = GoodsDeliverDetail.objects.filter(main=instance)
            serializer = GoodsDeliverDetailSerializer(deliver_detail, many=True)
            export_data = ExportChange.dict_to_obj(serializer)
            export_data = GoodsDeliverDetailResource(is_show_cost).export(export_data)
            filename = utils.attachment_save(export_data)
            BizLog.objects.addnew(request.user, BizLog.EXPORT, u"导出成品出库单[%s]明细，id=%d" % (instance.no, instance.id))
        else:
            warehouses_ids = Warehouse.getManagerWarehouses(request.user)
            department_ids = request.user.getSubDepartmentIds()
            user_ids = request.user.getSubEmployeeIds()
            rows = GoodsDeliver.objects.filter(warehouse_id__in=warehouses_ids)
            rows = rows.filter(
                Q(department_id__in=department_ids) | Q(create_user_id__in=user_ids) | Q(create_user=request.user))
            f = GoodsDeliverFilter(request.GET, queryset=rows)
            serializer = GoodsDeliverSerializer(f.qs, many=True)
            export_data = ExportChange.dict_to_obj(serializer)
            export_data = GoodsDeliverResource(is_show_cost).export(export_data)
            filename = utils.attachment_save(export_data)
            BizLog.objects.addnew(request.user, BizLog.EXPORT, u"导出成品出库单")
    except CustomError, e:
        return JSONError(e.get_error_msg())
    except Exception, e:
        traceback.print_exc()
        return JSONError(u'导出失败！')
    return JSONResponse({'filename': filename})


@csrf_exempt
@permission_required('order.add_goods_deliver')
def deliver_save(request):
    source = request.GET.get('source')
    id = request.GET.get('id')
    detail_id = -1
    if source == 'touch':
        main_data = json.loads(request.body)['main']
        items_data = json.loads(request.body)['item']
        detail_id = json.loads(request.body)['detail']
    else:
        main_data = json.loads(request.POST.get('main'))
        items_data = json.loads(request.POST.get('item'))
    try:
        with transaction.atomic():
            serializer = GoodsDeliverSerializer.factory(request.user, main_data, id)
            if serializer.instance and serializer.instance.status == settings.PASS:
                raise CustomError(u'该出库单已审核，禁止修改！')
            serializer = serializer.validSave()
            if source == 'touch' and detail_id >= 0:
                # 手机端保存，如果是修改，先删除要修改的明细
                GoodsDeliverDetail.objects.filter(id=int(detail_id)).delete()
                for item in items_data:
                    product_base_id = Goods.getById(item['product_base']).product_base.id
                    warehouse_stock = WarehouseStock.getByWarehouseAndProduct(serializer.warehouse,product_base_id)
                    instance = GoodsDeliverDetail.objects.create(
                        main_id=id,
                        product_base_id=item['product_base'],
                        warehouse_stock=warehouse_stock,
                        warehouse_stockrecord_id=item['warehouse_stockrecord'],
                        total_cost=Formater.formatAmount(item['total_cost']),
                        count=Formater.formatCount(item['count']),
                        price=Formater.formatPrice(item['price']),
                        total_amount=Formater.formatPrice(item['price']) * Formater.formatCount(item['count']),
                        notes=item['notes'],
                    )
                    BizLog.objects.addnew(
                        request.user,
                        BizLog.INSERT,
                        u"APP添加原料/耗材出库明细[%s]，id=%d" % (instance.product_base.product_base.name, instance.id),
                        item
                    )
            else:
                GoodsDeliverDetail.objects.filter(main=serializer).delete()
                for item in items_data:
                    item['main'] = serializer.id
                    item['product_base'] = Goods.getByBaseId(item['product_base']).id
                    if not item['warehouse_stockrecord']:
                        2 # todo 不选入库单号，自动选择入库单
                    detail_serializer = GoodsDeliverDetailSerializer.factory(request.user, data=item)
                    detail_serializer.validSave()
            serializer.update_total()
    except CustomError, e:
        return JSONError(e.get_error_msg())
    except Exception, e:
        traceback.print_exc()
        return JSONError(u'保存失败！')
    return JSONResponse(serializer.id)

@csrf_exempt
@permission_required('order.add_goods_deliver')
def deliver_save_mult(request):
    # 销售订单，批量转出库
    from apps.warehouse.models import WarehouseStockRecord
    try:
        with transaction.atomic():
            order_details = SaleOrderDetail.objects.filter().exclude(id=1654)
            print 2222222,order_details.count()
            for order_detail in order_details:
                main_data = {'customer': order_detail.main.customer.id,
                              'agent_user': 1,
                              # 'customer_text': '{}-{}'.format(order_detail.main.customer.name,order_detail.main.customer.mobile),
                              'notes': '',
                              'sale_order_no': order_detail.main.no,
                              'sale_order': order_detail.main.id,
                              'warehouse': 16
                              }
                # print 1111111111,main_data
                serializer = GoodsDeliverSerializer.factory(request.user, main_data)
                if serializer.instance and serializer.instance.status == settings.PASS:
                    raise CustomError(u'该出库单已审核，禁止修改！')
                serializer = serializer.validSave()
                # print 222222,serializer.id
                GoodsDeliverDetail.objects.filter(main=serializer).delete()
                warehouse_stockrecord = WarehouseStockRecord.objects.filter(product=order_detail.goods.product_base, warehouse_id=16).first()
                # print 3333333333, warehouse_stockrecord.id
                items_data = {
                                'count': Formater.formatCountShow(order_detail.count),
                              'warehouse_stockrecord': warehouse_stockrecord.id,
                              'total_cost': Formater.formatAmountShow(warehouse_stockrecord.entry_price * order_detail.count),
                              'price': Formater.formatPriceShow(order_detail.price),
                              'product_base': order_detail.goods.id,
                              'notes': u'',
                              'main': serializer.id,
                              }
                # print 444444444, items_data
                detail_serializer = GoodsDeliverDetailSerializer.factory(request.user, data=items_data)
                detail_serializer.validSave()
                serializer.update_total()
    except CustomError, e:
        return JSONError(e.get_error_msg())
    except Exception, e:
        traceback.print_exc()
        return JSONError(u'保存失败！')
    return JSONResponse(serializer.id)


@csrf_exempt
@permission_required('order.delete_goods_deliver')
def deliver_delete(request):
    id = request.GET.get('id')
    try:
        with transaction.atomic():
            instance = GoodsDeliver.getById(id)
            if instance.status == settings.PASS:
                raise CustomError(u'该出库单已审核，禁止删除！')

            BizLog.objects.addnew(request.user, BizLog.DELETE, u"删除成品出库单[%s]，id=%d" % (instance.no, instance.id))
            GoodsDeliverDetail.objects.filter(main=instance).delete()
            instance.delete()
    except CustomError, e:
        return JSONError(e.get_error_msg())
    except ProtectedError:
        return JSONError(u'该出库单已被以用，禁止删除！')
    except IntegrityError:
        return JSONError(u'该出库单已被以用，禁止删除！')
    except Exception, e:
        traceback.print_exc()
        return JSONError(u'删除失败！')

    return JSONResponse({})


@token_required
def deliver_detail(request):
    id = request.GET.get('id')
    instance = GoodsDeliver.getById(id)
    company = instance.department.getCompany()
    if instance.status == settings.PASS:
        status_text = u'已审核'
    else:
        status_text = u'待审核'
    main_data = {
        'sale_order_id': instance.sale_order_id or '',
        'id': instance.id,
        'company': company.name,
        'sale_order_no': instance.sale_order and instance.sale_order.no or '',
        'customer_name': instance.customer and instance.customer.name or '',
        'customer_id': instance.customer_id or '',
        'customer_tel': instance.customer and instance.customer.mobile or '',
        'agent_user_id': instance.agent_user_id,
        'agent_user_name': instance.agent_user.name,
        'agent_department_name': instance.agent_department and instance.agent_department.name or '',
        'warehouse_id': instance.warehouse_id,
        'warehouse_name': instance.warehouse.name,
        'create_user_name': instance.create_user.name,
        'create_time': Formater.formatStrTime(instance.create_time),
        'total_count': Formater.formatCountShow(instance.total_count),
        'total_amount': Formater.formatAmountShow(instance.total_amount),
        'total_cost': Formater.formatAmountShow(instance.total_cost),
        'status': instance.status,
        'status_text': status_text,
        'check_user_text': instance.check_user and instance.check_user.name or ' ',
        'check_time': Formater.formatStrTime(instance.create_time),
        'notes': instance.notes,
        'no': instance.no
    }

    data = {
        'main_data': main_data,
        'items_data': []
    }
    detail_rows = GoodsDeliverDetail.objects.filter(main=instance)
    for detail_row in detail_rows:
        no = ''
        if detail_row.warehouse_stockrecord_id:
            godownentry = GoodsGodownEntryDetail.objects.filter(stock_record=detail_row.warehouse_stockrecord).first()
            if godownentry:
                no = godownentry.main.no
            else:
                no = InventoryDetail.objects.filter(warehouse_stock_record=detail_row.warehouse_stockrecord).first().main.no
        record_data = GetWarehouseSrockRecord.getRecord(detail_row.product_base.product_base.id, instance.warehouse_id)
        item_data = {
            'id': detail_row.product_base_id,
            'product_base': detail_row.product_base.product_base_id,
            'detail_id': detail_row.id,
            'name': detail_row.product_base.product_base.name,
            'model': detail_row.product_base.product_base.model,
            'total_cost': Formater.formatAmountShow(detail_row.total_cost),
            'total_amount': Formater.formatAmountShow(detail_row.total_amount),
            'count': Formater.formatCountShow(detail_row.count),
            'price': Formater.formatPriceShow(detail_row.price),
            'warehouse_stock_count': Formater.formatCountShow(detail_row.warehouse_stock.count),
            'unit': detail_row.product_base.product_base.unit or '',
            'notes': detail_row.notes or '',
            'entry_no': detail_row.warehouse_stockrecord_id,
            'record_data': record_data,
            'no': no,
        }
        data['items_data'].append(item_data)

    return JSONResponse(data)




@csrf_exempt
@permission_required('order.check_goods_deliver')
def deliver_check(request):
    id = request.GET.get('id')
    try:
        with transaction.atomic():
            instance = GoodsDeliver.getById(id)
            if instance.status == settings.PASS:
                raise CustomError(u'该出库单已审核')
            deliver_details = GoodsDeliverDetail.objects.filter(main=instance)
            for deliver_detail in deliver_details:
                if instance.sale_order:
                    type = WarehouseRecord.CK_XS
                else:
                    type = WarehouseRecord.CK_ZJ
                warehouse_record = BizWarehouse.deliveredByStockRecord(type,
                                                  deliver_detail.warehouse_stockrecord,
                                                  deliver_detail.count)
                deliver_detail.warehouse_record = warehouse_record
                deliver_detail.total_cost = -warehouse_record.amount
                deliver_detail.save()
            instance.update_total()
            instance.status = settings.PASS
            instance.check_user = request.user
            instance.check_time = timezone.now()
            BizLog.objects.addnew(
                request.user,
                BizLog.CHECK,
                u"审核成品出库[%s]，id=%d" % (instance.no, instance.id),
            )

            instance.save()
    except CustomError, e:
        return JSONError(e.get_error_msg())
    except Exception, e:
        traceback.print_exc()
        return JSONError(u'审核失败')
    return JSONResponse({})


@csrf_exempt
@permission_required('order.view_goods_deliver_query')
def deliver_query_list(request):# 成品出库查询
    rows = get_filter_data(request)
    total_row = rows.aggregate(total_count1=Sum('goods_deliver_detail_ref_warehouse_record__count'),
                               total_count2=Sum('inventory_details_ref_warehouse_record__count'),
                               total_cost1=Sum('goods_deliver_detail_ref_warehouse_record__total_cost'),
                               total_cost2=Sum('inventory_details_ref_warehouse_record__amount'),
                               total_amount=Sum('goods_deliver_detail_ref_warehouse_record__total_amount'),
                               return_count=Sum('goods_deliver_detail_ref_warehouse_record__return_count'),
                               return_cost=Sum('goods_deliver_detail_ref_warehouse_record__return_cost'))
    more = {
        'total_count': Formater.formatCountShow((total_row['total_count1'] or 0) + (total_row['total_count2'] or 0)),
        'total_cost': Formater.formatAmountShow((total_row['total_cost1'] or 0) + (total_row['total_cost2'] or 0)),
        'total_amount': Formater.formatAmountShow(total_row['total_amount']),
        'return_count': Formater.formatCountShow(total_row['return_count']),
        'return_cost': Formater.formatAmountShow(total_row['return_cost']),
    }
    rows, total = utils.get_page_data(request, rows)
    data = get_deliver_query_data(rows)
    return DataGridJSONResponse(data, total, more)

@csrf_exempt
@permission_required('order.export_goods_deliver_query')
def deliver_query_export(request):
    try:
        rows = get_filter_data(request)
        data = get_deliver_query_data(rows)
        export_data = ExportChange.dict_to_obj2(data)
        perm = 'goods.view_goods_cost'
        is_show_cost = isHasPermissions(request.user, perm)
        export_data = GoodsDeliverQueryResource(is_show_cost).export(export_data)
        filename = utils.attachment_save(export_data)
        BizLog.objects.addnew(request.user, BizLog.EXPORT, u"导出成品出库查询")
    except CustomError, e:
        return JSONError(e.get_error_msg())
    except Exception, e:
        traceback.print_exc()
        return JSONError(u'导出出库查询失败！')
    return JSONResponse({'filename': filename})


@token_required
def deliver_query_detail(request):
    rows = get_filter_data(request)
    data = get_deliver_query_data(rows)
    return JSONResponse(data)

def get_filter_data(request):
    happen_time = request.GET.get('happen_time')
    no = request.GET.get('no')
    create_user = request.GET.get('create_user')
    name = request.GET.get('name')
    model = request.GET.get('model')
    type = request.GET.get('type')
    warehouse = request.GET.get('warehouse')
    notes = request.GET.get('notes')
    rows = WarehouseRecord.objects.filter(product__type=2, type__in=[3,4,5]).order_by('-id')
    if happen_time:
        happen_time_begin = happen_time.split(' - ')[0]
        happen_time_end = happen_time.split(' - ')[1] + ' 23:59:59'
        rows = rows.filter(happen_time__gt=happen_time_begin,happen_time__lt=happen_time_end)
    if no:
        rows = rows.filter(Q(goods_deliver_detail_ref_warehouse_record__main__no__icontains=no) | Q(inventory_details_ref_warehouse_record__main__no__icontains=no))
    if create_user:
        rows = rows.filter(Q(goods_deliver_detail_ref_warehouse_record__main__create_user__name__icontains=create_user) |
                           Q(inventory_details_ref_warehouse_record__main__create_user__name__icontains=create_user))
    if notes:
        rows = rows.filter(Q(goods_deliver_detail_ref_warehouse_record__notes__icontains=notes) |
                           Q(inventory_details_ref_warehouse_record__notes__icontains=notes))
    if name:
        rows = rows.filter(product__name__icontains=name)
    if model:
        rows = rows.filter(product__model__icontains=model)
    if type:
        rows = rows.filter(type=type)
    if warehouse:
        rows = rows.filter(warehouse__name__icontains=warehouse)

    warehouses_ids = Warehouse.getManagerWarehouses(request.user)
    department_ids = request.user.getSubDepartmentIds()
    user_ids = request.user.getSubEmployeeIds()
    rows = rows.filter(warehouse_id__in=warehouses_ids)
    rows = rows.filter(
        Q(goods_deliver_detail_ref_warehouse_record__main__department_id__in=department_ids) |
        Q(goods_deliver_detail_ref_warehouse_record__main__create_user_id__in=user_ids) |
        Q(goods_deliver_detail_ref_warehouse_record__main__create_user=request.user) |
        Q(inventory_details_ref_warehouse_record__main__department_id__in=department_ids) |
        Q(inventory_details_ref_warehouse_record__main__create_user_id__in=user_ids) |
        Q(inventory_details_ref_warehouse_record__main__create_user=request.user)
    )
    return rows

def get_deliver_query_data(rows):
    rows = rows.values(
        'id',
        'type',
        'product__name',
        'product__model',
        'product__unit',
        'product__type',
        'product__warehouse_place',
        # 盘亏
        'inventory_details_ref_warehouse_record__count',
        'inventory_details_ref_warehouse_record__price',
        'inventory_details_ref_warehouse_record__amount',
        'inventory_details_ref_warehouse_record__notes',


        'warehouse__name',
        'happen_time',
        'cur_count',
        'goods_deliver_detail_ref_warehouse_record__count',
        'goods_deliver_detail_ref_warehouse_record__price',
        'goods_deliver_detail_ref_warehouse_record__total_cost',
        'goods_deliver_detail_ref_warehouse_record__total_amount',
        'goods_deliver_detail_ref_warehouse_record__return_count',
        'goods_deliver_detail_ref_warehouse_record__return_cost',
        'goods_deliver_detail_ref_warehouse_record__notes',
        'goods_deliver_detail_ref_warehouse_record__main__check_user__name',
        'goods_deliver_detail_ref_warehouse_record__main__create_user__name',
        'goods_deliver_detail_ref_warehouse_record__main__check_time',
        'goods_deliver_detail_ref_warehouse_record__main__no',
        'goods_deliver_detail_ref_warehouse_record__warehouse_stockrecord__goods_godown_entry_detail_ref_stock_record__main__no',
        'goods_deliver_detail_ref_warehouse_record__warehouse_stockrecord__inventory_details_ref_warehouse_stock_record__main__no',
        # 盘亏
        'inventory_details_ref_warehouse_record__main__no',
        'inventory_details_ref_warehouse_record__main__check_user__name',
        'inventory_details_ref_warehouse_record__main__create_user__name',
        'inventory_details_ref_warehouse_record__main__check_time',


    )
    data = []
    for row in rows:
        warehouse_record_type = WarehouseRecord.TYPE_CHOICES[row['type']][1]
        product_type_text = ProductBase.TYPE_CHOICES[row['product__type']][1]

        no = row['goods_deliver_detail_ref_warehouse_record__main__no']
        check_user = row['goods_deliver_detail_ref_warehouse_record__main__check_user__name']
        create_user = row['goods_deliver_detail_ref_warehouse_record__main__create_user__name']
        check_time = Formater.formatStrTime(row['goods_deliver_detail_ref_warehouse_record__main__check_time'])
        notes = row['goods_deliver_detail_ref_warehouse_record__notes']
        name = row['product__name']
        model = row['product__model']
        unit = row['product__unit']
        warehouse_place = row['product__warehouse_place']
        count = Formater.formatCountShow(row['goods_deliver_detail_ref_warehouse_record__count'])
        entry_no = row['goods_deliver_detail_ref_warehouse_record__warehouse_stockrecord__goods_godown_entry_detail_ref_stock_record__main__no']
        if not entry_no:
            entry_no = row['goods_deliver_detail_ref_warehouse_record__warehouse_stockrecord__inventory_details_ref_warehouse_stock_record__main__no']
        price = Formater.formatPriceShow(row['goods_deliver_detail_ref_warehouse_record__price'])
        total_cost = Formater.formatAmountShow(row['goods_deliver_detail_ref_warehouse_record__total_cost'])
        total_amount = Formater.formatAmountShow(row['goods_deliver_detail_ref_warehouse_record__total_amount'])
        return_count = Formater.formatCountShow(row['goods_deliver_detail_ref_warehouse_record__return_count'])
        return_cost = Formater.formatAmountShow(row['goods_deliver_detail_ref_warehouse_record__return_cost'])

        if row['type'] == WarehouseRecord.CK_PK:
            no = row['inventory_details_ref_warehouse_record__main__no']
            entry_no = ''
            check_user = row['inventory_details_ref_warehouse_record__main__check_user__name']
            create_user = row['inventory_details_ref_warehouse_record__main__create_user__name']
            check_time = Formater.formatStrTime(row['inventory_details_ref_warehouse_record__main__check_time'])
            notes = row['inventory_details_ref_warehouse_record__notes']
            count = Formater.formatCountShow(row['inventory_details_ref_warehouse_record__count'])
            price = Formater.formatPriceShow(row['inventory_details_ref_warehouse_record__price'])
            total_cost = Formater.formatAmountShow(row['inventory_details_ref_warehouse_record__amount'])
            total_amount = '0.0000'
            return_count = '0.00'
            return_cost = '0.0000'

        item = {
            'id': row['id'],
            'type': warehouse_record_type,
            'product_type': product_type_text,

            'name': name,
            'model': model,
            'unit': unit,
            'warehouse_place': warehouse_place,

            'warehouse': row['warehouse__name'],
            'happen_time': Formater.formatStrTime(row['happen_time']),
            'cur_count': Formater.formatCountShow(row['cur_count']),

            'count': count,
            'price': price,
            'total_cost': total_cost,
            'total_amount': total_amount,
            'return_count': return_count,
            'return_cost': return_cost,

            'check_user': check_user,
            'create_user': create_user,
            'check_time': check_time,
            'notes': notes,
            'no': no,
            'entry_no': entry_no,
        }
        data.append(item)
    return data


@csrf_exempt
@permission_required('order.view_goods_deliver_return')
def deliver_return_list(request):
    product_notes = request.GET.get('product_notes')
    warehouses_ids = Warehouse.getManagerWarehouses(request.user)
    department_ids = request.user.getSubDepartmentIds()
    user_ids = request.user.getSubEmployeeIds()
    rows = GoodsDeliver.objects.filter(status=settings.PASS, warehouse_id__in=warehouses_ids)
    rows = rows.filter(
        Q(department_id__in=department_ids) | Q(create_user_id__in=user_ids) | Q(create_user=request.user))

    if product_notes:
        g_ids = rows.values_list('id')
        d_ids = GoodsDeliverDetail.objects.filter(main_id__in=g_ids, notes__icontains=product_notes).values_list('main_id')
        rows = rows.filter(id__in=d_ids)
    f = GoodsDeliverReturnFilter(request.GET, queryset=rows)
    total_row = f.qs.aggregate(total_count=Sum('total_count'), total_cost=Sum('total_cost'),
                               total_amount=Sum('total_amount'), return_count=Sum('return_count'),
                               return_cost=Sum('return_cost'))
    more = {
        'total_count': Formater.formatCountShow(total_row['total_count']),
        'total_cost': Formater.formatAmountShow(total_row['total_cost']),
        'total_amount': Formater.formatAmountShow(total_row['total_amount']),
        'return_count': Formater.formatCountShow(total_row['return_count']),
        'return_cost': Formater.formatAmountShow(total_row['return_cost']),
    }
    rows, total = utils.get_page_data(request, f.qs)
    serializer = GoodsDeliverReturnViewSerializer(rows, many=True)
    return DataGridJSONResponse(serializer.data, total, more)

@token_required
def deliver_return_select_list(request):
    id = int(request.GET.get('id'))

    ids = GoodsDeliverReturnDetail.objects.filter(deliver_detail__main_id=id).values_list('main_id', flat=True)
    rows = GoodsDeliverReturn.objects.filter(id__in=ids)
    data = []
    for row in rows:
        data.append(row)
    serializer = GoodsDeliverReturnSerializer(data, many=True)
    return DataGridJSONResponse(serializer.data, rows.count())

@token_required
def deliver_return_detail(request):
    id = request.GET.get('id')
    ids = request.GET.get('ids')
    data = {
        'main_data': '',
        'deliver_data': [],
        'items_data': []
    }
    if ids:
        id_list = ids.split(',')
        deliver_returns = GoodsDeliverReturn.getByIds(id_list)
        for deliver_return in deliver_returns:
            deliver_data = {
                'no': deliver_return.no,
                'return_count': Formater.formatCountShow(deliver_return.return_count),
                'return_cost': Formater.formatAmountShow(deliver_return.return_cost),
                'reason': deliver_return.reason
            }
            data['deliver_data'].append(deliver_data)
    instance = GoodsDeliver.getById(id)
    company = instance.department.getCompany()
    main_data = {
        'customer_name': instance.customer and instance.customer.name or '',
        'customer_tel': instance.customer and instance.customer.mobile or '',
        'total_amount': Formater.formatAmountShow(instance.total_amount),
        'warehouse_id': instance.warehouse_id,
        'warehouse_name': instance.warehouse.name,
        'create_user_name': instance.create_user.name,
        'create_time': Formater.formatStrTime(instance.create_time),
        'total_count': Formater.formatCountShow(instance.total_count),
        'total_cost': Formater.formatAmountShow(instance.total_cost),
        'return_count': Formater.formatCountShow(instance.return_count),
        'return_cost': Formater.formatAmountShow(instance.return_cost),
        'notes': instance.notes,
        'no': instance.no,
        'company': company.name,
    }
    data['main_data'] = main_data
    detail_rows = GoodsDeliverDetail.objects.filter(main=instance)
    for detail_row in detail_rows:
        item_data = {
            'id': detail_row.id,
            'product_id': detail_row.product_base.id,
            'name': detail_row.product_base.product_base.name,
            'model': detail_row.product_base.product_base.model,
            'total_cost': Formater.formatAmountShow(detail_row.total_cost),
            'total_amount': Formater.formatAmountShow(detail_row.total_amount),
            'count': Formater.formatCountShow(detail_row.count),
            'price': Formater.formatPriceShow(detail_row.price),
            'warehouse_stock_count': Formater.formatCountShow(detail_row.warehouse_stock.count),
            'unit': detail_row.product_base.product_base.unit or '',
            'cur_count': Formater.formatCountShow(detail_row.count - detail_row.return_count),
            'notes': detail_row.notes or ''
        }
        data['items_data'].append(item_data)

    return JSONResponse(data)

@csrf_exempt
@permission_required('order.add_goods_deliver_return')
def deliver_return_save(request):
    id = request.GET.get('id')
    main_data = json.loads(request.POST.get('main'))
    items_data = json.loads(request.POST.get('item'))
    try:
        with transaction.atomic():
            serializer = GoodsDeliverReturnSerializer.factory(request.user, main_data)
            serializer = serializer.validSave()
            for item in items_data:
                item['main'] = serializer.id
                detail_serializer = GoodsDeliverReturnDetailSerializer.factory(request.user, data=item)
                detail_serializer = detail_serializer.validSave()
                detail_serializer.deliver_detail.updateReturn()
            serializer.update_total()
            deliver = GoodsDeliver.getById(id)
            deliver.update_return()
    except CustomError, e:
        return JSONError(e.get_error_msg())
    except Exception, e:
        traceback.print_exc()
        return JSONError(u'保存失败！')
    return JSONResponse()



@csrf_exempt
@permission_required('order.view_goods_deliver_return_query')
def deliver_return_query_list(request):# 成品退库查询
    rows = get_return_filter_data(request)
    total_row = rows.aggregate(return_count=Sum('goods_return_deliver_detail_ref_warehouse_record__return_count'),
                               return_cost=Sum('goods_return_deliver_detail_ref_warehouse_record__return_cost'))
    more = {
        'return_count': Formater.formatCountShow(total_row['return_count']),
        'return_cost': Formater.formatAmountShow(total_row['return_cost']),
    }
    rows, total = utils.get_page_data(request, rows)
    data = get_deliver_return_query_data(rows)
    return DataGridJSONResponse(data, total, more)

@csrf_exempt
@permission_required('order.export_goods_deliver_return_query')
def deliver_return_query_export(request):
    try:
        rows = get_return_filter_data(request)
        data = get_deliver_return_query_data(rows)
        export_data = ExportChange.dict_to_obj2(data)
        perm = 'goods.view_goods_cost'
        is_show_cost = isHasPermissions(request.user, perm)
        export_data = GoodsDeliverReturnQueryResource(is_show_cost).export(export_data)
        filename = utils.attachment_save(export_data)
        BizLog.objects.addnew(request.user, BizLog.EXPORT, u"导出成品退库查询")
    except CustomError, e:
        return JSONError(e.get_error_msg())
    except Exception, e:
        traceback.print_exc()
        return JSONError(u'导出成品退库查询失败！')
    return JSONResponse({'filename': filename})


@token_required
def deliver_return_query_detail(request):
    rows = get_return_filter_data(request)
    data = get_deliver_return_query_data(rows)
    return JSONResponse(data)

def get_return_filter_data(request):
    create_time = request.GET.get('create_time')
    warehouse = request.GET.get('warehouse')
    return_no = request.GET.get('return_no')
    no = request.GET.get('no')
    name = request.GET.get('name')
    model = request.GET.get('model')
    reason = request.GET.get('reason')
    notes = request.GET.get('notes')
    create_user = request.GET.get('create_user')
    rows = WarehouseRecord.objects.filter(product__type=2, type=7).order_by('-id')
    if create_time:
        create_time_begin = create_time.split(' - ')[0]
        create_time_end = create_time.split(' - ')[1] + ' 23:59:59'
        rows = rows.filter(goods_return_deliver_detail_ref_warehouse_record__main__create_time__gt=create_time_begin,
                           goods_return_deliver_detail_ref_warehouse_record__main__create_time__lt=create_time_end)
    if no:
        rows = rows.filter(goods_return_deliver_detail_ref_warehouse_record__deliver_detail__main__no__icontains=no)
    if create_user:
        rows = rows.filter(goods_return_deliver_detail_ref_warehouse_record__main__create_user__name__icontains=create_user)
    if warehouse:
        rows = rows.filter(goods_return_deliver_detail_ref_warehouse_record__deliver_detail__main__warehouse__name__icontains=warehouse)
    if return_no:
        rows = rows.filter(
            goods_return_deliver_detail_ref_warehouse_record__main__no__icontains=return_no)
    if notes:
        rows = rows.filter(
            goods_return_deliver_detail_ref_warehouse_record__notes__icontains=notes)
    if reason:
        rows = rows.filter(goods_return_deliver_detail_ref_warehouse_record__main__reason__icontains=reason)
    if name:
        rows = rows.filter(goods_return_deliver_detail_ref_warehouse_record__product_base__name__icontains=name)
    if model:
        rows = rows.filter(goods_return_deliver_detail_ref_warehouse_record__product_base__name__icontains=model)
    warehouses_ids = Warehouse.getManagerWarehouses(request.user)
    department_ids = request.user.getSubDepartmentIds()
    user_ids = request.user.getSubEmployeeIds()
    rows = rows.filter(warehouse_id__in=warehouses_ids)
    rows = rows.filter(
        Q(goods_return_deliver_detail_ref_warehouse_record__main__department_id__in=department_ids)
        | Q(goods_return_deliver_detail_ref_warehouse_record__main__create_user_id__in=user_ids)
        | Q(goods_return_deliver_detail_ref_warehouse_record__main__create_user=request.user))
    return rows

def get_deliver_return_query_data(rows):
    rows = rows.values(
        'id',
        'type',
        'goods_return_deliver_detail_ref_warehouse_record__product_base__product_base__name',
        'goods_return_deliver_detail_ref_warehouse_record__product_base__product_base__model',
        'goods_return_deliver_detail_ref_warehouse_record__product_base__product_base__type',
        'goods_return_deliver_detail_ref_warehouse_record__product_base__product_base__warehouse_place',
        'warehouse__name',
        'cur_count',
        'goods_return_deliver_detail_ref_warehouse_record__return_count',
        'goods_return_deliver_detail_ref_warehouse_record__return_cost',
        'goods_return_deliver_detail_ref_warehouse_record__notes',
        'goods_return_deliver_detail_ref_warehouse_record__main__create_user__name',
        'goods_return_deliver_detail_ref_warehouse_record__main__create_time',
        'goods_return_deliver_detail_ref_warehouse_record__main__reason',
        'goods_return_deliver_detail_ref_warehouse_record__main__no',
        'goods_return_deliver_detail_ref_warehouse_record__deliver_detail__main__no',
    )
    data = []
    for row in rows:
        warehouse_record_type = WarehouseRecord.TYPE_CHOICES[row['type']][1]
        product_type_text = ProductBase.TYPE_CHOICES[row['goods_return_deliver_detail_ref_warehouse_record__product_base__product_base__type']][1]
        item = {
            'id': row['id'],
            'type': warehouse_record_type,
            'product_type': product_type_text,

            'name': row['goods_return_deliver_detail_ref_warehouse_record__product_base__product_base__name'],
            'model': row['goods_return_deliver_detail_ref_warehouse_record__product_base__product_base__model'],
            'warehouse_place': row['goods_return_deliver_detail_ref_warehouse_record__product_base__product_base__warehouse_place'],

            'warehouse': row['warehouse__name'],
            'cur_count': Formater.formatCountShow(row['cur_count']),

            'create_user': row['goods_return_deliver_detail_ref_warehouse_record__main__create_user__name'],
            'notes': row['goods_return_deliver_detail_ref_warehouse_record__notes'],
            'create_time': Formater.formatStrTime(row['goods_return_deliver_detail_ref_warehouse_record__main__create_time']),
            'return_count': Formater.formatCountShow(row['goods_return_deliver_detail_ref_warehouse_record__return_count']),
            'return_cost': Formater.formatAmountShow(row['goods_return_deliver_detail_ref_warehouse_record__return_cost']),
            'reason': row['goods_return_deliver_detail_ref_warehouse_record__main__reason'],
            'return_no': row['goods_return_deliver_detail_ref_warehouse_record__main__no'],

            'no': row['goods_return_deliver_detail_ref_warehouse_record__deliver_detail__main__no']
        }
        data.append(item)
    return data
