#coding=utf-8

import traceback
import json

from django.utils import timezone
from libs import utils
from libs.http import JSONError, JSONResponse,DataGridJSONResponse
from apps.account.decorators import token_required
from django.db import transaction, IntegrityError
from apps.exceptions import CustomError

from apps.foundation.models import BizLog

from django.db.models import Q, Sum
from django.conf import settings
from .models import *
from .serializers import *
from .filters import *
from apps.customer.models import Customer
from apps.account.models import Branch


@token_required
def branch_list(request):
    f = BranchFilter(request.GET, queryset=Branch.objects.filter())
    rows, total = utils.get_page_data(request, f.qs)
    serializer = BranchSerializer(rows, many=True)
    return DataGridJSONResponse(serializer.data, total)


@token_required
def branch_save(request):
    id = request.GET.get('id')
    data = json.loads(request.body)

    try:
        with transaction.atomic():
            serializer = BranchSerializer.factory(request.user, data, id)
            serializer.validSave()
        return JSONResponse(serializer.data)
    except CustomError as e:
        return JSONError(e.get_error_msg())
    except Exception as e:
        traceback.print_exc()
        return JSONError(u'保存失败！')


@token_required
def self_branch(request):
    order = Branch.objects.filter(id=request.user.branch_id).first()
    data = {}
    if order:
        data = {'name': order.name, 'tel': order.tel, 'address': order.address}
    return JSONResponse({'data': data})


@token_required
def member_list(request):
    f = CustomerFilter(request.GET, queryset=Customer.objects.filter(branch=request.user.branch))
    rows, total = utils.get_page_data(request, f.qs)
    serializer = CustomerSerializer(rows, many=True)
    return DataGridJSONResponse(serializer.data, total)


@token_required
def member_coupon_list(request):
    f = MemberCouponFilter(request.GET, queryset=MemberCoupon.objects.filter(member__branch=request.user.branch))
    rows, total = utils.get_page_data(request, f.qs)
    serializer = MemberCouponSerializer(rows, many=True)
    return DataGridJSONResponse(serializer.data, total)


@token_required
def coupon_write_off(request):
    id = request.GET.get('id')
    try:
        with transaction.atomic():
            instance = MemberCoupon.getById(id)
            if instance.member.branch and instance.member.branch_id != request.user.branch_id:
                raise CustomError(u'禁止跨店操作!')
            instance.writeOff()
            BizLog.objects.addnew(request.user, BizLog.CHECK, u"核销会员优惠券,id=%d" % instance.id)
    except CustomError as e:
        return JSONError(e.get_error_msg())
    except Exception as e:
        traceback.print_exc()
        return JSONError(u'核销失败！')
    return JSONResponse()


@token_required
def coupon_cancel_write_off(request):
    id = request.GET.get('id')
    try:
        with transaction.atomic():
            instance = MemberCoupon.getById(id)
            if instance.member.branch and instance.member.branch_id != request.user.branch_id:
                raise CustomError(u'禁止跨店操作！')
            instance.cancelWriteOff()
            BizLog.objects.addnew(request.user, BizLog.CHECK, u"撤销核销会员优惠券,id=%d" % instance.id)
    except CustomError as e:
        return JSONError(e.get_error_msg())
    except Exception as e:
        traceback.print_exc()
        return JSONError(u'撤销核销失败！')
    return JSONResponse()


@token_required
def order_list(request):
    if request.user.is_superuser:
        rows = Order.objects.filter()
    else:
        rows = Order.objects.filter(branch=request.user.branch)
    f = OrderFilter(request.GET, queryset=rows)
    rows_sum = f.qs.aggregate(
        sum_rebate=Sum('rebate'),
        sum_amount=Sum('amount')
    )
    more = {
        'sum_amount':rows_sum['sum_amount'],
        'sum_rebate':rows_sum['sum_rebate'],
    }
    rows, total = utils.get_page_data(request, f.qs)
    serializer = OrderSerializer(rows, many=True)
    return DataGridJSONResponse(serializer.data, total, more)


@token_required
def coupon_list(request):
    f = BranchFilter(request.GET, queryset=Coupon.objects.filter(branch=request.user.branch))
    rows, total = utils.get_page_data(request, f.qs)
    serializer = CouponSerializer(rows, many=True)
    return DataGridJSONResponse(serializer.data, total)


