# coding=utf-8
import tablib
from django.contrib.auth.models import User
from django.core.management import BaseCommand
from django.db import transaction
from openpyxl import load_workbook

from api.models import Hospital, DocBusinessRecord


class Command(BaseCommand):
    """
    python manage.py change_hospital_hospital
    """

    def handle(self, *args, **options):
        wb = load_workbook(filename='/data/hospital/hospital.xlsx')
        sheetnames = wb.get_sheet_names()
        if sheetnames == 0:
            return
        ws = wb.get_sheet_by_name(sheetnames[0])
        print ws.title
        dt_result = tablib.Dataset()
        dt_result.headers = [u'医生ID', u'医生名字', u'机构ID', u'机构名称', u'原商务', u'新商务']

        for rx in range(2, ws.get_highest_row() + 1):
            try:
                hospital_name = ws.cell(row=rx, column=1).value.strip()
                username = ws.cell(row=rx, column=2).value.strip()
                user = User.objects.get(username=username)
                print hospital_name, username
                hospital = Hospital.objects.get(name=hospital_name)
                for doctor in hospital.doctor_hospital.all():
                    try:
                        with transaction.atomic():
                            row = []
                            docrecord = DocBusinessRecord()
                            old_business = doctor.business_partener
                            docrecord.doctor_id = doctor.id
                            docrecord.business_id = doctor.business_partener.id
                            docrecord.to_business_id = user.id
                            doctor.business_partener = user
                            doctor.save()
                            docrecord.save()
                            row.append(doctor.id)
                            row.append(doctor.name)
                            row.append(hospital.id)
                            row.append(hospital.name)
                            row.append(old_business._get_full_field_content_('username'))
                            row.append(user._get_full_field_content_('username'))
                            dt_result.append(row)
                    except Exception as e:
                        print e.message
                        continue

            except Exception as e:
                print e.message
                continue
        open(u'/data/hospital/result.xlsx', 'wb').write(dt_result.xlsx)
        print u'Done!'
