# -*- coding: UTF-8 -*-

import codecs
import time
from django.core.management import BaseCommand
from django.db.models.functions import Length
from django.conf import settings
from services.custom_phone_service import Union400
from api.models import Doctor


open = codecs.open
suozhang_ext = '6666'


def batch_update_and_check(union400, phones):
    ret = union400.batch_add_phone_ext(phones)
    print len(phones)
    print ret
    old_data = {d['dn']: d['tel'] for d in phones}
    data = union400.batch_query_phone_ext(old_data.keys())
    print '****** old_data: {}  return_data: {}'.format(old_data, data)
    for ext, ph in data.iteritems():
        if str(ph) != str(old_data[ext]):
            print 'ext: %s; old: %s; new: %s;' % (ext, old_data[ext], ph)


class Command(BaseCommand):
    def handle(self, *args, **options):
        succ_log = open('/tmp/union400_success.log', 'w', 'utf8')
        error_log = open('/tmp/union400_error.log', 'w', 'utf8')
        union400 = Union400(**settings.UNION400_CONF)

        # 先处理所长大人分机号
        suozhang = Doctor.objects.get(phone_ext=suozhang_ext)
        ret = union400.add_phone_ext(suozhang.phone_ext, suozhang.phone)
        print '******** add suozhang_ext result: ', ret

        # 批量处理其他分机号长度为6的医生
        print '******** begin add other doctors_ext'
        i = 0
        phones = []
        doctors = Doctor.objects.annotate(ext_len=Length('phone_ext')).filter(ext_len=6)
        for doctor in doctors:
            # print '*** doctor.phone: {}    doctor.phone_ext: {}'.format(doctor.phone, doctor.phone_ext)
            if not doctor.phone or not doctor.phone_ext.isdigit():
                continue

            phones.append({'dn': doctor.phone_ext, 'tel': doctor.phone})
            if not i % 500:
                batch_update_and_check(union400, phones)
                phones = []
                time.sleep(10)
            i += 1

        batch_update_and_check(union400, phones)
