# coding: utf-8
from rpc.decorators import bind, bind_context
from api.models import BDTransfer, BDTransferVisitRecord
import datetime
from themis.models import Team
from api.tool.user_tool import get_user_from_context
from django.db.models import Q
from gm_types.gaia import TEAM_TYPE
from django.contrib.auth.models import User
from gm_types.gaia import BD_SERVICE_TYPE
from utils.time_tools import get_today_range
from django.db import transaction
from themis.views.team import recursive_users


uri_pre = 'hera/bdtransfer/'


@bind_context(uri_pre + 'create_visit_record')
def create_visit_record(ctx, bdtransfer_id_list=[],method=None,type=None,plan_at=None):
    user_id = get_user_from_context(ctx).id
    bdtransfer_id_list = BDTransfer.objects.filter(id__in=bdtransfer_id_list, is_assign=True).values_list('id','current_follow_up_consultant')
    plan_at = datetime.datetime.strptime(plan_at, '%Y-%m-%d %H:%M:%S')
    visit_object = []
    for bdtransfer_id,current_follow_up_consultant in bdtransfer_id_list:
        obj = BDTransferVisitRecord(bdtransfer_id=bdtransfer_id,method=method,type=type,creator_id=user_id, assignor_id=current_follow_up_consultant, plan_at=plan_at)
        visit_object.append(obj)

    if visit_object:
        visit_id_list = BDTransferVisitRecord.objects.bulk_create(visit_object)
    return [item.id for item in visit_id_list]


@bind_context(uri_pre + 'visit_statistics')
def visit_record_statistics(ctx, srch_field=None, srch_value=None, status=None, plan_at__lte=None, plan_at__gte=None):
    cur_user = ctx.session.user
    business_partener_list = recursive_users.func(user_id=cur_user.id)

    q = Q(assignor__in=business_partener_list)
    if status:
        q &= Q(status=status)
    if srch_field == 'assignor' and srch_value:
        q &= Q(assignor__username__contains=srch_value)
    elif srch_field == 'id' and srch_value:
        q &= Q(id=srch_value)

    if plan_at__lte:
        q &= Q(plan_at__lte=datetime.datetime.strptime(plan_at__lte, '%Y-%m-%d') + datetime.timedelta(days=1))
    if plan_at__gte:
        q &= Q(plan_at__gte=datetime.datetime.strptime(plan_at__gte, '%Y-%m-%d'))

    task_list = BDTransferVisitRecord.objects.filter(q)
    data = []
    tmp_dict = {}
    if task_list:
        for single_task in task_list:
            task_assignor = single_task.assignor
            username = task_assignor.username
            user_id = task_assignor.id
            # 姓名
            tmp_dict.setdefault(user_id, {}).setdefault('assignor', username)

            # 名下所有线索
            if tmp_dict.get(user_id).get('count_bdtransfer', None) is None:
                tmp_dict.setdefault(user_id, {}).setdefault('conut_bdtransfer',
                                                            task_assignor.follow_bdtransfers.count())

            # 筛选出来的所有线索任务
            conut_visit = tmp_dict.setdefault(user_id, {}).setdefault('conut_visit', 0)
            conut_visit += 1
            tmp_dict.setdefault(user_id, {})['conut_visit'] = conut_visit

            # 筛选出来的线索任务对应的线索数量
            if tmp_dict.get(user_id).get('count_have_visit', None) is None:
                tmp_dict.get(user_id)['count_have_visit'] = len(set(task_list.filter(assignor=user_id).values_list('bdtransfer', flat=True)))

            if single_task.status == BD_SERVICE_TYPE.FINISHED:
                do_visit = tmp_dict.setdefault(user_id, {}).setdefault('do_visit', 0)
                do_visit += 1
                tmp_dict.setdefault(user_id, {})['do_visit'] = do_visit
            elif single_task.status == BD_SERVICE_TYPE.TOBEDONE:
                undo_visit = tmp_dict.setdefault(user_id, {}).setdefault('undo_visit', 0)
                undo_visit += 1
                tmp_dict.setdefault(user_id, {})['undo_visit'] = undo_visit
            elif single_task.status == BD_SERVICE_TYPE.OVERDUE:
                over_visit = tmp_dict.setdefault(user_id, {}).setdefault('over_visit', 0)
                over_visit += 1
                tmp_dict.setdefault(user_id, {})['over_visit'] = over_visit
            else:
                invalid_visit = tmp_dict.setdefault(user_id, {}).setdefault('invalid_visit', 0)
                invalid_visit += 1
                tmp_dict.setdefault(user_id, {})['invalid_visit'] = invalid_visit

            if tmp_dict.get(user_id).get('undo_bdtransfer', None) is None:
                tmp_dict.get(user_id)['undo_bdtransfer'] = len(
                    set(task_list.filter(assignor=user_id,status=BD_SERVICE_TYPE.TOBEDONE).values_list('bdtransfer', flat=True)))

            if tmp_dict.get(user_id).get('do_bdtransfer', None) is None:
                tmp_dict.get(user_id)['do_bdtransfer'] = len(
                    set(task_list.filter(assignor=user_id,status=BD_SERVICE_TYPE.FINISHED).values_list('bdtransfer', flat=True)))

            if tmp_dict.get(user_id).get('over_bdtransfer', None) is None:
                tmp_dict.get(user_id)['over_bdtransfer'] = len(
                    set(task_list.filter(assignor=user_id,status=BD_SERVICE_TYPE.OVERDUE).values_list('bdtransfer', flat=True)))

            if tmp_dict.get(user_id).get('invalid_bdtransfer', None) is None:
                tmp_dict.get(user_id)['invalid_bdtransfer'] = len(
                    set(task_list.filter(assignor=user_id,status=BD_SERVICE_TYPE.INVALID).values_list('bdtransfer', flat=True)))

    for user_id in tmp_dict:
        item = tmp_dict[user_id]
        item['id'] = user_id
        item['undo_visit_bdtransfer'] = '{}/{}'.format(str(item.setdefault('undo_visit', 0)),
                                                       str(item['undo_bdtransfer']))
        item['do_visit_bdtransfer'] = '{}/{}'.format(str(item.setdefault('do_visit', 0)), str(item['do_bdtransfer']))
        item['over_visit_bdtransfer'] = '{}/{}'.format(str(item.setdefault('over_visit', 0)),
                                                       str(item['over_bdtransfer']))
        item['invalid_visit_bdtransfer'] = '{}/{}'.format(str(item.setdefault('invalid_visit', 0)),
                                                          str(item['invalid_bdtransfer']))
        data.append(item)

    return data


