import datetime

from django.db.models import Q
from django.utils import timezone

import zeep

from .models import *

import ntuhgov.portal_selenium as portal

def UpdateNHICase(case):

    # print(case)

    if 'PackageTime' not in case:
        case['PackageTime'] = case['ApplyDate']

    if 'ApplyQty' in case:
        case['ResultDesc'] = case['ApplyQty']

    if case['PackageTime'] is not None:
        case['PackageTime']=case['PackageTime'].replace('/','-')

    if 'ExamineDate' in case and case['ExamineDate'] is not None:
        case['ExamineDate']=case['ExamineDate'].replace('/','-')
    if 'ApplyDate' in case and case['ApplyDate'] is not None:
        case['ApplyDate']=case['ApplyDate'].replace('/','-')

    if 'ApplyDoctor' in case and case['ApplyDoctor'] is not None:
        case['ApplyDoctor']=case['ApplyDoctor'].replace('\ue09b', '峯') #'許峯銘'

    if case['PackageTime'] is None:
        return

    # id = case['ChartNo']+'_'+case['PackageTime'][:4]
    id = case['ChartNo']+'_'+case['PackageTime'][:7]

    order = NHIOrder.objects.filter(id=id).first()

    if order == None:
        order = NHIOrder(id=id)

    # print(order)
    # exit()
    # order, created = NHIOrder.objects.get_or_create(id=id)

    for k, v in case.items():
        # order[k] = v
        # print(k,v)
        if v is not None:
            setattr(order, k, v)

    if order.Priority is None:
        if order.Quantity == '同意備查':
            order.Priority = 1

    order.save()

FirstPriority = 900
LastPriority = 100
def SortNHI(CheckTreated=True):

    for v in NHIOrder.objects.values('ApplyDoctor').distinct():

        if v['ApplyDoctor'] is None:
            continue

        print(v)
            
        q = NHIOrder.objects.filter(ApplyDoctor=v['ApplyDoctor'],Priority__gt=0).order_by('-Priority', 'PackageTime')
        total = len(q)
        print(v['ApplyDoctor'], total)

        if total < 1:
            continue


        priority = FirstPriority
        d = (FirstPriority-LastPriority)/total
        for order in q:

            # check if treated
            # patient = Patient.objects.get(medical_records=order.ChartNo)

            if CheckTreated:
                patient = Patient.objects.filter(medical_records=order.ChartNo).first()
                if patient is not None:
                    print(patient, patient.medical_records)
                    for t in patient.treatment_set.all():
                        print(t.date_started, order.ExamineDate)
                        if (t.date_started is not None) and (order.ExamineDate is not None) and t.date_started > order.ExamineDate:
                            order.Priority = -1                   

            # if v['ApplyDoctor'] is not None and order.Priority > 0:
            if order.Priority > 0:
                order.Priority = priority
                priority -= d
            order.save()

def AddPatient(d, force=True):
    # r = portal.QueryModifyPatBase({'IdNo': idcode,
    #                                                     'ChartNo': chartno,
    #                                                     })

    p = None
    r = portal.QueryModifyPatBase(d)

    if r:
        r['name'] = r['ChtName']
        r['medical_records'] = r['ChartNo']
        r['gender'] = r['Sex']
        r['birthday'] = r['Birth']
        r['address'] = r['AddressControl1']
        r['phone'] = r['ContTel']
        r['id_cards'] = r['IdNo']
        
        result = [r]
    else:
        result = []  

    if force and len(result)>0:
        r=result[0]
        
        if r['gender'] == 'M':
            r['gender'] = 1
        else:
            r['gender'] = 2
