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 ReportStaffFeeDetail(Model):
    _name="clinic.report.staff.fee"
    _string="Report Staff Fee"
    _transient=True
    
    _fields={
        "date": fields.Date("Month"),
        "date_from": fields.Date("From", required=True),
        "date_to": fields.Date("To", required=True),
        'staff_id': fields.Many2One("clinic.staff","Staff"),
        "type": fields.Selection([["doctor","Doctor"],["nurse","Nurse"],["staff","Staff"]],"Type"),
        'department_id': fields.Many2One("clinic.department","Department"),
        'branch_id': fields.Many2One("clinic.branch","Branch"),
    }

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

    def _get_date_to(self,context={}):
        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,
    }
    
    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("-")
            time_start='%s-%s-01'%(year,str(month).zfill(2))
            time_stop='%s-%s-%s'%(year,str(month).zfill(2),total_day)
        staff_id=None
        staff_type=None
        department=None
        branch=None
        if ids:
            obj=self.browse(ids)[0]
            month=obj.date_from.split("-")[1]
            time_start=obj.date_from
            time_stop=obj.date_to
            staff_id=obj.staff_id.id
            staff_type=obj.type
            department=obj.department_id
            branch=obj.branch_id
        # new patient of this month
        dom=[]
        dom.append(['date','>=',time_start])
        dom.append(['date','<=',time_stop])
        if department:
            dom.append(['staff_id.department_id','=',department.id])
        if branch:
            dom.append(['staff_id.branch_id','=',branch.id])
        if staff_type:
            dom.append(['staff_id.type','=',staff_type])
        staff_name=''
        show_qty=False
        if staff_id:
            dom.append(['staff_id','=',staff_id])
            show_qty=True 
        dlines=get_model('clinic.labor.cost.line').search_browse(dom)
        # group by date
        all_vals={}
        for dline in dlines:
            date=dline.date
            staff=dline.staff_id
            dpt=staff.department_id
            brch=staff.branch_id
            key=(date,staff.id)
            if key not in all_vals.keys():
                all_vals[key]={
                   'qty': 0,
                   'staff_type': utils.STAFF_TYPE.get(staff.type,''),
                   'staff_name': staff.name or "",
                   'staff_id': staff.id,
                   'branch_name': brch.name or '',
                   'department_name': dpt.name or '',
                   'amount': 0,
                }
            all_vals[key]['qty']+=dline.qty or 0
            all_vals[key]['amount']+=dline.amount or 0

        lines=[]
        total_amount=0.0
        total_qty=0.0
        for key,vals in all_vals.items():
            date,staff_id=key
            qty=vals['qty'] or 0
            amount=vals['amount'] or 0
            lines.append({
               'date': date,
               'qty': qty,
               'staff_id': vals['staff_id'],
               'staff_type': vals['staff_type'],
               'staff_name': vals['staff_name'],
               'department_name': vals['department_name'],
               'branch_name': vals['branch_name'],
               'amount': amount or 0.0,
            })
            total_qty+=qty
            total_amount+=amount
            
        month_str=utils.MONTHS['th_TH'][int(month)]
        start=int(time_start[8:10])
        stop=int(time_stop[8:10])
        diff=stop-start
        branch_name=''
        if branch:
            branch_name='(%s)'%branch.name or ''
        if department:
            branch_name='(%s)'%department.name or ''
        data={
            'company_name': company.name or "",
            'parent_company_name': company.parent_id.name or "",
            'staff_name': staff_name,
            'lines': sorted(lines,key=lambda x: x['date']),
            'total_qty': total_qty,
            'total_amount': total_amount,
            'month': month_str,
            'from': time_start,
            'to': time_stop,
            'is_duration': diff+1 < total_day,
            'year': year,
            'branch_name': branch_name,
            'show_qty': show_qty,
        }
        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

ReportStaffFeeDetail.register()