#! /usr/bin/env python
# -*- coding: utf-8 -*-
import json
from django.db.models import Q
from api.models import MarketTag, MarketPersonas, MarketActivityUserProfile, User
from rpc.decorators import bind_context
from api.tool.user_tool import get_user_from_context
from api.tasks.export_excel_task import export_market_excel


uri_pre = 'hera/market'


@bind_context(uri_pre + '/create')
def market_create(ctx, data, id_=None):
    user = get_user_from_context(ctx)
    if not user:
        return {
            'code': -1,
            'msg': '操作员不存在',
        }

    if not id_:
        tag_name = data.get('tag_name')
        obj = MarketTag.objects.filter(tag_name=tag_name, is_online=True).first()
        if obj:
            return {
                'code': -1,
                'msg': '营销标签已存在',
            }
        nums = search_market(data=data.get('search_condition'), get_count=True)
        if not nums:
            return {
                'code': -1,
                'msg': '筛选条件下不存在用户，营销标签创建失败',
            }
        obj = MarketTag()
        obj.tag_name = data.get('tag_name')
        obj.reason = data.get('reason')
        obj.tag_type = data.get('tag_type')
        obj.description = data.get('description')
        obj.search_condition = data.get('search_condition') if data.get('search_condition') else '{}'
        obj.operater = user.id
        obj.nums = nums

        obj.save()
    else:
        obj = MarketTag.objects.filter(pk=id_).first()
        if not obj:
            return {
                'code': -1,
                'msg': '营销标签不存在',
            }
        MarketTag.objects.filter(pk=id_).update(**data)
    return {'id': obj.id}


@bind_context(uri_pre + '/get')
def get_info(ctx, id_):
    obj = MarketTag.objects.filter(pk=id_).first()
    if not obj:
        return {
            'code': -1,
            'msg': '营销标签不存在',
        }
    return {
        'id': obj.id,
        'tag_name': obj.tag_name,
        'tag_type': obj.tag_type,
        'reason': obj.reason,
        'description': obj.description,
        'nums': obj.nums,
        'search_condition': json.loads(obj.search_condition),
    }


@bind_context(uri_pre + '/search_user_count')
def search_user_count(ctx, data):
    return {'count': search_market(data, get_count=True)}

def gets_user_ids(marked_ids):
    if not marked_ids:
        return []
    objs = MarketTag.objects.filter(id__in=marked_ids)
    query_list = [obj.search_condition for obj in objs]
    user_ids = []
    for data in query_list:
        ids = search_market(data)
        if not ids:
            continue
        user_ids.extend(ids)

    return list(set(user_ids))

def search_market(data, get_count=False):
    data = json.loads(data)
    personas_query = Q()

    conditions = data.get('conditions')
    for condition in conditions:
        query = Q()
        tag_id = condition.get('tag_id')
        if tag_id:
            query = Q(tag_id=tag_id)
        
        score_down = condition.get('score_down')
        score_up = condition.get('score_up')
        if score_down and score_up:
            query = query & Q(score__gte=float(score_down)) & Q(score__lte=float(score_up))

        ratio_down = condition.get('ratio_down')
        ratio_up = condition.get('ratio_up')
        if ratio_down and ratio_up:
            query = query & Q(weight__gte=ratio_down) & Q(weight__lte=ratio_up)

        pay_condition = condition.get('pay_condition')
        if pay_condition:
            query = query & Q(pay_type=int(pay_condition))

        personas_query = personas_query | query

    device_ids = MarketPersonas.objects.filter(personas_query).values_list('device_id', flat=True) 

    active_query = Q()
    sex = data.get('gender')
    if sex:
        active_query = active_query & Q(sex=int(sex))
    age_down = data.get('age_down')
    age_up = data.get('age_up')
    
    if age_down and age_up:
        active_query = active_query & Q(age__gte=int(age_down)) & Q(age__lte=int(age_up))

    city_id = data.get('city')
    if city_id:
        active_query = active_query & Q(city_id=city_id)
    register_from = data.get('register_from')
    register_to = data.get('register_to')
    if register_from and register_to:
        active_query = active_query & Q(register_time__gte=register_from) & Q(register_time__lte=register_to)
    active_from = data.get('active_from')
    active_to = data.get('active_to')
    if active_from and active_to:
        active_query = active_query & Q(active_time__gte=active_from) & Q(active_time__lte=active_to)
    
    active_query = active_query & Q(device_id__in=device_ids)

    if get_count:
        return MarketActivityUserProfile.objects.filter(active_query).count()
    return list(MarketActivityUserProfile.objects.filter(active_query).values_list('user_id', flat=True))


@bind_context(uri_pre + '/export_excel')
def market_export_excel(ctx, id_):
    """
    导出营销标签用户信息
    :param ctx:
    :return:
    """
    user = get_user_from_context(ctx)
    tag = MarketTag.objects.filter(id=id_).first()
    if not tag:
        return {
                'code': -1,
                'msg': '营销标签不存在',
            }
    user_ids = gets_user_ids([id_])
    export_market_excel.delay(user_ids=user_ids, tag_name=tag.tag_name, user=user)
    