# -*- coding: utf-8 -*-
'''
#NTUHWeb1_QueryOPPatListCommon1_QueryFinishRecordByDRRS
'''
from datetime import datetime, timedelta

import calendar
import csv
import os
import re


from ntuhgov.portal_selenium import Login, SimpleQueryOpSchedule, SimpleQueryOpScheduleDRRS

CSV_FILE = "%s/172_16_3_33_389.csv" % os.path.dirname(os.path.realpath(__file__))

R_DICT = {}
R_LIST = []

def find_dir(*paths):
    for path in paths:
        if os.path.isdir(path):
            return path
    return ''

OUTDIR=find_dir('/home/ntuh/domains/static.ntuh.net/public_html','/shares/Public/@Downloads','/tmp')
OUTFILE = os.path.join(OUTDIR, 'DRRS.xlsx')

def GetOP(DrCode, start, end):

    PatList = []

    # print('Getting ', DrCode)


    results = SimpleQueryOpScheduleDRRS(DrCode, start, end)
    if results:
        print (results)
        print (len(results))
        # exit()

    return len(results)

    for r in results:
        PatList.append(r['PatChartNo'])

    # print (results)
    # print(len(results), len(PatSet))
    # if results:
        # pprint(results[0])
        # exit()

    return PatList

def ReadCN():

    today = datetime.today()

    year  = today.year
    month = today.month

    start = '%d/%d/1' % (year, month)
    end   = '%d/%d/%d'% (year, month, calendar.monthrange(year, month)[1])

    first = today.replace(day=1)
    lastMonth = first - timedelta(days=1)

    year_1  = lastMonth.year
    month_1 = lastMonth.month

    start_1 = '%d/%d/1' % (year_1, month_1)
    end_1   = '%d/%d/%d'% (year_1, month_1, calendar.monthrange(year_1, month_1)[1])


    cn_pattern = 'CN=(\d+),'

    with open(CSV_FILE) as csvfile:
        # spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
        spamreader = csv.reader((line.replace('\0','') for line in csvfile), delimiter=',', quotechar='"')
        for row in spamreader:
            join_row = ', '.join(row)
            if '住院醫師' in join_row:
                # print(join_row)
                # exit()
                m = re.search(cn_pattern, join_row)
                CN = m.group(1)
                R_DICT[CN] = row[22].strip()

                # print (R_DICT[CN])
                # exit()

                # print(join_row)
                # print(CN)

                # exit()
            # print(', '.join(row))



    # print(sorted(VS_LIST))
    # print (len(VS))

    from openpyxl import Workbook
    wb = Workbook()

    ws = wb.active
    ws.title = '%d-%d' % (year, month)
    for r in sorted(R_DICT):
        print('%s %s'%(r, R_DICT[r]))
        OPnum = GetOP(r, start, end)
        # print(OPList)
        if OPnum:
            print('%s, %s, %d'%(r, R_DICT[r], OPnum))
            # exit()
            ws.append([r, R_DICT[r], OPnum])

    title = '%d-%d' % (year_1, month_1)
    wb.create_sheet(title)
    ws = wb[title]

    for r in sorted(R_DICT):
        print('%s %s'%(r, R_DICT[r]))
        OPnum = GetOP(r, start_1, end_1)
        # print(OPList)
        if OPnum:
            print('%s, %s, %d'%(r, R_DICT[r], OPnum))
            # exit()
            ws.append([r, R_DICT[r], OPnum])

    wb.save(OUTFILE)



ReadCN()
exit()
