import time
from datetime import datetime
from calendar import monthrange

from netforce.model import Model, fields, get_model
from netforce.access import get_active_company
from . import utils

class HDCasePrint(Model):
    _name="clinic.hd.case.print"
    _transient=True

    _fields={
        "date": fields.Date("Month"),
        "date_from": fields.Date("From", required=True),
        "date_to": fields.Date("To", required=True),
    }

    def default_get(self,field_names=None,context={},**kw):
        defaults=context.get("defaults",{})
        date=defaults.get('date',time.strftime("%Y-%m-%d"))
        year,month=time.strftime("%Y-%m").split("-")
        weekday, total_day=monthrange(int(year), int(month))
        date_from=defaults.get('date_from','%s-%s-01'%(year,month))
        date_to=defaults.get('date_to',"%s-%s-%s"%(year,month,total_day))
        res={
            'date': date,
            'date_from': date_from,
            'date_to': date_to,
        }
        return res
    
    def onchange_date(self,context={}):
        data=context['data']
        date=data['date']
        year,month,day=date.split("-")
        weekday, total_day=monthrange(int(year), int(month))
        data['date_from']="%s-%s-01"%(year,month)
        data['date_to']="%s-%s-%s"%(year,month,total_day)
        return data

    def get_data(self,context={}):
        return

    def get_report_data(self,ids,context={}):
        company_id=get_active_company()
        company=get_model("company").browse(company_id)

        date=datetime.now().strftime("%Y-%m-%d")
        year=int(date[0:4])
        crr_month=int(date[5:7])
        weekday, crr_total_day=monthrange(year, crr_month)
        branch_id=None
        department_id=None
        time_start='%s-%s-01 00:00:00'%(year,str(crr_month).zfill(2))
        time_stop='%s-%s-%s 23:59:59'%(year,str(crr_month).zfill(2),crr_total_day)
        if ids:
            obj=self.browse(ids)[0]
            branch_id=obj.branch_id.id
            department_id=obj.department_id.id
            date=obj.date 
            crr_month=int(date[5:7]) #XXX
            time_start='%s 00:00:00'%obj.date_from
            time_stop='%s 23:59:59'%obj.date_to
            year=int(date[0:4])

        prev_year=year
        next_year=year
        prev_month=crr_month-1
        next_month=crr_month+1
        if crr_month==1:
            prev_month=12
            prev_year-=1
        if crr_month==12:
            next_month=1
            next_year+=1

        month_str=utils.MONTHS['th_TH'][crr_month]
        next_month_str=utils.MONTHS['th_TH'][next_month]
        prev_month_str=utils.MONTHS['th_TH'][prev_month]
              
        def encode_url(dom):
            dom='%s'%dom
            dom=urllib.quote(dom.encode('utf-8'))
            return dom

        def replace_quote(dom=""):
            return dom.replace("'","\"")
            
        count=1
        # number of hd case of this month
        dom=[]
        dom.append(["time_start",">=",time_start])
        dom.append(["time_stop","<=",time_stop])
        dom.append(["state","in",["completed","waiting_payment","paid"]])
        dom.append(['patient_id.walkin','=','no'])
        if branch_id:
            dom.append(['branch_id','=',branch_id])
        if department_id:
            dom.append(['department_id','=',department_id])
        crr_total=len(get_model("clinic.hd.case").search(dom))
        items={}
        items['topic%s'%count]={
                'month': month_str,
                'qty': crr_total or 0,
                'action': 'clinic_hd_case',
                'action_options': 'mode=list&search_domain=%s&tab_no=0'%replace_quote('%s'%dom),
            }
        count+=1

        # number of patient from previous
        dom=[]
        weekday, prev_total_day=monthrange(prev_year, prev_month)
        time_stop='%s-%s-%s'%(prev_year,str(prev_month).zfill(2),prev_total_day)
        dom.append(['reg_date','<=',time_stop])
        if branch_id:
            dom.append(['branch_id','=',branch_id])
        if department_id:
            dom.append(['department_id','=',department_id])
        npatient=len(get_model("clinic.patient").search(dom))
        dom=replace_quote('%s'%dom)
        items['topic%s'%count]={
                'month': prev_month_str,
                'qty': npatient or 0,
                'action': 'clinic_patient',
                'action_options': 'mode=list&search_domain=%s'%dom,
            }
        count+=1

        # new patient of this month
        dom=[]
        weekday, crr_total_day=monthrange(prev_year, crr_month)
        time_start='%s-%s-01'%(year,str(crr_month).zfill(2))
        time_stop='%s-%s-%s'%(year,str(crr_month).zfill(2),crr_total_day)
        dom.append(['reg_date','>=',time_start])
        dom.append(['reg_date','<=',time_stop])
        if branch_id:
            dom.append(['branch_id','=',branch_id])
        if department_id:
            dom.append(['department_id','=',department_id])
        new_patients=get_model('clinic.patient').search_browse(dom)
        dom=replace_quote('%s'%dom)
        items['topic%s'%count]={
                'month': month_str,
                'qty': len(new_patients) or 0,
                'action': 'clinic_patient',
                'action_options': 'mode=list&search_domain=%s'%dom,
            }
        count+=1

        # number for patient who resign for this month
        dom=[]
        time_start='%s-%s-01'%(year,str(crr_month).zfill(2))
        time_stop='%s-%s-%s'%(year,str(crr_month).zfill(2),crr_total_day)
        dom.append(['resign_date','>=',time_start])
        dom.append(['resign_date','<=',time_stop])
        if branch_id:
            dom.append(['branch_id','=',branch_id])
        if department_id:
            dom.append(['department_id','=',department_id])
        resign_patients_qty=0
        resign_patients=[]
        for pt in get_model('clinic.patient').search_browse(dom):
            resign_patients_qty+=1
            resign_patients.append(pt.name)

        del dom[-1]
        dom=replace_quote('%s'%dom)
        items['topic%s'%count]={
                'month': month_str,
                'qty':  resign_patients_qty,
                'action': 'clinic_patient',
                'action_options': 'mode=list&search_domain=%s&tab_no=2'%dom,
            }
        count+=1
        # all patient who are in hospital on select month
        dom=[]
        weekday, crr_total_day=monthrange(year, crr_month)
        time_stop='%s-%s-%s'%(year,str(crr_month).zfill(2),crr_total_day)
        dom.append(['reg_date','<=',time_stop])
        if branch_id:
            dom.append(['branch_id','=',branch_id])
        if department_id:
            dom.append(['department_id','=',department_id])
        total_patient=get_model('clinic.patient').search_browse(dom)
        dom=replace_quote('%s'%dom)
        total_patient_qty=len(total_patient) or 0
        items['topic%s'%count]={
                'month': next_month_str,
                'qty': total_patient_qty-resign_patients_qty,
                'action': 'clinic_patient',
                'action_options': 'mode=list&search_domain=%s'%dom,
            }
        count+=1

        topics=utils.TOPICS
        for ptype in get_model("clinic.patient.type").search_read([[]],['name']):
            tkey='topic%s'%count
            topics.update({
                tkey:{
                    'name': ptype['name'],
                    'unit': 'คน',
                    }
            })


            dom=[]
            time_start='%s-%s-01'%(year,str(crr_month).zfill(2))
            time_stop='%s-%s-%s'%(year,str(crr_month).zfill(2),crr_total_day)
            dom.append(['reg_date','<=',time_stop])
            dom.append(['type_id','=',ptype['id']])
            dom.append(['name','not in', resign_patients])
            npatients_qty=0
            for pt in get_model("clinic.patient").search(dom):
                npatients_qty+=1
            dom=replace_quote('%s'%dom)
            items[tkey]={
                    'month': '',
                    'qty': npatients_qty,
                    'action': 'clinic_patient',
                    'action_options': 'mode=list&search_domain=%s'%dom,
                }
            count+=1

        lines=[] 
        index=1
        for item in items:
            topic='topic%s'%index
            name=utils.TOPICS[topic]['name']
            unit=utils.TOPICS[topic]['unit']
            line=items[topic]
            line['topic']=name
            line['unit']=unit
            lines.append(line)
            index+=1

        context['defaults']={
            'date': date,
            'branch_id': branch_id,
            'department_id': department_id,
            }

        medicals=get_model("clinic.report.medical.summary").get_report_data(ids=[],context=context)
        year=year+543
        sub_name=''
        if department_id:
            dpt=get_model("clinic.department").browse(department_id)
            sub_name="(%s)" % dpt.name or ""
        elif branch_id:
            branch=get_model("clinic.branch").browse(branch_id)
            sub_name="(%s)" % branch.name or ""
        data={
            'branch_id': branch_id,
            'department_id': department_id,
            'date': date,
            'month': month_str,
            'year': year,
            'lines': lines,
            'recent_patients': get_model("clinic.report.recent.patient").get_report_data(ids=[],context=context)['lines'],
            'resign_patients': get_model("clinic.report.discontinue.patient").get_report_data(ids=[],context=context)['lines'],
            'medicals': medicals['lines'],
            'titles': medicals['titles'],
            'company_name': '%s %s'% (company.name or "", sub_name),
            'parent_company_name': company.parent_id.name or "",
        }
        return data

HDCasePrint.register()