#!/usr/bin/perl

#use utf8;
use strict;
use CGI;
use JSON;

use Opals::Constant;
use Opals::Context;
use Opals::Equipment qw(
    eq_record_findByRId
    eq_categoryMapList
);
use Opals::Eq_Circulation qw(
    eq_circ_getItemStatus
);
use Opals::Session qw(
    SessionHdl_getSSID
);
my $dbh = Opals::Context->dbh();
END { $dbh->disconnect(); }

my $request=getRequest();
my $cgi     = CGI->new;
my $pStatus=1;

my $ssid        = SessionHdl_getSSID($cgi);
my $varName     =$request->{'varName'};
my $pSize       =$request->{'pSize'};
my $pNum        =$request->{'pNum'};
my $briefFormat =$request->{'briefFormat'};
my $status      =$request->{'status'};
my $displayStyle=$request->{'displayStyle'};
my $op          =$request->{'op'};

my ($ridCount,$bcCount,$itemList);
if ($op =~ m/returnedItem/){
  ($ridCount,$bcCount,$itemList)=getReturnedItemList($dbh,$ssid,$varName,$pSize,$pNum,$briefFormat);
}
else{
 ($ridCount,$bcCount,$itemList)=getItemList($dbh,$ssid,$varName,$pSize,$pNum,$briefFormat);
}
close debug;
#print "Content-type: text/plain\n\n";

print "Content-type: application/json\n\n";
my $rs={status=>1,itemList=>$itemList,bcCount=>$bcCount,ridCount=>$ridCount};
print   to_json($rs);

#-------------------------------------------------------------------------------
sub getItemList{
    my ($dbh,$ssid,$vaName,$pSize,$pNum,$briefFormat)=@_;
    my $itemList=[];
    my ($ridCount,$bcCount)=(0,0);
    my $sql = "";
    if($briefFormat){
        $sql = " select s.rid, barcode,r.rname";
    }
    else{
        $sql = " select s.rid, barcode ";
    }
    my $sql_count =" select count(distinct rid) as ridCount ,count(barcode) as bcCount ";

    $sql .= "  from opl_sessionVar s ";
    $sql_count .= "  from opl_sessionVar  ";
    if($briefFormat){
        $sql .= "  inner join eq_items i using(barcode) inner join eq_records r on r.rid=s.rid ";
    }
    $sql .= " where ssid= ? && var=? ";
    $sql_count .= " where ssid= ? && var=? ";
    if ($displayStyle eq "record") {
        $sql .= " group by rid ";
    }
    $sql .= " order by sOrder";
    if(defined $pSize && $pSize && defined $pNum && $pNum){
        my $offset = ($pNum - 1) * $pSize; 
        $sql .= " limit $offset, $pSize";
    }
    open debug,">/tmp/oo"; print debug "$sql\n$ssid,$vaName\n sql_count:$sql_count \n"; close debug;
    my $sth_count =$dbh->prepare($sql_count);
    $sth_count->execute($ssid,$vaName);
    if(my $r =$sth_count->fetchrow_hashref){
       ($ridCount,$bcCount)= ($r->{'ridCount'},$r->{'bcCount'});
    }

    my $sth =$dbh->prepare($sql);
    $sth->execute($ssid,$vaName);
    while( my $item=$sth->fetchrow_hashref){
        $item->{'selected'}= TRUE;
        $item->{'circInfo'}=eq_circ_getItemStatus($dbh,{barcode=>$item->{'barcode'}});
        if (!$briefFormat) {
           $item   = findRecordById($dbh,{recordId=>$item->{'rid'}});
        }
        push @$itemList, $item;

    }
    return ($ridCount,$bcCount,$itemList);

}
sub getReturnedItemList{
  my ($dbh,$ssid,$vaName,$pSize,$pNum,$briefFormat)=@_;
  my $itemList=[];
    my ($ridCount,$bcCount)=(0,0);
    my $sql_count =" select count(distinct rid) as ridCount ,count(barcode) as bcCount ";
    $sql_count .= "  from opl_sessionVar  where ssid= ? && var=? ";

    my $sql .= "select l.id as rid from opl_sessionVar s inner join eq_loan l on s.rid=l.id ";
    $sql .= " where s.ssid= ? && s.var=? && l.dateReturn is not NULL";
    open debug,">/tmp/oo"; print debug "$sql\n$ssid,$vaName\n sql_count:$sql_count\t$ssid \t$vaName, \n"; close debug;
    my $sth_count =$dbh->prepare($sql_count);
    $sth_count->execute($ssid,$vaName);
    if(my $r =$sth_count->fetchrow_hashref){
       ($ridCount,$bcCount)= ($r->{'ridCount'},$r->{'bcCount'});
    }

    my $sth =$dbh->prepare($sql);
    $sth->execute($ssid,$vaName);
    while( my $item=$sth->fetchrow_hashref){
        $item->{'selected'}= TRUE;
        push @$itemList, $item;
    }
    return ($ridCount,$bcCount,$itemList);

}


#-------------------------------------------------------------------------------
sub getRequest{
  my $fineList=[];
  my $in={};
  if ($ENV{'REQUEST_METHOD'} eq "POST") {
        my $json ="";
        while (<STDIN>) {
            $json .= $_;
        }
        $in = decode_json($json);
   }
   return $in;
}

sub findRecordById {

    my ($dbh,$params) = @_;
    return if ($params->{'recordId'} eq '');
    my $rid = $params->{'recordId'};
    my $categoryMapList = eq_categoryMapList($dbh);
    my @recordInfo=();
    my $sql = "SELECT r.rid,r.rname,r.category,r.container,  rf.fId, rf.fValue as fValue
                FROM eq_records as r 
                    left JOIN eq_recordFields as rf ON r.rid = rf.rid 
                    right JOIN eq_def as d ON rf.fId = d.id && r.rid = ?
                WHERE d.defType = 'record'  order by d.fOrder";
    my $sth = $dbh->prepare($sql);
    $sth->execute($params->{'recordId'});
    my $record;
    while( my $rec = $sth->fetchrow_hashref){
        if (!$record->{'rid'} ) {
            $record->{'rid'} = $rec->{'rid'};
        }
        if (!$record->{'name'} ) {
            $record->{'name'} = $rec->{'rname'};
        }
        if (!$record->{$rec->{'fId'}}){
            $record->{$rec->{'fId'}} = $rec->{'fValue'};
        }
    }
    my @barcodeList = ();
    $sql = "select barcode from eq_items where barcode not regexp '^\_\_\_'  && rid = $rid order by barcode";
    $sth = $dbh->prepare($sql);
    $sth->execute();
    my $i=0;
    while (my $bc = $sth->fetchrow_hashref()){
        push @barcodeList, { 
            barcode => $bc->{'barcode'},
        };
    }
    $record->{'items'} = \@barcodeList;
    
    $sth->finish;
    return $record;
}

