# coding=utf-8
import json
import traceback
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt

from apps.customer.models import Customer
from apps.order.models import GoodsDeliverDetail,SaleOrderDetail
from apps.purchase.models import PurchaseInvoiceImage

from libs.http import JSONResponse
from apps.account.decorators import permission_required, token_required
from libs import utils
from libs.http import DataGridJSONResponse, JSONResponse, JSONError
from apps.goods.models import Goods
from apps.account.models import User
from apps.warehouse.models import WarehouseAdmin
from biz import *
from apps.material.models import DeliverDetail
from apps.plan.models import SalePlanDetail
from apps.office.models import Notice,NoticeBrowseRecord

@csrf_exempt
@token_required
def home_data(request):
    department_ids = request.user.getSubDepartmentIds()
    user_ids = request.user.getSubEmployeeIds()

    data, unchecks_total_count = get_unchecks(request.user,department_ids,user_ids)

    children = request.user.getSubDepartmentIds()
    children.append(request.user.department.id)
    rows = Notice.objects.filter(dendline__gte=timezone.now(), department__in=children)
    browsed_ids = NoticeBrowseRecord.objects.filter(browse_user_id=request.user).values_list('notice_id', flat=True)
    not_notices = rows.filter(~Q(id__in=browsed_ids))

    result = {
        'data':data,
        'unchecks_total_count':unchecks_total_count,
        'notice_unread':not_notices.count(),
    }
    return JSONResponse(result)

@csrf_exempt
@token_required
def material_data(request):
    department_ids = request.user.getSubDepartmentIds()
    user_ids = request.user.getSubEmployeeIds()
    warehouses_ids = Warehouse.getManagerWarehouses(request.user)

    data = get_material_data(request.user, user_ids, department_ids, warehouses_ids)
    return JSONResponse(data)

@csrf_exempt
@token_required
def consumable_data(request):
    department_ids = request.user.getSubDepartmentIds()
    user_ids = request.user.getSubEmployeeIds()
    warehouses_ids = Warehouse.getManagerWarehouses(request.user)

    data = get_consumable_data(request.user, user_ids, department_ids, warehouses_ids)
    return JSONResponse(data)

@csrf_exempt
@token_required
def goods_data(request):
    department_ids = request.user.getSubDepartmentIds()
    user_ids = request.user.getSubEmployeeIds()
    warehouses_ids = Warehouse.getManagerWarehouses(request.user)

    data = get_goods_data(request.user, user_ids, department_ids, warehouses_ids)
    return JSONResponse(data)

@csrf_exempt
@token_required
def material_deliver_options(request):
    type = request.GET.get('type')
    users = User.objects.filter(status=User.INSERVICE).values('id', 'name')
    data = {
        'users': [],
        'goods': [],
        'warehouses': [],
    }
    for row in users:
        data['users'].append(
            {'value':row['id'], 'label':row['name']}
        )

    goods = Goods.objects.filter(product_base__enabled=True)
    for row in goods:
        data['goods'].append({
            'value': row.id,
            'label': row.product_base.name
        })
    try:
        type = Warehouse.getValidType(type)
        warehouses = WarehouseAdmin.objects.filter(user=request.user, warehouse__type=type,warehouse__enabled=True).order_by('-warehouse__is_default','-warehouse_id').values('warehouse_id', 'warehouse__name')
        for row in warehouses:
            data['warehouses'].append({
                'value': row['warehouse_id'],
                'label': row['warehouse__name']
            })
    except Exception, e:
        traceback.print_exc()
    return JSONResponse(data)

@csrf_exempt
@token_required
def goods_deliver_options(request):
    users = User.objects.filter(status=User.INSERVICE).values('id', 'name')
    data = {
        'agent_users': [],
        'customers': [],
        'warehouses': [],
        'sale_orders': [],
    }
    for row in users:
        data['agent_users'].append(
            {'value':row['id'], 'label':row['name']}
        )

    customers = Customer.objects.filter()
    for row in customers:
        data['customers'].append({
            'value': row.id,
            'label': row.name
        })
    saleorders = SaleOrder.objects.filter()
    for row in saleorders:
        data['sale_orders'].append({
            'value': row.id,
            'label': row.no
        })
    try:
        warehouses = WarehouseAdmin.objects.filter(user=request.user, warehouse__type=2,warehouse__enabled=True).order_by('-warehouse__is_default','-warehouse_id').values('warehouse_id', 'warehouse__name')
        for row in warehouses:
            data['warehouses'].append({
                'value': row['warehouse_id'],
                'label': row['warehouse__name']
            })
    except Exception, e:
        traceback.print_exc()
    return JSONResponse(data)

