#!/usr/bin/perl

use strict;
use CGI;
use JSON;

use Opals::Context;

use Opals::Template qw(
    tmpl_read
    tmpl_write
);

use Opals::Log;

use Opals::User qw(
    user_currentUserID
);

use Opals::Equipment qw(

    eq_defItem_getList
    eq_defRecord_getList

    eq_record_findByRId
    eq_record_addUpdate
    eq_record_update_rname
    
    eq_item_findByRId
    eq_item_addUpdateBarCodeItemType
    eq_item_addUpdate

    eq_item_delete
    eq_item_deleteSubFields
    eq_item_deleteBarcode

    eq_authCtrlFields_getList
    eq_containerFields_getList

    eq_isBarcodeExist
    eq_itemType_getList
    eq_categoryMapList

    eq_getSchoolList
    eq_category_getList

);


use Opals::Eq_Circulation qw(

    circ_getLoanListByRid

);
use Opals::Eq_BarcodeMgmt qw(
    eq_bcm_getVendorList
    eq_bcm_getBiggestBcFromDB
    eq_bcm_createNextBiggestBc
);


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

my $cgi = CGI->new;
my $input = $cgi->Vars();
my ($permission, $cookieList, $template) = tmpl_read(
    {
        dbh             => $dbh,
        cgi             => $cgi,
        tmplFile        => 'eqmnt/record/edit.tmpl',
    }
);

my $uIdInfo = user_currentUserID($dbh,$cgi);

my $rid     = $input->{'rid'} ;
my $edit    = $input->{'edit'};
my $op      = $input->{'op'};
    $op = "edit" if (!$op ||$op eq "");
my $kw       = $input->{'kw'};
my $sfield   = $input->{'sfield'};
my $sortOrder= $input->{'sortOrder'};
my $sortAttr = $input->{'sortAttr'};
my $pNum     = $input->{'pNum'};

my $recRsPos     = $input->{'recRsPos'};
open debug, ">/tmp/debugK";

my $recordInfo = [];
my $itemList = [];
my ($rFieldList,$iFieldList);
my $eqItemTypeList  = eq_itemType_getList($dbh);
my $vendorList = eq_bcm_getVendorList($dbh);
my $biggestBc = eq_bcm_getBiggestBcFromDB($dbh);
my $nextBiggestBc = eq_bcm_createNextBiggestBc($dbh,$biggestBc);
my $authCtrlFields  = eq_authCtrlFields_getList($dbh);
print debug "barcode:$biggestBc \t nextBiggestBc:$nextBiggestBc \n";
my $containerFields = eq_containerFields_getList($dbh);
my $schoolList      = eq_getSchoolList($dbh);

my $categoryList    = eq_category_getList($dbh);
my $categoryMapList = eq_categoryMapList($dbh);
my $libCode         = $template->param('libcode');
my $authCtrlFieldsList = _authCtrlFields_getList($dbh);
close debug;
my $acList;
foreach my $ac (@{$authCtrlFieldsList}){
    $acList->{$ac->{'fId'}} = $ac->{'list'};
}

