#!/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 Time::localtime;
use Opals::Equipment qw(

    eq_record_findByRId


);
use Opals::Eq_Search qw(
      
    eq_category_getList
    eq_category_getListById

);

use Opals::Template qw(
    tmpl_read
    tmpl_write
);

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/report/getHistoryById.tmpl',
        #reqPermission   => 'eq_record_edit',
    }
);

my $categoryList    = eq_category_getList($dbh);
       
my $id = $input->{'id'};
   
    my $history = _getHistoryById($dbh);
    my $action = $history->{'action'};
    my $content = decode_json($history->{'content'});
    my $rid=0;
    my $rec;
    my $curRec;
    my $list;
    my ($changed,$deleted);
    if ($action =~ m/edit-record|edit-item/){
        $rid = $content->{'rid'};
        $curRec = to_json($content->{'rec'},{pretty=>1});
        $changed = to_json($content->{'changed'}||{},{pretty=>1});
        $list = "[]";
        $deleted = '""';
    }
    elsif ($action =~ m/delete-hitlist/){
        $list   = to_json($content,{pretty=>1});
        $curRec = '""';
        $changed= '""';
    }
    elsif ($action =~ m/delete/){
        $list   = "[]";
        $deleted = to_json(_getDeletedRecordInfo($dbh,$content->{'rid'}), {pretty=>1});
        $curRec = $changed = "[]";
    }
    else {
        $list   = "[]";
        $deleted = '""';
        $curRec = to_json($content->{'rec'},{pretty=>1});
        $changed = to_json($content->{'changed'}||{},{pretty=>1});
    }
    $template->param (
        action      => $action,
        changed     => $changed,
        deleted     => $deleted || '""',
        record      => $curRec,
        list        => $list 
    );
tmpl_write($dbh, $cgi, $cookieList, $template);


sub _getHistoryById{

    my ($dbh) = @_;
    my $sth = $dbh->prepare(<<_STH_);
select action, content
from log  
where id = $id
_STH_

    $sth->execute();
    my @list = ();
    my $rec = $sth->fetchrow_hashref();
    return $rec;
}

sub _getRecordInfo {
    
    my ($dbh,$rid) = @_;
    my ($id, $recordInfo) = eq_record_findByRId($dbh,{recordId=>$rid});
    my $itemList = _eq_item_findByRId($dbh, $rid);
    my @iListSorted = sort { $a->{'iid'} cmp $b->{'iid'} || $a->{'copyNo'} cmp $b->{'copyNo'}} @$itemList;
    $rec = _formatRecInfo($recordInfo,\@iListSorted);
    return $rec;
}
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;
}
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 _getDeletedRecordInfo {

    my ($dbh,$rid) = @_;
    return if (!$rid || $rid eq '');
    my @recordInfo =();
    my $sth = $dbh->prepare(<<_SQL_);
SELECT  r.rid, r.rname,r.category,r.container, 
        d.id as dId,d.name as defName, d.description as defDescription,
        rf.fId, rf.fValue as fValue
FROM    eq_records as r 
        LEFT JOIN eq_recordFieldsArchive as rf ON r.rid = rf.rid 
        RIGHT JOIN eq_def as d ON rf.fId = d.id && r.rid = ?
WHERE   d.defType = 'record'  && rf.fValue is not null order by d.fOrder
_SQL_

    $sth->execute($rid);
    while (my $rec = $sth->fetchrow_hashref){
        push @recordInfo, {
            category    => $rec->{'category'}? $rec->{'category'}: "",
            categoryStr => $rec->{'category'}? _eq_categoryNameById($dbh,$rec->{'category'}): "",
            container   => $rec->{'container'},
            rid         => $rec->{'rid'},
            rname       => $rec->{'rname'},
            name        => $rec->{'defName'},
            value      => $rec->{'fValue'},
            fId         => ($rec->{'fId'})?$rec->{'fId'}:$rec->{'id'},
        };
    }
    $sth = $dbh->prepare("select iid, barcode,typeId,copyNo,r.container from eq_items i inner join eq_records r using(rid) where rid=? && i.barcode regexp '^\_\_\_' && i.deleted='1'");
    my $sqlItems = <<_SQLItems_;
SELECT  d.name, i.sfId, i.sfValue                  
FROM    eq_def as d
        LEFT OUTER JOIN eq_fieldDataType fdt on d.fieldType=fdt.id                 
        LEFT OUTER JOIN eq_itemFieldsArchive as i on i.sfId = d.id && i.rid = ? && i.iid = ?
        WHERE   d.defType = 'item' order by i.id
_SQLItems_
     
    my $sth_item = $dbh->prepare($sqlItems);
    my @itemList;
    $sth->execute($rid);
    while (my ($iid,$barcode,$typeId,$copyNo,$createdDate,$container) = $sth->fetchrow_array()){
        $sth_item->execute($rid, $iid);
        my @fields;
        while(my $f = $sth_item->fetchrow_hashref()){
            push @fields, {
                id              => ($f->{'sfId'})? $f->{sfId}:$f->{'id'},
                value           => $f->{'sfValue'}, 
                name            => $f->{'name'},
            };
       }
       
       $barcode =~ s/^___//;
       $barcode =~ s/[_]$rid$//;
       push @itemList, {
            iid     => $iid,
            barcode => $barcode,
            typeId  => $typeId,
            copyNo  => $copyNo,
            cDate   => $createdDate,
            container=>$container, 
            fields  => \@fields
       };
    }

    my $record = {
        rid         => $recordInfo[0]->{'rid'},
        name       => $recordInfo[0]->{'rname'},
        categoryStr => $recordInfo[0]->{'categoryStr'},
        fields      => \@recordInfo,
        items       => \@itemList
    };
    $sth->finish;
    return $record;
}

sub _eq_categoryNameById {

    my ($dbh,$catIds) = @_;
    my $sth = $dbh->prepare("select name from eq_category where id in ( $catIds )");
    my $catNameStr = "";
    $sth->execute();
    while (my $name = $sth->fetchrow_array()) {
        $catNameStr .= ($catNameStr eq "")? $name : ", " . $name ;
    }
    return $catNameStr;
}

