#!/usr/bin/perl

#use utf8;
use strict;
use CGI;

use Opals::Context;
use POSIX qw(
    floor
    ceil
);

use Time::localtime;
use Opals::Constant;

use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_rangedPageList
);




my $dbh = Opals::Context->dbh();
END { $dbh->disconnect(); }

my $cgi = CGI->new;
my $input = $cgi->Vars();

my ($permission, $cookie, $template) = tmpl_read(
        {
            dbh             => $dbh,
            cgi             => $cgi,
            tmplFile        => 'eqmnt/ajax/inventory/getBCListByInvId.tmpl',
            reqPermission   => 'eq_report',
        }
);

    my $invId   = $input->{'invId'};
    my $fid     = $input->{'fid'}|| 0;
    my $pNum    = $input->{'pNum'} || 1;
    my $pSize   = $input->{'pSize'} || 10;
   
    my @list = getInputFileData($dbh, $fid, $invId, $pNum,$pSize); 
    $template->param(
        invId   =>   $invId,
        pNum    =>   $pNum,
        pSize   =>   $pSize,
        list => \@list 
    ); 

tmpl_write($dbh, $cgi, $cookie, $template);
$dbh->disconnect();
    

sub getInputFileData {
    my ($dbh, $fid, $invId, $pNum, $pSize) = @_;
    $pNum = 1 if ($pNum <1);
    my $pOffset = $pSize * ($pNum - 1);
    my $query = "select * from eq_inventory ";
    if (!$fid || $fid =~ m/[\D]/){
        $query .= " where fid > 0";
    }
    else {
        $query .= " where fid = $fid";
    }
    $query .= " && invId = $invId ";
    $query .= " order by fid, scanOrder limit $pOffset, $pSize ";
    my $sth = $dbh->prepare($query);
    my @bc;
    $sth->execute();
    while ( my $h = $sth->fetchrow_hashref){
        push @bc , $h;
    }
    $sth->finish;
    return @bc;
}

