# coding=utf-8

import imp
import os
import sys
import traceback
import datetime

import django
from django.utils import timezone
from django.db import transaction
from django.db.models import Sum, Q

def autoSplitAccount():
    # 查询状态是未处理和处理中的分账明细进行分账处理(处理中就查询结果  未处理的就进行分账)
    details = SplitAccountDetail.objects.filter(Q(status=SplitAccountDetail.DEFAULT) | Q(status=SplitAccountDetail.PENDING))
    app = WechatApplet.objects.filter().first()
    if not app:
        return
    for instance in details:
        main = instance.main
        if (not main) or (main.status == SplitAccount.FINISHED):
            continue
        order = Order.objects.filter(splitaccount=main).first()
        if (not order) or (order.status != Order.FINISH) or (not order.recommend_member) or (order.rebate <= 0):
            continue
        pay = order.pay
        if (not pay) or (pay.status != Pay.CONFIRM) or (pay.profit_sharing == 'N'):
            continue
        try:
            main.handSplitAccont(instance, pay, app)
        except:
            traceback.print_exc()
            continue

def setup_django_env(path):
    sys.path.insert(0, path)

    f, filename, desc = imp.find_module('settings', [path])
    imp.load_module('settings', f, filename, desc)
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
    sys.path.append(os.path.abspath(os.path.join(path, os.path.pardir)))

if __name__ == '__main__':
    dirname, filename = os.path.split(os.path.abspath(sys.argv[0]))
    setup_django_env(dirname+'/../carwin_activity')
    django.setup()

    from apps.activity.models import SplitAccount, SplitAccountDetail, Order, Pay
    from apps.WechatApplet.models import WechatApplet

    try:
        print('start=======',timezone.now())
        # with transaction.atomic():
        autoSplitAccount()
        print('end========', timezone.now())
    except Exception as e:
        traceback.print_exc()