@token_required
def coupon_save(request):
    id = request.GET.get('id')
    data = json.loads(request.body)

    try:
        with transaction.atomic():
            data['branch'] = request.user.branch_id
            serializer = CouponSerializer.factory(request.user, data, id)
            serializer.validSave()
        return JSONResponse(serializer.data)
    except CustomError as e:
        return JSONError(e.get_error_msg())
    except Exception as e:
        traceback.print_exc()
        return JSONError(u'保存失败！')


@token_required
def coupon_dict(request):
    rows = Coupon.objects.filter(
        Q(branch=request.user.branch, enabled=True) &
        Q(
            Q(end_date__isnull=False) & Q(end_date__gt=timezone.now().date()) |
            Q(end_date__isnull=True)
        )
    )

    serializer = CouponComboboxSerializer(rows, many=True)
    return DataGridJSONResponse(serializer.data, rows.count())


@token_required
def activity_list(request):
    if request.user.is_superuser:
        rows = Activity.objects.filter(delete=False)
    else:
        rows = Activity.objects.filter(branch_id=request.user.branch_id, delete=False)
    f = ActivityFilter(request.GET, queryset=rows)
    rows, total = utils.get_page_data(request, f.qs)
    serializer = ActivitySerializer(rows, many=True)
    return DataGridJSONResponse(serializer.data, total)


@token_required
def activity_save(request):
    id = request.GET.get('id')
    data = json.loads(request.body)

    try:
        with transaction.atomic():
            data['branch'] = request.user.branch_id
            serializer = ActivitySerializer.factory(request.user, data, id)
            serializer.validSave()
        return JSONResponse(serializer.data)
    except CustomError as e:
        return JSONError(e.get_error_msg())
    except Exception as e:
        traceback.print_exc()
        return JSONError(u'保存失败！')

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

    try:
        with transaction.atomic():
            order = Activity.objects.filter(id=id).first()
            if order.check_status == settings.PASS:
                raise CustomError(u'该活动已审核')

            order.delete = True
            order.save()
            BizLog.objects.addnew(request.user, BizLog.INSERT, u"删除活动[%s],id=%s" % (order.title, order.id))
        return JSONResponse({})
    except CustomError as e:
        return JSONError(e.get_error_msg())
    except Exception as e:
        traceback.print_exc()
        return JSONError(u'保存失败！')


@token_required
def activity_check(request):
    id = request.GET.get('id')
    status = request.GET.get('status')

    try:
        with transaction.atomic():
            order = Activity.objects.filter(id=id).first()
            if order.delete:
                raise CustomError(u'该活动已删除')

            if order.check_status == int(status):
                raise CustomError(u'该活动已当前状态不允许执行此操作')

            if int(status) == settings.PASS:
                order.check_status = settings.PASS
                order.save()
                BizLog.objects.addnew(request.user, BizLog.INSERT, u"审核活动[%s],id=%s" % (order.title, order.id))
            else:
                order.check_status = settings.DEFAULT
                order.save()
                BizLog.objects.addnew(request.user, BizLog.INSERT, u"活动撤销审核[%s],id=%s" % (order.title, order.id))

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


@token_required
def activity_signs_save(request):
    id = request.GET.get('id')
    signs = request.POST.get('signs')

    try:
        with transaction.atomic():
            signs = json.loads(signs)
            order = Activity.objects.filter(id=id).first()
            if order.delete:
                raise CustomError(u'该活动已删除')

            save_sign = ''
            for sign in signs:
                save_sign += sign + ','
            order.required_signs = save_sign
            order.save()

            BizLog.objects.addnew(request.user, BizLog.INSERT, u"活动设置必填项[%s],id=%s" % (order.title, order.id),signs )
        return JSONResponse({})
    except CustomError as e:
        return JSONError(e.get_error_msg())
    except Exception as e:
        traceback.print_exc()
        return JSONError(u'保存失败！')

@token_required
def activity_coupon_save(request):
    id = request.GET.get('id')
    coupon_ids = request.POST.get('coupons')

    try:
        with transaction.atomic():
            coupons = json.loads(coupon_ids)
            order = Activity.objects.filter(id=id).first()
            if order.delete:
                raise CustomError(u'该活动已删除')

            ActivityCoupon.objects.filter(activity=order).delete()
            for coupon in coupons:
                ActivityCoupon.objects.create(
                    activity=order,
                    coupon_id=coupon
                )

            BizLog.objects.addnew(request.user, BizLog.INSERT, u"活动添加优惠券[%s],id=%s" % (order.title, order.id),coupon_ids )
        return JSONResponse({})
    except CustomError as e:
        return JSONError(e.get_error_msg())
    except Exception as e:
        traceback.print_exc()
        return JSONError(u'保存失败！')