import time

from netforce.model import Model, fields, get_model
from netforce.utils import get_file_path
from . import utils

class ImportHDCase(Model):
    _name="clinic.import.hd.case"
    _transient=True

    _fields={
        'date': fields.Date("Date"),
        'file': fields.File("File"),
        'hcode_id': fields.Many2One("clinic.hospital", "Hospital",required=True),
        'max_row': fields.Integer("Max Row"),
        'remain_row': fields.Integer("Import Pending"),
        'total_row': fields.Integer("Total Case"),
        'msg': fields.Text("Message"),
        'done_qty': fields.Integer("Success"),
        'fail_qty': fields.Integer("Fail"),
    }
    
    def get_hcode_id(self,context={}):
        hp_ids=get_model("clinic.hospital").search([])
        hp_id=None
        if hp_ids:
            hp_id=hp_ids[0]
        return hp_id

    _defaults={
        'date': lambda *a: time.strftime("%Y-%m-%d %H:%M:%S"),
        'hcode_id': get_hcode_id,
        'max_row': 50,
    }

    def import_hd_case(self,ids,context={}):
        obj=self.browse(ids)[0]
        fname=obj.file
        fpath=get_file_path(fname)
        lines=utils.read_excel(fpath,show_datetime=True)
        if not lines:
            raise Exception("Wrong File")

        st_lines=[]
        st=get_model("clinic.setting").browse(1)
        for st_prod in st.products:
            prod=st_prod.product_id
            if st_prod.patient_type=='sc':
                st_lines.append(('create',{
                    'type': st_prod.type,
                    'product_id': prod.id,
                    'uom_id': prod.uom_id.id,
                    'description': prod.name,
                    'qty': 1,
                    'price': st_prod.price,
                    'amount': st_prod.price,
                }))
        policy=''
        option=''
        for st_policy in st.invoice_policies:
            if st_policy=='sc':
                policy=st_policy.invoice_policy
                option=st_policy.invoice_option
        msg=""
        max_row=obj.max_row
        count=0
        did=0
        blank=0
        fail_qty=0
        done_qty=0
        for line in lines:
            name=line.get("name14")
            hn=line.get('hn',"")
            hct=line.get("hct","")
            hcode=line.get('hcode18','0')
            if not hcode:
                hcode='0'
            hcode=int(hcode)
            hcode=str(hcode)
            if not obj.hcode_id.code==hcode:
                if hcode:
                    if hcode!='0':
                        msg+="not found %s, %s, %s \n"%(hcode,hn,name)
                        fail_qty+=1
                    else:
                        blank+=1
                else:
                    blank+=1
                continue
            dttran=line.get("dttran","")
            date=dttran[0:10]
            pt_ids=get_model("clinic.patient").search([['name','=',name]])
            if not pt_ids:
                pt_ids=get_model("clinic.patient").search([['hn','=',hn]])

            if count > max_row:
                #XXX timeout
                break

            hlines=[]
            if pt_ids:
                prod_price=line.get("epopay27") # XXX
                prod_code=line.get("code31")
                prods=get_model("product").search_browse([['code','=',prod_code]])
                if prods:
                    prod=prods[0]
                    hlines=[('create',{
                        'type': 'medicine',
                        'product_id': prod.id,
                        'uom_id': prod.uom_id.id,
                        'description': prod.name,
                        'price': prod_price or 0.0,
                        'qty': 1,
                        'amount': prod_price or 0.0,
                    })]

                patient_id=pt_ids[0]
                visit_obj=get_model("clinic.visit")
                visits=visit_obj.search_browse([['visit_date','=',date],['patient_id','=',patient_id],['state','=','draft']])
                if visits:
                    count+=1
                    done_qty+=1
                    hlines+=st_lines
                    visit=visits[0]
                    cycle=visit.cycle_id
                    vals={
                        'patient_id': patient_id,
                        'hct': hct or 0,
                        'invoice_policy': policy,
                        'invoice_option': option,
                        'date': visit.visit_date,
                        'time_start': visit.time_start,
                        'time_stop': visit.time_stop, # XXX
                        'visit_id': visit.id,
                        'cycle_id': cycle.id,
                        'lines': hlines,
                    }
                    hd_case_obj=get_model("clinic.hd.case")
                    hd_case_id=hd_case_obj.create(vals)
                    visit.confirm()
                    hd_case=hd_case_obj.browse(hd_case_id)
                    hd_case.done()
                    for inv in hd_case.invoices:
                        inv.write({
                            'date': inv.due_date,
                        })
                    msg+="confirm visit %s\n"%(visit.visit_date)
                else:
                    did+=1
            else:
                pass
        total_row=len(lines)
        remain_row=total_row-blank-did-count
        if remain_row <= 0:
            msg="Nothing to import"
        final_msg=''

        if done_qty <=0 and did==0:
            final_msg="Please import visit first"
            raise Exception(final_msg)
        elif done_qty <=0 and did!=0:
            final_msg="Nothing to import"
            total_row=0
            done_qty=0
            fail_qty=0
            remain_row=0
        else: final_msg="Done!"
        obj.write({
            'total_row': total_row,
            'remain_row': remain_row+1, # XXX
            'msg': msg,
            'done_qty': done_qty and done_qty-1 or 0,
            'fail_qty': fail_qty,
        })
        print("Done!")
        return {
            'next': {
                'name': 'import_clinic_hd_case',
                'mode': 'form',
                'active_id': obj.id,
            },
            'flash': final_msg,
        }

ImportHDCase.register()