if (!$schoolList || scalar(@$schoolList)<=0){
    $schoolList = {
        "id"    => 1,
        "code"  => $libCode
    };

};
    my $recInfo_json;
    my $itemType_json;

    if ($rid && $rid > 0){
        my $max_iid=0;
        my $iCount = 0;
        ($rid, $recordInfo) = eq_record_findByRId($dbh,{recordId=>$rid});
        $itemList = _eq_item_findByRId($dbh, $rid);
        my $onLoanList =  circ_getLoanListByRid($dbh,$rid);
        foreach my $i(@$itemList){
            $iCount++;
            $i->{'onLoan'} = "";
            $max_iid=$i->{'iid'} if($i->{'iid'}>$max_iid);
            foreach my $ol (@$onLoanList){
                if ($ol->{'barcode'} eq $i->{'barcode'}){
                    $i->{'onLoan'} = 'true';
                }
            }
        }
        my @iListSorted = sort { $a->{'iid'} cmp $b->{'iid'} || $a->{'copyNo'} cmp $b->{'copyNo'}} @$itemList;
        my $rec = _formatRecInfo($recordInfo,\@iListSorted);
        $recInfo_json = to_json($rec, {pretty=>1});
    }
    my $itemType_json = to_json($eqItemTypeList,{pretty=>1});
    my $schoolList_json = to_json($schoolList,{pretty=>1});
    my $acList_json = "{}";
    if (defined $acList && $acList) {
        $acList_json = to_json($acList,{pretty=>1});
    }
    my $authCtrlFields_json = to_json($authCtrlFields,{pretty=>1});
    my $itemTemplate_json = to_json(getEmptyItemTemplate($dbh),{pretty=>1});
    my $itemNewTemplate_json = to_json(getItemNewTemplate($dbh),{pretty=>1});
    my $recordEmptyTemplate_json = to_json(getEmptyRecordTemplate($dbh),{pretty=>1});
    $template->param(
        rid                 =>  $rid,
        recInfo_json        => (defined $rid && $rid>0)?$recInfo_json:$recordEmptyTemplate_json,
        #recInfo_json        =>  $recordEmptyTemplate_json,
        itemType_json       =>  $itemType_json,
        itemTemplate_json   =>  $itemTemplate_json,
        itemNewTemplate_json=>  $itemNewTemplate_json,
        authCtrlFields_json =>  $authCtrlFields_json,
        acList_json         =>  $acList_json,
        schoolList_json     =>  $schoolList_json,
        authCtrlFields      =>  $authCtrlFields,
        http_referer        =>  $ENV{'HTTP_REFERER'},
        vendorList          => to_json($vendorList,,{pretty=>1}),
        nextBiggestBc      =>   $nextBiggestBc,
    );
        my $log = Opals::Log->new(dbh=>$dbh);
        my $content_log = to_json($input);
        my $params = {
            module      => "eqmnt",
            uid         => $uIdInfo->{'uid'} || 0,
            sessionid   => $uIdInfo->{'sessionid'} || "",
            action      => "edit",
            content     => $recInfo_json
        };
        #$log->log($params);
tmpl_write($dbh, $cgi, $cookieList, $template);


sub _formatRecInfo {
    my ($rec,$items) = @_;
    my $ret;
    my @fields=();
    my $i=0;
    foreach my $r (@{$rec}){
        if (! $i || $i > 1){
            $ret->{'rid'}   = $r->{'rid'};
            $ret->{'name'}  = $r->{'rname'};
            $ret->{'container'} = ($r->{'container'})? $r->{'container'}:"";
            $ret->{'category'}= $r->{'category'};
            $ret->{'categoryStr'}= $r->{'categoryStr'};
        }
        push @fields, {
            name    => $r->{'name'},
            id      => $r->{'fId'},
            value   => $r->{'fValue'},
        }
    }
    my @tmp = split(',', $ret->{'category'});
    foreach my $i (@{$categoryList}){
        $i->{'selected'} = 0;
        foreach my $t (@tmp){
            if ($t == $i->{'id'}){
                $i->{'selected'} = 1;
            }
        }
        foreach my $k (@{$i->{'children'}}){
            $k->{'selected'} = 0;
            foreach my $t (@tmp){
                if ($t == $k->{'id'}){
                    $k->{'selected'} = 1;
                }
            }
        }
    }
    my @sorted = sort { $a->{'name'} cmp $b->{'name'}} @fields;
    $ret->{'categories'} = $categoryList;
    $ret->{'fields'} = \@sorted;
    $ret->{'items'} = $items;
    return $ret;
}

sub _eq_item_findByRId{
    
    my ($dbh, $recordId)=@_;
    return undef if ($recordId eq '');
    my $sth = $dbh->prepare("select iid, barcode,typeId,copyNo,i.createdDate,r.container from eq_items i inner join eq_records r using(rid) where rid=? && i.barcode not regexp '^\_\_\_'");
    my $sql = " SELECT  d.*, fdt.dataType, fdt.maxVal, i.id as i_iid, i.rid, i.sfId, i.sfValue 
                FROM    eq_def as d 
                LEFT OUTER JOIN eq_fieldDataType fdt on d.fieldType=fdt.id
                LEFT OUTER JOIN eq_itemFields as i on i.sfId = d.id && i.rid = ? && i.iid = ? 
                WHERE   d.defType = 'item'  ";
    my $sth_item = $dbh->prepare($sql);
    $sth->execute($recordId);
    my @itemList =();
    my $i=0;
    while (my ($iid,$barcode,$typeId,$copyNo,$createdDate,$container) = $sth->fetchrow_array()){
       $sth_item->execute($recordId, $iid);
       my @fields;
       my $fCount = 0;
       while(my $f = $sth_item->fetchrow_hashref()){
            push @fields, {
                id              => ($f->{'sfId'})? $f->{sfId}:$f->{'id'},
                value           => $f->{'sfValue'}, 
                name            => $f->{'name'},
                url_link        => ($f->{'fieldType'} eq '2')?1:0,
                fieldType       => $f->{'fieldType'},
                dataType        => lc($f->{'dataType'}) || "text",
                fieldSize       => $f->{'fieldSize'} || 10,
                showOnRecBrief  => $f->{'showOnRecBrief'},
            };
            if ($f->{'display'}){
                $fCount++;
            }
       }
       push @itemList, {
            rid     => $recordId,
            iid     => $iid,
            barcode => $barcode,
            typeId  => $typeId,
            copyNo  => $copyNo,
            cDate   => $createdDate,
            container=>$container, 
            fields  => \@fields
       };
       $i++;
    }
    $sth->finish;
    $sth_item->finish;
    return \@itemList;
}

