# coding=utf-8

import tablib
from django.conf import settings
from django.core.management import BaseCommand
from rpc.tool.queryset_tool import big_qs_iter
from gm_types.gaia import TRANS_ACTION, TRANS_STATUS

from api.models import UserExtra
from cashback.models import Registration, CashbackManager, TransactionLog
from statistic.models import Device

DFAULT_DBS = [getattr(settings, 'HERA_READ_DB', ''), 'default']


def get_db_key(dbs):
    for db in dbs:
        if db in settings.DATABASES:
            return db
    return None

using_dbs = DFAULT_DBS
using = get_db_key(using_dbs)

def is_valid(count, max_same, empty):
    if empty >= 2:
        return False
    if count in range(5, 10):
        return (max_same * 1.0 / count) <= 0.6
    elif count in range(11, 30):
        return (max_same * 1.0 / count) <= 0.4
    elif count >= 30:
        return (max_same * 1.0 / count) <= 0.25
    return True


class Command(BaseCommand):
    """
    python manage.py dump_20180619_export_inviter_data
    导出医院信息
    """

    def handle(self, *args, **options):
        inviter_ids = Registration.objects.values_list('inviter', flat=True).distinct()
        valid_inviter_ids = []
        for inviter in inviter_ids:
            os = Registration.objects.filter(inviter=inviter)
            empty = 0
            model_same = {}
            for o in os:
                device = Device.objects.filter(user=o.invitee)
                if device:
                    model = device.latest('last_activity').model
                    if model:
                        if model_same.get(model, None):
                            model_same[model] += 1
                        else:
                            model_same[model] = 1
                    else:
                        empty += 1
                else:
                    empty += 1
            if is_valid(os.count(), max(model_same.values() if model_same else [0]), empty):
                valid_inviter_ids.append(inviter)
        objs = Registration.objects.using(using).filter(inviter__in=valid_inviter_ids)
        dt_result = tablib.Dataset()
        dt_result.headers = [
            u'邀请人ID', u'邀请人', u'注册人', u'手机号', u'设备类型', u'首次登录时间', u'设备是否登录过其他用户'
        ]
        for obj in big_qs_iter(objs):
            if CashbackManager.isSuspect(obj.inviter):
                continue
            user = obj.inviter
            if not TransactionLog.objects.filter(
                    user=obj.inviter,
                    type=TRANS_ACTION.WITHDRAW,
                    state=TRANS_STATUS.WAIT).exists():
                continue
            try:
                devices = Device.objects.filter(user=obj.invitee)
                x = (
                    obj.inviter.id,
                    obj.inviter.last_name,
                    obj.invitee.last_name,
                    UserExtra.objects.get(user_id=obj.invitee_id).phone,
                    devices.latest('last_activity').model if devices else '',
                    obj.login_time.strftime('%Y-%m-%d %H:%M:%S') if obj.login_time else '',
                    u'是' if devices and CashbackManager.isLoginOthers(devices.latest('last_activity').device_id) else u'否'
                )
                dt_result.append(x)
                print obj.id
            except Exception as e:
                print e.message
                continue
        open(u'非嫌疑邀请人详情.csv', 'wb').write(dt_result.csv)
        open(u'非嫌疑邀请人详情.xlsx', 'wb').write(dt_result.xlsx)
        print 'DONE!!!'
