#!/usr/bin/python
# coding=utf-8

### 已移至 M5A99FX 執行 ###

from operator import *
from ntuhgov.portal_spynner import *

import collections
import datetime
import multiprocessing
import os
import time


import sys  
reload(sys)  
sys.setdefaultencoding('utf8')

def get_path():
    import os,sys
    return os.path.realpath(os.path.dirname(sys.argv[0]))

def jprint(a):
    import json    
    print json.dumps(a, ensure_ascii = False, indent=4, sort_keys=True)


import csv
# def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
#     # csv.py doesn't do Unicode; encode temporarily as UTF-8:
#     csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),
#                             dialect=dialect, **kwargs)
#     for row in csv_reader:
#         # decode UTF-8 back to Unicode, cell by cell:
#         yield [unicode(cell, 'utf-8') for cell in row]
# def utf_8_encoder(unicode_csv_data):
#     for line in unicode_csv_data:
#         yield line.encode('utf-8')
def unicode_csv_reader(utf8_data, dialect=csv.excel, **kwargs):
    csv_reader = csv.reader(utf8_data, dialect=dialect, **kwargs)
    for row in csv_reader:
        yield [unicode(cell, 'utf-8') for cell in row]
        

# reader = csv.reader(open(get_path()+"/vs.csv", "rb"))
reader = unicode_csv_reader(open(get_path()+"/vs.csv", "rb"))

vs = {}
for row in reader:
#     print row[1], row[0]
    vs[row[1]]=row[0]
    
# exit()
    
def find_dir(*paths):
    for path in paths:
        if os.path.isdir(path):
            return path
    return ''


html_dir = find_dir(
#                    '/Shared/public_html',
                    '/home/xfr/workspace/media.ntuh.net/public_html',
                    '/home/ntuh/domains/media.ntuh.net/public_html',
                    '.')

def DivCode(v):
    if v in vs:
        div = vs[v]
    else:
        div = 'Other'
#     print v, div
    return div

def unf_start_end(a, b):
    StartDate = (datetime.date.today() + datetime.timedelta(days=a)).strftime('%Y/%m/%d')
    EndDate = (datetime.date.today() + datetime.timedelta(days=b)).strftime('%Y/%m/%d')
    
    print StartDate, EndDate

    list = WardQueryUncompletedChart(StartDate, EndDate)
    
    '''
{
    "主治": " ", 
    "住院": " ", 
    "姓名": "測試病人", 
    "帳號": "", 
    "床號": "YI2B2701", 
    "序": "1", 
    "病歷號": "Y800001", 
    "科部": "SURG", 
    "結束日": "2013/12/30", 
    "註": " ", 
    "逾期": "347", 
    "開始/手術日": "2013/12/26", 
    "類別": ""
}

    '''

    return list    


def unf(days=30, dest='unf.html'):
    list = unf_start_end(-365, 0)
#     list = unf_start_end(-180, 0)
#     list = unf_start_end(-90, 0)

#     list = unf_start_end(-60, 0)

    lt30 = []
    ge30 = []
    for r in list:
        if 'H' in r['病歷號']:
            continue
        if 'Y' in r['病歷號']:
            continue
        
        try:
            overdue = int(r['逾期'])
        except:
            continue
        
        if overdue < days:
            lt30.append(r)
        else:
            ge30.append(r)
# #         jprint(r)
#         print r['開始/手術日'], r['結束日'], r['主治'], r['住院'], r['逾期']
#         
#     exit()



    vslt30 = collections.Counter([r['主治'] for r in lt30])
    vsge30 = collections.Counter([r['主治'] for r in ge30])
    
    dvlt30 = collections.Counter([DivCode(r['主治']) for r in lt30])
    dvge30 = collections.Counter([DivCode(r['主治']) for r in ge30])
    
    rlt30 = collections.Counter([r['住院'] for r in lt30])
    rge30 = collections.Counter([r['住院'] for r in ge30])
    
    print 'vslt30'
    for elem, cnt in vslt30.most_common():
        print elem, cnt

    print 'vsge30'
    for elem, cnt in vsge30.most_common():
        print elem, cnt

    
    dr1 = vslt30.most_common()
    resident1 = rlt30.most_common()
    division1 = dvlt30.most_common()

    dr2 = vsge30.most_common()
    resident2 = rge30.most_common()
    division2 = dvge30.most_common()
    
    print len(list), len(dr1), len(resident1) 
    
    if len(dr1) < 2:
        return

    length = max(
		 len(dr1),
         len(resident1),
         len(dr2),
         len(resident2))
    
    print length

    result=[]

    result.append(['主治醫師','科別','份數','住院醫師','份數','主治醫師','科別','份數','住院醫師','份數'])

    d1 = 0
    r1 = 0
    d2 = 0
    r2 = 0
    for i in range(length):
        r = []
        if i < len(dr1):
            r.append(dr1[i][0])
            r.append(DivCode(dr1[i][0]))
            r.append(dr1[i][1])
            d1 += dr1[i][1]
        else:
            r.append('')
            r.append('')
            r.append('')
        if i < len(resident1):
            r.append(resident1[i][0])
            r.append(resident1[i][1])
            r1 += resident1[i][1]
        else:
            r.append('')
            r.append('')
        if i < len(dr2):
            r.append(dr2[i][0])
            r.append(DivCode(dr1[i][0]))
            r.append(dr2[i][1])
            d2 += dr2[i][1]
        else:
            r.append('')
            r.append('')
            r.append('')
        if i < len(resident2):
            r.append(resident2[i][0])
            r.append(resident2[i][1])
            r2 += resident2[i][1]
        else:
            r.append('')
            r.append('')

        result.append(r)

