#!/usr/bin/perl

#use utf8;
use strict;

use Encode;
use LWP::UserAgent;
use HTTP::Request::Common;

use CGI;
use JSON;

use Opals::Context;
use Opals::Constant;

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

    eq_record_update_rname
    eq_record_addUpdate
);

use Opals::Eq_Circulation qw(

    circ_getLoanListByRid

);

use Opals::Eq_Search qw(
      
    eq_category_getList

);

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/ajax/saveRecord.tmpl',
        #reqPermission   => 'eq_record_edit',
    }
);
  
my $categoryList    = eq_category_getList($dbh);
  
    my $data     = $input->{'data'};
    my $data_perl = from_json($data,{utf8=>1});
    _saveRecord($dbh,$data_perl);
    my ($rid, $recordInfo) = eq_record_findByRId($dbh,{recordId=>$data->{'rid'}});
    my $itemList = _eq_item_findByRId($dbh, $rid);
    my $onLoanList =  circ_getLoanListByRid($dbh,$rid);

    foreach my $i(@$itemList){
        $i->{'onLoan'} = "";
        foreach my $ol (@$onLoanList){
            if ($ol->{'barcode'} eq $i->{'barcode'}){
                $i->{'onLoan'} = 'onLoan';
            }
        }
    }
    my @iListSorted = sort { $a->{'iid'} cmp $b->{'iid'} || $a->{'copyNo'} cmp $b->{'copyNo'}} @$itemList;
    my @iListSorted = ();    
    my $rec = _formatRecInfo($recordInfo,\@iListSorted);
    my $recInfo_json = to_json($rec, {pretty=>1});


    my $json = {}; 
    $template->param (
        json        =>  $recInfo_json,
    );
tmpl_write($dbh, $cgi, $cookieList, $template);


sub _saveRecord {
    
    my ($dbh,$data) = @_;
    my $rid = $data->{'rid'};
    my $rname = $data->{'name'};
    my $container = $data->{'container'};
    my @categories = $data->{'categories'};
    my $category = "";
    foreach my $c (@categories){
        foreach my $cc (@{$c}){
            if ($cc->{'selected'} eq "true"){
                $category .= ($category eq "")? "":"," ;
                $category .=  $cc->{'id'};
            }
            if ($cc->{'hasChild'} > 0){
                foreach my $ccc (@{$cc->{'children'}}){
                    if ($ccc->{'selected'} eq "true"){
                        $category .= ($category eq "")? "":"," ;
                        $category .=  $ccc->{'id'};
                    }
                }
            }
        }
    }

    eq_record_update_rname($dbh,$rid,$rname,$category,$container);
    foreach my $f (@{$data->{'fields'}}){
        my $id = $f->{'id'};
        my $val = $f->{'value'};
        my $params = {rid=>$rid, fId=>$id, fValue=>$val};
        eq_record_addUpdate($dbh, $params);
    }
}

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'} = "false";
        foreach my $t (@tmp){
            if ($t == $i->{'id'}){
                $i->{'selected'} ="true";
            }
        }
        foreach my $k (@{$i->{'children'}}){
            $k->{'selected'} = "false";
            foreach my $t (@tmp){
                if ($t == $k->{'id'}){
                    $k->{'selected'} ="true";
                }
            }
        }
    }
    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'  && showOnRecBrief = '1'";

    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;
}

