import time
from calendar import monthrange

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

from . import utils

class ReportVisit(Model):
    _name="clinic.report.visit"
    _string="Report Visit"
    _transient=True
    
    _fields={
        "date": fields.Date("Month"),
        "date_from": fields.Date("From", required=True),
        "date_to": fields.Date("To", required=True),
        "patient_id": fields.Many2One("clinic.patient","Patient",domain=[['state','=','admit']]),
        "doctor_id": fields.Many2One("clinic.staff","Doctor",domain=[['type','=','doctor']]),
        "state": fields.Selection([["draft","Draft"],['pending','Pending'],["confirmed","Confirmed"],["cancelled","Cancelled"]],"Status",required=True),
    }

    def _get_date_from(self,context={}):
        return time.strftime("%Y-%m-%d")
        year,month=time.strftime("%Y-%m").split("-")
        return '%s-%s-01'%(year,month)

    def _get_date_to(self,context={}):
        return time.strftime("%Y-%m-%d")
        year,month,day=time.strftime("%Y-%m-%d").split("-")
        weekday, total_day=monthrange(int(year), int(month))
        return "%s-%s-%s"%(year,month,total_day)

    _defaults={
        'date': lambda *a: time.strftime("%Y-%m-%d"),
        'date_from': _get_date_from,
        'date_to': _get_date_to,
        'state': 'pending',
    }
    
    def get_report_data(self,ids,context={}):
        company_id=get_active_company()
        company=get_model('company').browse(company_id)
        year, month=time.strftime("%Y-%m").split("-")
        weekday, total_day=monthrange(int(year), int(month))
        time_start='%s-%s-01'%(year,str(month).zfill(2))
        time_stop='%s-%s-%s'%(year,str(month).zfill(2),total_day)

        defaults=context.get('defaults')
        if defaults:
            year,month,day=defaults['date'].split("-")
            weekday, total_day=monthrange(int(year), int(month))
            time_start='%s-%s-01'%(year,str(month).zfill(2))
            time_stop='%s-%s-%s'%(year,str(month).zfill(2),total_day)
        patient_id=None
        doctor_id=None
        state=None
        if ids:
            obj=self.browse(ids)[0]
            month=obj.date_from.split("-")[1]
            time_start=obj.date_from
            time_stop=obj.date_to
            patient_id=obj.patient_id.id
            doctor_id=obj.doctor_id.id
            state=obj.state
        # new patient of this month
        dom=[]
        dom.append(['visit_date','>=',time_start])
        dom.append(['visit_date','<=',time_stop])
        if patient_id:
            dom.append(['patient_id','=',patient_id])
        if doctor_id:
            dom.append(['doctor_id','=',doctor_id])
        if state:
            dom.append(['state','=',state])

        records=get_model('clinic.visit').search_browse(dom)
        lines=[]
        no=1
        for record in sorted(records,key=lambda x: (x.patient_id.name or "",x.visit_date)):
            lines.append({
               'no': no,
               'vid': record.id,
               'cid': record.cycle_id.id,
               'cname': record.cycle_id.name or "",
               'pid': record.patient_id.id or '',
               'hn': record.patient_id.hn_no or '',
               'pname': record.patient_id.name or '',
               'tname': record.patient_id.type_id.name or '',
               'tid': record.patient_id.type_id.id or '',
               'did': record.doctor_id.id,
               'dname': record.doctor_id.name or "",
               #'date': record.visit_date or '',
               'date': utils.date2thai(record.visit_date or '',format='%(Td)s %(d)s/%(m)s/%(BY)s'),
               'note': record.note or '',
            })
            no+=1
            
        month_str=utils.MONTHS['th_TH'][int(month)]
        start=int(time_start[8:10])
        stop=int(time_stop[8:10])
        diff=stop-start
        data={
            'company_name': company.name or "",
            'parent_company_name': company.parent_id.name or "",
            'lines': lines,
            'month': month_str,
            'from': time_start,
            'to': time_stop,
            'is_duration': diff+1 < total_day,
            'year': year,
        }
        return data

    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

ReportVisit.register()