#!/usr/bin/perl

#use utf8;
use strict;
use CGI;

use Time::localtime;
use Opals::Context;
use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_preference
);

use Opals::Tb_Record qw(
    
    tb_defRecordIndex_getList
    tb_barcode_getMaxValue
    tb_maxBarcodeDup

    tb_record_setFlagUpdating
    tb_record_findByRId
    tb_record_add
    tb_record_delete
    
    tb_itemType_getList
    tb_item_findByRId
    tb_item_setFlagUpdating
    tb_item_add
    tb_item_update
    tb_item_delete
    tb_item_deleteByBarcode

    tb_barcode_getList
    tb_isbn_getList
    tb_title_getList

    tb_record_idGen
    tb_isBarcodeExist
    tb_barcode_getMaxDup
    tb_createNextBiggerBc

);

use Opals::Tb_Circulation qw(

    circ_getLoanListByRid
    circ_getItemStatus

);

use Opals::Constant;

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        => 'txtbk/ajax/record/save.tmpl',
        reqPermission   => 'tb_record_edit',
    }
);

my $syspref = tmpl_preference($dbh);
my $tm = localtime;
my $dateToday = sprintf("%04d-%02d-%02d %02d:%02d:%02d", 
                $tm->year+1900, ($tm->mon)+1, $tm->mday, $tm->hour, $tm->min, $tm->sec);

my $defRecordIndexList  = tb_defRecordIndex_getList($dbh, 1);
my $tbItemTypeList    = tb_itemType_getList($dbh);

    my $rid             = $input->{'rid'};
    my $opt             = $input->{'opt'};
    my $zEdit           = $input->{'tbZEdit'};
    my $resultId        = $input->{'resultId'};
    my @bCode           = ($cgi->param('barcode'));
    my @itType          = ($cgi->param('itemType'));
    my @copyNo          = ($cgi->param('copyNo'));
    my @lCode           = ($cgi->param('lCode'));
    my @price           = ($cgi->param('price'));
    my @classNo         = ($cgi->param('classNo'));
    my @acqDate         = ($cgi->param('acqDate'));
    my @distributor     = ($cgi->param('distributor'));
    my @PONo            = ($cgi->param('poNo'));
    my @regionCode      = ($cgi->param('regioncode'));
    my @districtCode    = ($cgi->param('districtCode'));
    my @buildingCode    = ($cgi->param('buildingCode'));
    my @importDate      = ($cgi->param('importDate'));
    my @budgetCategory  = ($cgi->param('budgetCategory'));
    my @vendorCatalogNo = ($cgi->param('vendorCatNo'));
    my @delItem         = ($cgi->param('delItem'));
    my @available       = ($cgi->param('available'));
    my $op = '';
    if ($rid && $rid > 0) {
        $op = 'new';
        tb_record_setFlagUpdating($dbh, $rid);
        _tb_item_update($dbh, $rid);
        _tb_item_delete_barcodeByRid($dbh,$rid);
    }
    else{
        $rid = tb_record_idGen($dbh);
    }
    my $retRecAdd = tb_record_add($dbh,$rid,'005',$dateToday);
    foreach my $def(@{$defRecordIndexList}){
        my $fId = $def->{'fieldId'} . "_" . $def->{'subfield'};
        if ($def->{'repeatable'}){
            my @fVals = ($cgi->param($fId));
            foreach my $f(@fVals){
                $retRecAdd = tb_record_add($dbh,$rid,$fId,$f);
            }
        }elsif($def->{'checkbox'}){   
            my $fVal    = $input->{$fId};
            if ($fVal){
                $fVal    = $input->{$fId . '_v'};
                 $retRecAdd = tb_record_add($dbh, $rid, $fId, $fVal);
            }
        }else{
            if ($fId eq '900_a'){
                my @fVals = ($cgi->param($fId));
                my $fVal = join(",", @fVals);
                $retRecAdd = tb_record_add($dbh, $rid, $fId, $fVal);
            }else {
                my $fVal = $input->{$fId};
                $retRecAdd = tb_record_add($dbh, $rid, $fId, $fVal);
            }
        }
    }
    for my $i (0 .. $#bCode){
        my $params = {
            rid             => $rid,
            barcode         => $bCode[$i],
            available       => $available[$i],
            typeId          => $itType[$i],
            copyNo          => $copyNo[$i],
            lCode           => $lCode[$i],
            price           => $price[$i],
            classno         => $classNo[$i],
            acqDate         => $acqDate[$i],
            PONo            => $PONo[$i],
            distributor     => $distributor[$i],
            regionCode      => $regionCode[$i],
            districtCode    => $districtCode[$i],
            buildingCode    => $buildingCode[$i],
            importDate      => $importDate[$i],
            budgetCategory  => $budgetCategory[$i],
            vendorCatalogNo =>$vendorCatalogNo[$i]
        };
        my $retItemAdd = _tb_item_add($dbh, $params);
    }
   
    if ($op eq 'new'){ 
        my $flag_updating = 1;
        tb_record_delete($dbh, $rid,$flag_updating); 
    }
    my $itemList    = tb_item_findByRId($dbh,$rid);
    foreach my $i(@$itemList){
        my $ret = circ_getItemStatus($dbh,$i->{'barcode'});
        if ($ret->{'status'} == IT_STAT_ONLOAN){
            $i->{'onLoan'} = 1;
        }
        if ($ret->{'status'} == IT_STAT_LOST){
            $i->{'lost'} = 1;
        }
        if ($ret->{'status'} == ITEM_DAMAGED){
            $i->{'damaged'} = 1;
        }
    }
    $template->param(
        rid             => $rid,
        itemList        => $itemList,
    );