#        hw = intra.HeightWeight(r['id_cards'])
#         hw = ntuhgov.portal.HeightWeight(r['id_cards'])
        hw = portal.BriefHistoryLink(r['id_cards'])
        p = Patient(name = r['name'],
                    medical_records = r['medical_records'],
                    gender = r['gender'],
                    birthday = r['birthday'],
                    address = r['address'],
                    phone = r['phone'],
                    id_cards = r['id_cards'],
                    # height = hw['Height'],
                    weight = hw['Weight'],
           )

        try:
            p.height = int(hw['Height'])
        except:
            pass
        p.save()

    return p

def QueryMS():
    import mssql_ntuh.models as mssql

    tzinfo=timezone.get_default_timezone()

    # time_threshold = datetime.datetime.now() - datetime.timedelta(weeks=4) 
    # DateTimeField Treatment.timestamp received a naive datetime while time zone support is active.
    time_threshold = timezone.now() - datetime.timedelta(weeks=4)

    # qs = mssql.PatientAppointmentSchedule.objects.using('mssql-ntuh').all()
    qs = mssql.PatientAppointmentSchedule.objects.using('mssql-ntuh').filter(appointment_date__gt=time_threshold)

    for s in qs:
        appointment_time = s.appointment_date.replace(tzinfo=tzinfo, hour=int(s.appointment_hour), minute=int(s.appointment_minutes))

        if s.treatment_start_datetime:
            start_time = s.treatment_start_datetime.replace(tzinfo=tzinfo)
        elif s.checkin_datetime :
            start_time = s.checkin_datetime.replace(tzinfo=tzinfo)
        else:
            start_time = s.appointment_date.replace(tzinfo=tzinfo, hour=int(s.appointment_hour), minute=int(s.appointment_minutes))

        if s.treatment_complete_datetime:
            end_time = s.treatment_complete_datetime.replace(tzinfo=tzinfo)
        else:
            end_time = start_time + datetime.timedelta(hours=1)

        if s.treatment_room == 'MR':
            end_time = max(end_time, start_time + datetime.timedelta(hours=1))

        # start_time = timezone.make_aware(datetime.datetime.now(),timezone.get_default_timezone())
        # start_time = timezone.get_default_timezone().localize(start_time)
        # start_time = start_time.replace(tzinfo=tzinfo)

        print(s.mapping_patient, s.treatment_room,  s.appointment_date, s.checkin_datetime, s.queue_datetime, s.treatment_start_datetime,  s.treatment_complete_datetime, s.fallrisktime, s.willtime)
        mapping_patient = mssql.Patient.objects.using('mssql-ntuh').filter(id=s.mapping_patient).first()
        # print(p.name)
        # try:
        #     print(s.mapping_patient.name)
        # except:
        #     #no patient found
        #     continue
        print(s.id, s.main_diagnose, s.treatment_room,  start_time, end_time)
        # chartno = s.mapping_patient.record_no
        patient = Patient.objects.filter(medical_records=s.record_no).first()
        # print(patient)
        if patient is None:
            print('AddPatient', s.record_no, mapping_patient.name)
            patient = AddPatient({'ChartNo': s.record_no})

        if patient is None:
            # false patient
            continue

        # print(patient.name)
        treatment = patient.treatment_set.filter(Q(creation__gt=time_threshold) | Q(timestamp__gt=time_threshold)).order_by('-id').first()

        if treatment is None:
            print('Add Treatment', mapping_patient.record_no, mapping_patient.name)
            treatment = Treatment(patient=patient)
            treatment.save()

        if treatment.surgeon is None and s.main_doctor:
            treatment.surgeon = Surgeon.objects.filter(name=s.main_doctor).first()
        if treatment.oncologist is None and s.rt_doctor:
            treatment.oncologist = Oncologist.objects.filter(name=s.rt_doctor).first()
        if treatment.other_diagnosis is None and s.main_diagnose:
            treatment.other_diagnosis = s.main_diagnose


        if s.treatment_room == 'CK':
            if treatment.date_started is None or treatment.date_started > start_time.date():
                treatment.date_started = start_time
            if treatment.date_completed is None or treatment.date_completed < end_time.date():
                treatment.date_completed = end_time
            if treatment.bed is None and s.hospitalized_status:
                treatment.bed = s.hospitalized_status

        if treatment.icd10cm is None: # 找之前的健保申請
            order = NHIOrder.objects.filter(ChartNo=s.record_no).order_by('-id').first()
            if order is not None and order.ExamineDate is not None:                
                treatment.icd10cm = ICD10CMfinal.objects.filter(ICD10CM=order.Diagnosis).first()
                count = patient.treatment_set.filter(Q(creation__gt=order.ExamineDate)).count()
                if count <= 1:
                    treatment.accounting = 10

        timestamp = max(treatment.creation, treatment.timestamp)
        print(patient.name, treatment, timestamp)

        print()
        treatment.save()


        vevent = treatment.vevent_set.filter(DESCRIPTION=s.id).first()
        if vevent is None:
            vevent = VEVENT(treatment=treatment,DESCRIPTION=s.id)

        vevent.DTSTART  = start_time
        vevent.DURATION = str(end_time-start_time)
        # print(vevent.DURATION, type(vevent.DURATION))

        print(s.treatment_room)
        if s.treatment_room == 'CK':
            vevent.mode = 310
            vevent.SUMMARY = patient.name+'治療'
        elif s.treatment_room == 'MR':
            vevent.mode = 220
            vevent.SUMMARY = patient.name+'MRI'
        elif s.treatment_room == 'HE':
            vevent.mode = 100
            vevent.SUMMARY = patient.name+'衛教'
        elif s.treatment_room.startswith('CT'):
            vevent.mode = 210
            vevent.SUMMARY = patient.name+s.treatment_room

        vevent.save()

    print(len(qs))

