#!/usr/bin/env python
# coding=utf-8
from openpyxl import load_workbook

from django.core.management import BaseCommand

from gm_types.doctor import DOCTOR_AREA_TYPE, DOCTOR_LICENCE_TYPE, DOCTOR_REGISTER_STATUS
from api.models import Doctor, Hospital, DoctorLicence
from doctor.models import DoctorRegister


class Command(BaseCommand):

    def handle(self, *args, **options):
        # 境外医生id
        doctor_ids = []
        # 从xlsx 读取数据
        wb = load_workbook(filename=u'/tmp/doctor_foreign_table.xlsx')
        sheetnames = wb.get_sheet_names()
        ws = wb.get_sheet_by_name(sheetnames[0])
        for rx in range(2, ws.get_highest_row() + 1):
            row = ws.cell(row=rx, column=1).value
            if row:
                doctor_ids.append(row)

        # 调整同步医生、医院的一些信息
        for d in Doctor.objects.all():
            print (u'sycn doctor id is {}'.format(d.id))
            if d.id in doctor_ids:
                # 若是境外医生
                d.area_type = DOCTOR_AREA_TYPE.ABROAD
            else:
                d.area_type = DOCTOR_AREA_TYPE.CISBORDER

            if d.business_licence:
                DoctorLicence.objects.get_or_create(
                    doctor_id=d.id, type=DOCTOR_LICENCE_TYPE.BUSINESS, image_url=d.business_licence
                )
            if d.practice_licence:
                DoctorLicence.objects.get_or_create(
                    doctor_id=d.id, type=DOCTOR_LICENCE_TYPE.PRACTICE, image_url=d.practice_licence
                )

            d.save()

        hospitals = Hospital.objects.all()
        for h in hospitals:
            print (u'sycn hospital id is {}'.format(h.id))
            if h.business_licence:
                DoctorLicence.objects.get_or_create(
                    hospital_id=h.id, type=DOCTOR_LICENCE_TYPE.BUSINESS, image_url=h.business_licence
                )
            if h.practice_licence:
                DoctorLicence.objects.get_or_create(
                    hospital_id=h.id, type=DOCTOR_LICENCE_TYPE.PRACTICE, image_url=h.practice_licence
                )

        # 初始化Register没处理的老数据
        for dr in DoctorRegister.objects.all():
            print (u'sycn DoctorRegister id is {}'.format(dr.id))
            if Doctor.objects.filter(user__person__id=dr.person_id).exists():  # 若医生已有
                dr.status = DOCTOR_REGISTER_STATUS.FINISHED
            else:
                dr.status = DOCTOR_REGISTER_STATUS.OLD_DATA
            dr.save()
