# -*- coding: UTF-8 -*-
from datetime import datetime
from django.core.management import BaseCommand
from openpyxl import load_workbook
from .utils import get_mail
from api.models import Doctor
from api.models import User
from api.models import DocBusinessRecord
from django.db import transaction
import copy


change_time = str(datetime.now().date())


class Command(BaseCommand):
    """
        python manage.py update_20170612_business_parter
        解锁sku美购
    """

    def add_arguments(self, parser):
        parser.add_argument('filename', nargs='+', type=str)

    def handle(self, *args, **options):
        filename = options['filename'][0]
        wb = load_workbook(filename=filename)
        sheetnames = wb.get_sheet_names()
        ws = wb.get_sheet_by_name(sheetnames[0])
        error_msg = ''
        result_log = ''
        record_user = User.objects.filter(username='yilingxiao')[0]
        for r in ws.rows[1:]:
            hospital_id = r[1].value
            business_partner_username = r[7].value
            try:
                business_partners = User.objects.filter(username=business_partner_username)
                if business_partners.count() != 1:
                    continue
                doctors = Doctor.objects.filter(hospital_id=hospital_id)
                if not doctors.exists():
                    continue
                business_partner = business_partners[0]
                doctor_business = {}
                doctor_ids = []
                for d in doctors:
                    doctor_business[d.id] = d.business_partener_id
                    doctor_ids.append(d.id)
                with transaction.atomic():
                    Doctor.objects.filter(id__in=doctor_ids).update(business_partener=business_partner)
                    DocBusinessRecord.objects.bulk_create([
                        DocBusinessRecord(
                            doctor_id=d.id,
                            business_id=doctor_business[d.id],
                            to_business_id=d.business_partener_id,
                            user_id=record_user.id,
                        ) for d in Doctor.objects.filter(id__in=doctor_ids)
                    ])
                print hospital_id
                result_log += '{}:{}:{}\n'.format(hospital_id, doctor_ids, business_partner.id)
            except Exception as e:
                message = '{},{}:{}'.format(hospital_id, business_partner_username, e.message)
                print message
                error_msg += message + '\n'
        body = u'{}_business_parter'.format(change_time)
        get_mail(u'{}_rusult.txt'.format(body), u'{}_result'.format(body), u'chenfeifei@gmei.com', result_log).send()
        get_mail(u'{}_error.txt'.format(body), u'{}_error'.format(body), u'chenfeifei@gmei.com', error_msg).send()
        print u'DONE!'
