# coding=utf-8
import xlrd

from django.core.management import BaseCommand

from lasker.models import AwardResult
from gm_types.gaia import SERVICE_FLAG


def open_excel(file_name="famous_doctor_list.xlsx"):
    try:
        data = xlrd.open_workbook(file_name)
        return data
    except Exception, e:
        print str(e)


class Command(BaseCommand):
    """ Import famous doctor award list from excel to database """

    def handle(self, *args, **options):
        data = open_excel("famous_doctor_list.xlsx")
        doctor_table, hospital_table = data.sheets()[0], data.sheets()[1]
        d_rows, d_cols = doctor_table.nrows, doctor_table.ncols
        h_rows, h_cols = hospital_table.nrows, hospital_table.ncols

        AwardResult.objects.filter(is_deleted=False).update(is_deleted=True)

        # insert DOCTOR data into database
        for row_num in range(1, d_rows):
            row = doctor_table.row_values(row_num)
            if row:
                laureate_id = row[5]
                laureate_name = row[0]
                # 奖项优先级为2>3>1, 去除列表中的空字符串, 最多展示1项
                award_name = ','.join([item for item in (row[3], row[4], row[2]) if item][:1])
                AwardResult.objects.update_or_create(laureate_id=laureate_id, defaults={
                    'laureate_name': laureate_name,
                    'laureate_type': SERVICE_FLAG.DOCTOR,
                    'award_name': award_name,
                    'is_deleted': False
                })
                print u'*** handled doctor info: {} {} {}'.format(laureate_id, laureate_name, award_name)

        # insert HOSPITAL data into database
        for row_num in range(1, h_rows):
            row = hospital_table.row_values(row_num)
            if row:
                laureate_id = row[2]
                laureate_name = row[0]
                award_name = row[1]
                AwardResult.objects.update_or_create(laureate_id=laureate_id, defaults={
                    'laureate_name': laureate_name,
                    'laureate_type': SERVICE_FLAG.HOSPITAL,
                    'award_name': award_name,
                    'is_deleted': False
                })
                print u'*** handled hospital info: {} {} {}'.format(laureate_id, laureate_name, award_name)
