#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "chenwei"
# Date: 2019/8/20


from utils.execel import ExcelReader
from django.core.management import BaseCommand
from api.models import Doctor
from lasker.models import AwardResult
from gm_types.gaia import SERVICE_FLAG, DOCTOR_TYPE
from django.db.models import F

filename = "12.xlsx"


def update_or_create_hospital(row):
    hospital_id, hospital_name, award_name, _ = row
    doctor = Doctor.objects.filter(
        hospital_id=hospital_id, doctor_type=DOCTOR_TYPE.OFFICER).first()

    if not doctor:
        print("not exist....", row)
        return

    award = AwardResult.objects.filter(
        laureate_type=SERVICE_FLAG.HOSPITAL,
        is_deleted=False, laureate_id=doctor.id
    ).first()

    if award:
        award.award_name = F("award_name") + ',' + award_name
        award.save()
    else:
        AwardResult.objects.create(
            laureate_id=hospital_id,
            laureate_name=hospital_name,
            laureate_type=SERVICE_FLAG.HOSPITAL,
            award_name=award_name)


def update_or_create_doctor(row):
    doctor_id, doctor_name, award_name, _ = row
    doctor = Doctor.objects.filter(id=doctor_id).first()

    if not doctor:
        print("not exist....", row)
        return

    award = AwardResult.objects.filter(
        laureate_type=SERVICE_FLAG.DOCTOR,
        is_deleted=False, laureate_id=doctor_id
    ).first()

    if award:
        award.award_name = F("award_name") + ',' + award_name
        award.save()
    else:
        AwardResult.objects.create(
            laureate_id=doctor_id,
            laureate_name=doctor_name,
            laureate_type=SERVICE_FLAG.DOCTOR,
            award_name=award_name)


class Command(BaseCommand):

    def handle(self, *args, **options):
        excel = ExcelReader(filename)
        for row in range(1, excel.row_number):
            data = excel.read_row(row)
            assert len(data) == 4
            # 类型
            laureate_type = data[3]
            if laureate_type == SERVICE_FLAG.DOCTOR:
                update_or_create_doctor(data)
            else:
                update_or_create_hospital(data)