@bind_context(uri_pre + 'get_bdtransfer_over_visit_records')
def get_visit_records(ctx, bdtransfer_list=[]):
    bdtransfer_2_visit_dict = {}
    if bdtransfer_list:
        bdtransfer_visit_list = BDTransferVisitRecord.objects.filter(bdtransfer_id__in=bdtransfer_list,status__in=[BD_SERVICE_TYPE.TOBEDONE, BD_SERVICE_TYPE.OVERDUE]).values_list('bdtransfer_id', 'id')
        print bdtransfer_visit_list
        print type(bdtransfer_visit_list)
        if bdtransfer_visit_list:
            for bdtransfer_id, visit_id in bdtransfer_visit_list:
                bdtransfer_2_visit_dict.setdefault(bdtransfer_id, []).append(visit_id)
    return bdtransfer_2_visit_dict


@bind_context(uri_pre + 'list/visit_statistics')
def list_visit_statistics(ctx):
    user = get_user_from_context(ctx)
    today_begin, today_end = get_today_range()

    # todo 添加权限
    print(user.id)

    q = Q(plan_at__gt=today_begin) & Q(plan_at__lt=today_end) & Q(assignor_id=user.id)
    total = BDTransferVisitRecord.objects.filter(q).count()

    q_f = q & Q(status=BD_SERVICE_TYPE.FINISHED)
    finised = BDTransferVisitRecord.objects.filter(q_f).count()

    q_t = q & Q(status=BD_SERVICE_TYPE.TOBEDONE)
    todo = BDTransferVisitRecord.objects.filter(q_t).count()

    q_o = q & Q(status=BD_SERVICE_TYPE.OVERDUE)
    overdue = BDTransferVisitRecord.objects.filter(q_o).count()

    return {"total": total,
            "finished": finised,
            "todo": todo,
            "overdue": overdue,
            }


@bind_context(uri_pre + 'mark_visit_record')
@transaction.atomic
def mark_visit_record(ctx, visit_id=None, visit_at=None, method=None, type=None, state=None, remark='', next_plan_at=None ):
    if not all([visit_at, method, type, state]):
        raise ValueError('visit_at, method, type, state null')
    cur_user = ctx.session.user
    visit = BDTransferVisitRecord.objects.get(id=visit_id)
    if visit.visit_at:
        raise ValueError('have been mark')
    update = {
        'visit_at':datetime.datetime.strptime(visit_at, '%Y-%m-%d %H:%M:%S'),
        'method': method,
        'type':type,
        'state':state,
        'remark':remark,
        'status':BD_SERVICE_TYPE.FINISHED
    }
    for key, value in update.items():
        setattr(visit, key, value)
    visit.save(update_fields=update.keys())

    if next_plan_at:
        plan_at = datetime.datetime.strptime(next_plan_at, '%Y-%m-%d %H:%M:%S')
        BDTransferVisitRecord.objects.create(bdtransfer=visit.bdtransfer,method=method,type=type,creator=cur_user, assignor=visit.bdtransfer.current_follow_up_consultant, plan_at=plan_at)

    return visit.id