#    output = open('/home/xfr/mysite/site_media/unf.html','w')
    print '%s/%s' % (html_dir,dest)
    output = open('%s/%s' % (html_dir,dest), 'w')

    print >> output, """
<html>
<head>
<meta http-equiv=Content-Type content="text/html; charset=utf-8">
<title>外科部病歷未完成</title>
</head>
<body>
"""

    print >> output, "<table><tbody align='center'>"
    print >> output, "<tr><td colspan='10'>%s</td></tr>" % time.asctime()
    print >> output, "<tr><td colspan='5'>逾期30日內</td><td colspan='5'>30日以上</td></tr>" 
    for r in result:
        print >> output ,"<tr>"
        for c in r:
            print >> output, "<td>%s</td>" % c
        print >> output ,"</tr>"

    print >> output, "<tr><td>---</td></tr>"
    print >> output, "<tr>"
    print >> output, "<td>總計</td><td></td><td>%i</td>" % d1
    print >> output, "<td>總計</td><td>%i</td>" % r1
    print >> output, "<td>總計</td><td></td><td>%i</td>" % d2
    print >> output, "<td>總計</td><td>%i</td>" % r2
    print >> output, "</tr>"

    print >> output, "</tbody></table>"
    print >> output, "<hr/>"
    print >> output, "<table><tbody align='center'>"


    div1 = dict(division1)
    div2 = dict(division2)
    
    division3 = (dvlt30+dvge30).most_common()

    print >> output, "<tr><td></td>"
    for div, count in division3:
        print >> output, "<td>%s</td>" % div
    print >> output, "</tr>"

    print >> output, "<tr><td>逾期30日內</td>"
    for div, count in division3:
        print >> output, "<td>%s</td>" % dvlt30[div]
    print >> output, "</tr>"

    print >> output, "<tr><td>30日以上</td>"
    for div, count in division3:
        print >> output, "<td>%s</td>" % dvge30[div]
    print >> output, "</tr>"

    print >> output, "<tr><td>合計</td>"
    for div, count in division3:
        print >> output, "<td>%s</td>" % count
    print >> output, "</tr>"


    print >> output, "</tbody></table>"

    print >> output, "</body></html>"



    output.close()

    return result

def unf_month():
    day = datetime.date.today().day
    EndDate = datetime.date.today() + datetime.timedelta(days=-day)

#    unf1 = unf_sort(-365,-day)
    unf1 = unf_start_end(-365,-day)

    dr1 = unf1['dr']
    resident1 = unf1['resident']
    division1 = unf1['division']

    length = max(len(dr1),
                 len(resident1))

    result=[]

    result.append(['主治醫師','科別','份數','住院醫師','份數'])

    d1 = 0
    r1 = 0
    for i in range(length):
        r = []
        if i < len(dr1):
            r.append(dr1[i][0])
            r.append(DivCode(dr1[i][0]))
            r.append(dr1[i][1])
            d1 += dr1[i][1]
        else:
            r.append('')
            r.append('')
            r.append('')
        if i < len(resident1):
            r.append(resident1[i][0])
            r.append(resident1[i][1])
            r1 += resident1[i][1]
        else:
            r.append('')
            r.append('')

        result.append(r)

#    output = open('/home/xfr/mysite/site_media/unf.html','w')
    output = open('%s/unf_month.html' % html_dir, 'w')

    print >> output, """
<html>
<head>
<meta http-equiv=Content-Type content="text/html; charset=utf-8">
<title>上月外科部病歷未完成</title>
</head>
<body>
"""

    print >> output, "<table><tbody align='center'>"
    print >> output, "<tr><td colspan='5'>%s</td></tr>" % time.asctime()
    print >> output, "<tr><td colspan='5'>%s前</td></tr>" % EndDate
    for r in result:
        print >> output ,"<tr>"
        for c in r:
            print >> output, "<td>%s</td>" % c
        print >> output ,"</tr>"

    print >> output, "<tr><td>---</td></tr>"
    print >> output, "<tr>"
    print >> output, "<td>總計</td><td></td><td>%i</td>" % d1
    print >> output, "<td>總計</td><td>%i</td>" % r1
    print >> output, "</tr>"
    print >> output, "</tbody></table>"

    print >> output, "<hr/>"
    print >> output, "<table><tbody align='center'>"


    div1 = dict(division1)

#    print div1
#    print div2
#    print div3

    division_sort = sorted(list(div1), key=lambda x: -div1[x])
 #   print division_sort

    print >> output, "<tr><td></td>"
    for div in division_sort:
        print >> output, "<td>%s</td>" % div
    print >> output, "</tr>"

    print >> output, "<tr><td>合計</td>"
    for div in division_sort:
        print >> output, "<td>%s</td>" % div1[div]
    print >> output, "</tr>"


    print >> output, "</tbody></table>"

    print >> output, "</body></html>"

    output.close()

    return result


# unf()

if __name__ == '__main__':
    # Start foo as a process
    p = multiprocessing.Process(target=unf)
    p.start()

#     # Wait 10 seconds for foo
#     time.sleep(100)

    # Wait a maximum of 10 seconds for foo
    # Usage: join([timeout in seconds])
    p.join(200)
    
    # If thread is active
    if p.is_alive():
        print "foo is running... let's kill it..."
    
        # Terminate foo
        p.terminate()
        p.join()