# coding=utf-8
# create by oldman at 2018/8/18
import datetime

import tablib
from django.core.management import BaseCommand

from api.models import Message, ConversationUserStatus
from hippo.models import Doctor
from hera.management.commands.utils import get_mail

class Command(BaseCommand):
    """
    python manage.py update_2018_08_18_export_wuxiao_messages
    导出无效的私信
    """

    def handle(self, *args, **options):
        user_ids = [
            30302263,
            30301834,
            30301819,
            30303379,
            30303280,
            30303269,
            30303227,
            30303185,
            30303173,
            30302951,
            30302904,
            30302775,
            30302613,
            30307195,
            30305246,
            30304513,
            30304480,
            30304357,
            30304208,
            30304109,
            30303691,
            30303451,
            30303391,
            30308253,
            30303379,
            30312620
        ]
        gt_time = datetime.datetime(year=2018, month=8, day=6, hour=0, minute=0, second=0)
        lt_time = datetime.datetime(year=2018, month=8, day=10, hour=23, minute=59, second=59)
        messages = Message.objects.filter(send_time__gt=gt_time, send_time__lt=lt_time).filter(user_id__in=user_ids)
        doctor_dits = {}
        for message in messages:
            doctor_user_id= ConversationUserStatus.objects.filter(
                conversation=message.conversation).exclude(user_id=message.user_id).first().user_id
            doctors = Doctor.objects.filter(user_id=doctor_user_id)
            if doctors.exists():
                doctor = doctors.first()
                if doctor_dits.has_key(doctor.id):
                    doctor_dits[doctor.id] += 1
                else:
                    doctor_dits[doctor.id] = 1
        print doctor_dits

        dt = tablib.Dataset()
        dt.headers = [u'医生ID', u'医生名字', u'被骚扰用户数']
        for key, value in doctor_dits.items():
            try:
                doctor = Doctor.objects.get(id=key)
                row = (
                    doctor.id,
                    doctor.name,
                    value
                )
                dt.append(row)

            except Exception as e:
                print e.message
                continue
        body = u'私信沟通的医生信息'
        get_mail(u'私信沟通的医生信息.xlsx', u'私信沟通的医生信息.xlsx', u'lipeng@igengmei.com', dt.xlsx).send()

