# coding=utf-8
from django.core.management import BaseCommand
from doctor.models.capture import DoctorRegister
from api.models.user import User
from api.models.person import Person
from hera.views.doctorregister import create_user
from rpc.tool.dict_mixin import to_dict
import tablib


class Command(BaseCommand):

    def handle(self, *args, **options):
        file_log = open('doctorregister.txt', 'r')
        lines = file_log.readlines(100000)
        dt1 = tablib.Dataset()
        dt1.headers = [u'医生注册ID', u'message']
        for line in lines:
            try:
                can_connect = True
                doctorregister_id = int(line.strip())
                doctorregister = DoctorRegister.objects.get(id=doctorregister_id)
                doctorregister_info = to_dict(doctorregister)
                try:
                    user = User.objects.get(username=doctorregister_info['phone'])
                    try:
                        if user.doctor:
                            can_connect = False
                            message = u'{}相同手机号的医生已经存在'.format(doctorregister_id)
                            print message
                    except:
                        user.is_staff = True
                        user.last_name = doctorregister_info['name']
                        user.password = doctorregister.password
                        user.groups = '2'
                        user.save()
                except User.DoesNotExist:
                    user = create_user(doctorregister_info)
                    user.groups = '2'
                    user.save()
                if can_connect:
                    person = Person.get_or_create(user)
                    person.password = doctorregister.password
                    person.save()
                    doctorregister.person = person
                    doctorregister.save()
                    message = u'{}关联成功'.format(doctorregister_id)
                    print message
                row = []
                row.append(doctorregister_id)
                row.append(message)
                dt1.append(row)
            except Exception as e:
                print e.message
                continue
        open(u'message.xlsx', 'wb').write(dt1.xlsx)
        print (u"导出成功!!")
        file_log.close()