@token_required
def material_delete_details(request):
    id = request.GET.get('detail_id')
    try:
        with transaction.atomic():
            detail = DeliverDetail.objects.get(id=id)
            main = Deliver.objects.get(id=detail.main_id)
            detail.delete()
            main.update_total()
    except Exception, e:
        traceback.print_exc()
        return JSONError(u'删除失败！')
    return JSONResponse()

@token_required
def goods_delete_details(request):
    id = request.GET.get('detail_id')
    try:
        with transaction.atomic():
            detail = GoodsDeliverDetail.objects.get(id=id)
            main = GoodsDeliver.objects.get(id=detail.main_id)
            detail.delete()
            main.update_total()
    except Exception, e:
        traceback.print_exc()
        return JSONError(u'删除失败！')
    return JSONResponse()


@token_required
def table_touch(request):
    id = request.GET.get('id')
    data = get_plan_data(id)
    return JSONResponse(data)

@token_required
def payment_detail(request):
    id = request.GET.get('id')
    data = get_payment_data(id)
    return JSONResponse(data)

@token_required
def invoice_detail(request):
    id = request.GET.get('id')
    purchase_order = PurchaseOrderDetail.objects.filter(id=id).first()
    main_data = {
        'id': purchase_order.id,
        'no': purchase_order.main.no,
        'name': purchase_order.product.name,
        'model': purchase_order.product.model,
        'supplier_text': purchase_order.main.supplier and purchase_order.main.supplier.name or '',
        'amount': Formater.formatAmountShow(purchase_order.amount),
        'invoice_no': purchase_order.invoice_no,
        'invoice_amount': Formater.formatAmountShow(purchase_order.invoice_amount),
        'invoice_date': Formater.formatStrTime(purchase_order.invoice_date),
        'check_user': purchase_order.check_user and purchase_order.check_user.name or '',
        'check_status': purchase_order.check_status,
        'check_time': Formater.formatStrTime(purchase_order.check_time),
        'create_user': purchase_order.create_user and purchase_order.create_user.name or '',
        'create_time': Formater.formatStrTime(purchase_order.create_time),
    }
    data = {
        'main_data':main_data,
        'image_data':[]
    }
    images = PurchaseInvoiceImage.objects.filter(order_detail_id=id)
    for image in images:
        item = {
            'id': image.id,
            'url': image.invoice_image.url
        }
        data['image_data'].append(item)
    return JSONResponse(data)

@csrf_exempt
@token_required
def customer_select(request):
    rows = Customer.objects.filter().values('id','name','mobile')
    data = {
        'customers': [],
    }
    for row in rows:
        data['customers'].append(
            {'value':row['id'], 'label':u'{0}-{1}'.format(row['name'],row['mobile'])}
        )

    return JSONResponse(data)

@token_required
def plan_delete_details(request):
    id = request.GET.get('detail_id')
    try:
        with transaction.atomic():
            detail = SalePlanDetail.objects.get(id=id)
            main = SalePlan.objects.get(id=detail.main_id)
            detail.delete()
            main.update_total()
    except Exception, e:
        traceback.print_exc()
        return JSONError(u'删除失败！')
    return JSONResponse()

@token_required
def order_delete_details(request):
    id = request.GET.get('detail_id')
    try:
        with transaction.atomic():
            SaleOrderDetail.objects.filter(id=id).delete()
            detail = SaleOrderDetail.objects.get(id=id)
            main = SaleOrder.objects.get(id=detail.main_id)
            detail.delete()
            main.updateAmount()
    except Exception, e:
        traceback.print_exc()
        return JSONError(u'删除失败！')
    return JSONResponse()

@token_required
def stock_options(request):
    type = request.GET.get('type')
    type = Warehouse.getValidType(type)
    data = {
        'warehouse_place':[]
    }
    rows = Warehouse.objects.filter(type=type)

    for row in rows:
        item = {
            'id': row.id,
            'name': row.name
        }
        data['warehouse_place'].append(item)
    if type == 2:
        data['empty'] = [{'id': 1,'name': '是'},
                         {'id': 0,'name': '否'}]
    else:
        data['empty'] = [{'id': 1, 'name': '有库存'},
                         {'id': 0, 'name': '零库存'},
                         {'id': 2, 'name': '超储'},
                         {'id': 3, 'name': '短缺'},
                         {'id': 4, 'name': '负库存'}]
    return JSONResponse(data)
