#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.contrib.auth.decorators import login_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
from apps.WechatApplet.models import WechatApplet
from .base import OrderUpdate
from util.format import Formater
from util.file_operation import PathAndRename, resizePicture, UploadFile, DeleteFile
from django.http import JsonResponse as DJR


@token_required
@login_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
@login_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
@login_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
@login_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
@login_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
@login_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
@login_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
@login_required()
def order_list(request):
    OrderUpdate.update_status()
    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':Formater.formatPriceShow(rows_sum['sum_amount']),
        'sum_rebate':Formater.formatPriceShow(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
@login_required()
def order_split_account(request):
    id = request.GET.get('id')

    try:
        order = Order.objects.filter(id=id).first()
        app = WechatApplet.objects.filter().first()
        if not app:
            raise CustomError(u'未设置小程序信息！')
        if not order:
            raise CustomError(u'未找到相应的订单')
        if not order.pay or order.pay.status != Pay.CONFIRM:
            raise CustomError(u'该订单尚未支付，无法分账！')

        with transaction.atomic():
            if not order.splitaccount:
                if (order.rebate <= 0) or (not order.recommend_member) or (order.pay.profit_sharing == "N"):
                    raise CustomError(u'该订单无需分账！')
                sp, spd, spr = SplitAccount._addnew(order.branch, order.id, order.rebate, order.recommend_member)
                order.splitaccount = sp
                order.save()
            sp = order.splitaccount
            spd = SplitAccountDetail.objects.filter(main=sp).first()
            if not spd:
                raise CustomError(u'未找到相应的分账明细！')
            if spd.status == SplitAccountDetail.SUCCESS:
                raise CustomError(u'该订单已分账，禁止重复申请！')

            order.splitaccount.handSplitAccont(spd, order.pay, app)
            BizLog.objects.addnew(request.user, BizLog.INSERT, u"订单申请分账,id=%d" % order.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
@login_required()
def order_update_split(request):
    id = request.GET.get('id')

    try:
        order = Order.objects.filter(id=id).first()
        app = WechatApplet.objects.filter().first()
        if not app:
            raise CustomError(u'未设置小程序信息！')
        if not order:
            raise CustomError(u'未找到相应的订单！')
        if not order.splitaccount:
            raise CustomError(u'未找到该订单分账信息！')
        sp = order.splitaccount
        spd = SplitAccountDetail.objects.filter(main=sp).first()
        if not spd:
            raise CustomError(u'未找到相应的分账明细！')

        with transaction.atomic():
            order.splitaccount.updateAccountSplit(spd, order.pay, app)
            BizLog.objects.addnew(request.user, BizLog.INSERT, u"刷新订单分账结果,id=%d" % order.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
@login_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
@login_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
@login_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
@login_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
@login_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
@login_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
@login_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
@login_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
@login_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'保存失败！')


@token_required
@login_required()
def activity_code(request):
    id = request.GET.get('id')
    try:
        with transaction.atomic():
            order = Activity.getById(id)
            if order.delete:
                raise CustomError(u'该活动已删除')

            if not order.wxapp_img:
                app = WechatApplet.objects.filter().first()
                wxCode = app.generateActivityWXappCode(order.id)
                order.wxapp_img = settings.MEDIA_URL + wxCode
                order.save()

        return JSONResponse({'data': order.wxapp_img})
    except CustomError as e:
        return JSONError(e.get_error_msg())
    except Exception as e:
        traceback.print_exc()
        return JSONError(u'获取失败！')


# def ueditor_image(request):
#     try:
#         upload_path = PathAndRename("upload/")
#
#         data = {}
#         if request.FILES.getlist('upfile'):
#             document = request.FILES.getlist('upfile')[0]
#             type = document.name.split('.')[-1]
#             name = timezone.now().strftime('%Y%m%d%H%M%S%f')
#             filename = "%s-%s.%s" % (
#                 upload_path.path, name, type)
#             filename = filename.lower()
#             full_filename = "%s/%s" % (settings.MEDIA_ROOT, filename)
#             with open(full_filename, 'wb+') as destination:
#                 for chunk in document.chunks():
#                     destination.write(chunk)
#
#             resizePicture(full_filename, 500)
#             data = {
#                 "state": "SUCCESS",
#                 "original": "%s.%s" % (name, type),
#                 "title": "%s.%s" % (name, type),
#                 "url": 'https://jpm.zzly.vip' + settings.MEDIA_URL + filename
#             }
#         return DJR(data, safe=False)
#     except CustomError as e:
#         return JSONError(e.get_error_msg())
#     except Exception as e:
#         traceback.print_exc()
#         return JSONError(u'图片上传失败！')


@token_required
@login_required()
def upload_image(request):
    id = request.GET.get('id')
    poster = request.FILES.get('image', None)
    try:
        if not poster:
            raise CustomError(u'未找到上传文件！')
        activity = Activity.getById(id)
        if activity.delete:
            raise CustomError(u'该活动已删除')
        with transaction.atomic():
            filename = UploadFile(poster, "upload/", width=500)
            if activity.pic:
                DeleteFile(activity.pic)
            activity.pic = filename
            activity.save()
        return JSONResponse({})
    except CustomError as e:
        return JSONError(e.get_error_msg())
    except Exception as e:
        traceback.print_exc()
        return JSONError(u'上传失败！')