tmpl_write($dbh, $cgi, $cookie, $template);

#-------------------------------------------------------------------------------------------
#

sub _tb_item_update {
    my ($dbh, $rid) = @_;
    return -1 if ($rid eq '');
    my $sql = "update tb_items set deleted = '1', barcode = CONCAT('TMP_', barcode)  where rid = ? && deleted <> '1'";
    my $sth = $dbh->prepare($sql);
    $sth->execute($rid);
    $sth->finish;
    return $rid;

}
sub _tb_item_delete_barcodeByRid{

    my ($dbh, $rid, $flag ) = @_;
    return -1 if ($rid eq '');

    my $sql = "delete from tb_items where rid = ? && barcode regexp '^TMP_' && deleted='1' ";
    my $sth = $dbh->prepare($sql);
    $sth->execute($rid);
    $sth->finish;
    return $rid;

}

sub _tb_item_add{

    my ($dbh,$params) = @_;
    return -1 if ($params->{'rid'} eq '');
    
    if (tb_isBarcodeExist($dbh,  $params->{'barcode'})){
        my $maxDupBarcode = tb_maxBarcodeDup($dbh, $params->{'barcode'});
        $params->{'barcode'} = $maxDupBarcode;
    }
    my ($sql, $sth,$id);
        $sql = <<_SQL_;
            insert into tb_items set 
                rid=?, 
                barcode=?, 
                copyNo =?,
                available=?,
                typeId=?, 
                locationCode=?, 
                price=?,
                classNumber=?,
                acquisitionDate=?,
                PONumber = ?,
                distributor = ?,
                regionCode = ?,
                districtCode = ?,
                buildingCode = ?,
                importDate=?,
                budgetCategory=?,
                vendorCatalogNumber=?

_SQL_
    $sth = $dbh->prepare($sql);
    $sth->execute(  $params->{'rid'}, 
                    $params->{'barcode'}, 
                    $params->{'copyNo'}, 
                    $params->{'available'}, 
                    $params->{'typeId'},
                    $params->{'lCode'},
                    $params->{'price'},
                    $params->{'classno'},
                    $params->{'acqDate'},
                    $params->{'PONo'},
                    $params->{'distributor'},
                    $params->{'regionCode'},
                    $params->{'districtCode'},
                    $params->{'buildingCode'}, 
                    $params->{'importDate'},
                    $params->{'budgetCategory'},
                    $params->{'vendorCatalogNo'});
    $id = $dbh->{'mysql_insertid'};
    $sth->finish;
    return $id;
}

