# coding=utf-8
from __future__ import unicode_literals, print_function, absolute_import

from django.core.management import BaseCommand
from django.conf import settings
from gm_types.msg import CONVERSATION_TYPE

from api.models import ConversationUserStatus, Conversation, Person


class Command(BaseCommand):
    """初始化conversation 表中的conversation_type值， 如果对话是客服或者更美咨询师， 应该将conversation_type 初始化为对应数值
        python manage.py conversation_init_conversation_type
    """
    def handle(self, *args, **options):
        kefu_user_id = Person.objects.get(id=settings.KEFU_PERSION_ID).user_id
        if settings.CALL_CENTER_CONSULTANT_PERSON_ID:
            counselor_user_id = Person.objects.get(id=settings.CALL_CENTER_CONSULTANT_PERSON_ID).user_id
        else:
            counselor_user_id = None
        batch_size = 1000
        # 处理客服系统的数据
        if kefu_user_id:
            print('正在处理客服相关数据')
            kefu_conversation_ids = list(ConversationUserStatus.objects.filter(user_id=kefu_user_id).\
                                         values_list('conversation_id', flat=True))
            current_kefu_batch_num = 0
            for _ in kefu_conversation_ids[::batch_size]:
                print('正在处理 {}  -  {} 的数据'.format(current_kefu_batch_num, current_kefu_batch_num + batch_size))
                Conversation.objects.filter(
                    id__in=kefu_conversation_ids[current_kefu_batch_num: current_kefu_batch_num + batch_size]
                ).update(conversation_type=CONVERSATION_TYPE.CUSTOMER_SRV)
                ConversationUserStatus.objects.filter(
                    conversation_id__in=kefu_conversation_ids[current_kefu_batch_num: current_kefu_batch_num + batch_size]
                ).update(conversation_type=CONVERSATION_TYPE.CUSTOMER_SRV)
                current_kefu_batch_num += batch_size
        if counselor_user_id:
            print('正在处理更美咨询师相关数据')
            counselor_conversation_ids = list(ConversationUserStatus.objects.filter(user_id=counselor_user_id).\
                values_list('conversation_id', flat=True))

            Conversation.objects.filter(id__in=counselor_conversation_ids).\
                update(conversation_type=CONVERSATION_TYPE.CONSULTANT)
            ConversationUserStatus.objects.filter(
                conversation_id__in=counselor_conversation_ids
            ).update(conversation_type=CONVERSATION_TYPE.CUSTOMER_SRV)
        print('完成')