def UpdateNHICase2(case):

    print(case)
    case = zeep.helpers.serialize_object(case)

    if 'PackageTime' not in case:
        case['PackageTime'] = case['ApplyDate']

    if 'ApplyQty' in case:
        case['ResultDesc'] = case['ApplyQty']

    if 'ApplyDoctor' in case and case['ApplyDoctor'] is not None:
        case['ApplyDoctor']=case['ApplyDoctor'].replace('\ue09b', '峯') #'許峯銘'

    if case['PackageTime'] is None:
        return

    case['Quantity'] = case['ResultDesc']
    case['ResultDesc'] = 1
    case['ExamineQuantity'] = 1

    case['NhiDeptName'] = case['NhiDept']
    case['Diagnosis'] = case['DiagnosisCode']

    # id = case['ChartNo']+'_'+case['PackageTime'][:4]
    # print(case['PackageTime'].strftime('%Y-%m'))
    id = case['ChartNo']+'_'+case['PackageTime'].strftime('%Y-%m')

    order = NHIOrder.objects.filter(id=id).first()

    if order == None:
        order = NHIOrder(id=id)

    # print(order)
    # exit()
    # order, created = NHIOrder.objects.get_or_create(id=id)

    for k, v in case.items():
        # order[k] = v
        # print(k,v)
        if v is not None:
            setattr(order, k, v)

    if order.Priority is None:
        if order.Quantity == '同意備查':
            order.Priority = 1

    order.save()


def GetCaseForCyberKnifeList(days=30):

    eDate = datetime.date.today()
    sDate = eDate + datetime.timedelta(days=-days)

    settings = zeep.Settings(strict=False, xml_huge_tree=True)
    client = zeep.Client('https://converws.ntuh.gov.tw/WebApplication/NtuhACEService/CyberKnifeService.asmx?WSDL', settings=settings)
    # client = zeep.Client('https://tconverws.ntuh.gov.tw/WebApplication/NtuhACEService/CyberKnifeService.asmx?WSDL', settings=settings)
    result = client.service.GetCaseForCyberKnifeList('T0', sDate, eDate)
    # print(len(result))
    # exit()
    return result