sub getEmptyRecordTemplate {
    my $sql = <<_SQL_;
select d.id, "" as value, d.name, d.fOrder from eq_def d left outer join eq_fieldDataType dt on(d.fieldType=dt.id) 
where defType='record' order by d.name
_SQL_
    my $sth = $dbh->prepare($sql);
    my $fields = $dbh->selectall_arrayref($sql,{Slice=>{}} ,());

    my $recordTemplate = {
        rid         => "",
        name        => "",
        container   => "",
        categories  => $categoryList,
        fields      => $fields
    };
    return $recordTemplate;

}

sub getEmptyItemTemplate {

    my ($dbh)=@_;

    my $sql = <<_SQL_;
select d.id, "" as value, d.name, "" as url, d.fieldType, dt.dataType, d.fieldSize, "" as acList
from eq_def d inner join eq_fieldDataType dt on(d.fieldType=dt.id) 
where defType='item' order by d.id;
_SQL_
    my $sth = $dbh->prepare($sql);
    my $fields = $dbh->selectall_arrayref($sql,{Slice=>{}} ,());
    foreach my $f(@{$fields}){

    }
    my $itemTemplate = {
        rid => "",
        iid => "",
        barcode => "",
        copyNo  => "",
        typeId  => "",
        fields  => $fields
    };
    return $itemTemplate;
}

sub getItemNewTemplate {

    my ($dbh)=@_;
    my $sql = <<_SQL_;
select d.id, d.name, d.fieldSize, d.fieldType,d.textType, dt.dataType, dt.maxVal, "" as value, "" as acList
from eq_def d left outer join eq_fieldDataType dt on(d.fieldType=dt.id) 
where defType='item' order by d.id
_SQL_
    
    my $sth = $dbh->prepare($sql);
    my $fields = $dbh->selectall_arrayref($sql,{Slice=>{}} ,());
    my $item_tmp;
    my $item_val;
    if (scalar(@$itemList) > 0){
        $item_tmp = $itemList->[0]{'fields'};
    }
    foreach  my $v (@$item_tmp){
        $item_val->{$v->{'id'}} = $v->{'value'};
    }
    foreach my $f(@{$fields}){
        $f->{'acList'} =  $acList->{$f->{'id'}} || [];
        $f->{'value'} = $item_val->{$f->{'id'}} || "";
    }
    my $itemTemplate = {
        rid => $rid,
        startBarcode => "",
        nOfItems => "1",
        copyNo  => "",
        typeId  => $itemList->[0]{'typeId'} || "",
        fields  => $fields
    };
    return $itemTemplate;
}

sub _authCtrlFields_getList{

    my ($dbh) = @_;
    my $sth = $dbh->prepare(<<_STH_);
select ac.name as name,ac.fCode as fId, trim(ac.fData) as fVal,ed.defType,ed.fieldType,fdt.dataType from eq_authCtrl ac inner join eq_def ed on ac.fCode=ed.id left outer join eq_fieldDataType fdt on ed.fieldType=fdt.id  order by defType,fCode,fVal
_STH_
    $sth->execute();
    my $tmp;
    my $retVal = [];
    while (my $rec = $sth->fetchrow_hashref()){
        if (!$tmp->{$rec->{'fId'}}){
            $tmp->{$rec->{'fId'}}->{'fId'} = $rec->{'fId'};
            $tmp->{$rec->{'fId'}}->{'name'} = $rec->{'name'};
            $tmp->{$rec->{'fId'}}->{'type'} = $rec->{'defType'};
            $tmp->{$rec->{'fId'}}->{'fieldType'} = $rec->{'dataType'};
            $tmp->{$rec->{'fId'}}->{'checkboxList'} = ($rec->{'dataType'} eq 'CheckboxList')?1:0;
        }
        push @{$tmp->{$rec->{'fId'}}->{'list'}}, $rec->{'fVal'};
    }

    foreach my $fId (sort keys %{$tmp}) {
        push @$retVal, $tmp->{$fId};
    }
    return $retVal;
}


