#!/usr/bin/perl

use strict;
use CGI;
use JSON;
use Storable qw (dclone);

use Opals::Context;
use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_rangedPageList
    tmpl_redirect
    tmpl_preference
);
use Opals::User qw(
    user_currentUserID
);
use Opals::Eq_SolrSearch;
use Opals::Eq_SolrIndex;

use Opals::Equipment qw(

    eq_defItem_getList
    eq_defRecord_getList
    eq_record_findByRId
    eq_item_findByRId
    eq_itemType_getList
    eq_category_getList
    eq_building_getList
);

use Opals::Eq_Circulation qw(
    
    circ_infoRecord
);

use Opals::Locale qw(
    loc_getMsgFile
    loc_write
);

use Opals::Log;
use JSON;

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/geEQ.tmpl',
    }
);

my $uIdInfo = user_currentUserID($dbh,$cgi);
my $eqItemTypeList = eq_itemType_getList($dbh);
my $categoryList = eq_category_getList($dbh);
foreach my $i (@{$categoryList}){
    $i->{'selected'} = 0;
    foreach my $k (@{$i->{'children'}}){
        $k->{'selected'} = 0;
    }
}

################################################################################
# Delete Record

################################################################################
#

my $kw          = $input->{'kw'};
my $kw1         = $input->{'kw1'};
my $kw2         = $input->{'kw2'};
my $kw3         = $input->{'kw3'};
my $sfield      = $input->{'sfield'} || 0;
my $sfield1     = $input->{'sfield1'} || 0;
my $sfield2     = $input->{'sfield2'} || 0;
my $sfield3     = $input->{'sfield3'} || 0;
my $cfield1     = $input->{'cfield1'} ;
my $cfield2     = $input->{'cfield2'} ;
my $notContain  = $input->{'notContain'} || 0;
my $sortAttr    = $input->{'sortAttr'};
my $sortOrder   = $input->{'sortOrder'};
my $buildingSel = $input->{'bldList'};
my $searchType  = $input->{'searchType'} || "simple";
my $exactmatch  = $input->{'exactmatch'} || 0;

    if (!$sortAttr){
       $input->{'sortAttr'} = $sortAttr = 'eq_name';
    }
    if (!defined $sortOrder || $sortOrder eq "") {
        $input->{'sortOrder'} = $sortOrder = 1;
    }

my $cat         = $input->{'cat'} || 0;
my $searchByCat = $input->{'searchByCat'};
my $content_log = to_json($input, {pretty=>1});
my $sortFieldList = _eq_sortField_getList();

my $pRange = 5;
#my $pSize = 10;
my $pSize = $input->{'pSize'} || 10;
my $curPage = $input->{'pNum'};
my $offset;
($curPage && $curPage >= 1) || ($curPage = 1);
$offset = ($curPage - 1) * $pSize;

$input->{'offset'} = $offset;

my $defRecList = eq_defRecord_getList($dbh);
my $defItmList = eq_defItem_getList($dbh);
my $bldFieldList = [
    {id=>'bldName',  name=>"Building Name"} ,
    {id=>'bldAddress',name=>"Building Address"} ,
    {id=>'bldCity',   name=>"Building City"} ,
    {id=>'bldState',  name=>"Building State"} ,
]; 
my $buildingList = eq_building_getList($dbh);
my $fieldHashList = def_getList($dbh);

my $building = {};

foreach my $bld (@{$buildingList}) {
    $bld->{'selected'} = 0;
    if ($bld->{'id'} eq $buildingSel){
        $bld->{'selected'} = 1;
    }
    $building->{$bld->{'id'}} = $bld->{'name'};
}


my $defList = _eq_definition_getList($dbh,$sfield);
my ($hits,$recList,$facetList)=(0,(),()); 
my $action = $input->{'actionOpt'};
if ($action eq "update"){
    #print debug "option: update \n";
}
elsif ($action eq "add"){
    #print debug "option: add \n";
}
else {
    my $rs = do_SolrSearch($input);
    ($hits,$recList,$facetList) = ($rs->{'hits'},$rs->{'recordList'},$rs->{'facetList'});
    my $recRsPos = $offset;
    my $showOnSearchFieldList = getShowOnSearchFieldList($dbh);
    my $tmpRId = 0;
    foreach my $r (@{$recList}) {
        $r->{'itemList'} = eq_item_findByRId($dbh,$r->{'rid'});
        ($tmpRId,$r->{'recordInfo'}) = eq_record_findByRId($dbh,{recordId=>$r->{'rid'}});
        $r->{'iCount'} = scalar(@{$r->{'itemList'}});
        $r->{'recRsPos'}=$recRsPos++;
    }
    my $result_json = to_json($recList, {pretty=>1});
    $template->param(
        kw              => $kw,
        kw1             => $kw1,
        kw2             => $kw2,
        kw3             => $kw3,
        pNum            => $curPage,
        sfield          => $sfield,
        sfield1         => $sfield1,
        sfield2         => $sfield2,
        sfield3         => $sfield3,
        hits            => $hits,
        recList         => $recList,
        listResult      => (scalar(@{$recList})>0)?1:0,
        hasNoResult     => ($kw ne "" && $hits <=0)?1:0,
        buildingList    => $buildingList,
        bldList         => to_json($buildingList),
        hasMultiBlds    => scalar(@{$buildingList})>0?1:0,
        sortFieldList   => $sortFieldList,
        defRecList      => $defRecList,
        defItmList      => $defItmList,
        bldFieldList    => $bldFieldList,
        cat             => $cat,
        result_json     => $result_json,
        pSize           => $pSize,
        notContain      => $notContain,
        exactMatch      => $exactmatch,
        eqItemTypeList  => $eqItemTypeList,
        itemTypeList    => to_json($eqItemTypeList,{pretty=>1}),
        categoryList    => to_json($categoryList,{pretty=>1}),
        searchType      => $searchType,
    );
}

writeSortParam2Tmpl();

my @rangedPageList = tmpl_rangedPageList($hits, $curPage, $pSize, $pRange);

my $recTo   = $offset + $pSize;
if ($recTo > $hits){
    $recTo = $hits
}

    my @defList1 =  @{dclone(\@{$defList})};
    my @defList2 =  @{dclone(\@{$defList})};
    my @defList3 =  @{dclone(\@{$defList})};
    foreach my $d (@defList1){
        if ($d->{'id'} eq $sfield1 ) {$d->{'selected'} = 1;}
    }
    foreach my $d (@defList2){
        if ($d->{'id'} eq $sfield2 ) {$d->{'selected'} = 1;}
    }
    foreach my $d (@defList3){
        if ($d->{'id'} eq  $sfield3 ) {$d->{'selected'} = 1;}
    }
    my @cfield1List = (
        {name => 'AND', value => 'and', selected=>0},
        {name => 'OR', value => 'or',   selected=>0},
        {name => 'NOT', value => 'not', selected=>0},
    );
    my @cfield2List = (
        {name => 'AND', value => 'and',selected=>0},
        {name => 'OR', value => 'or' , selected=>1},
        {name => 'NOT', value => 'not',selected=>0},
    );
    if ($input->{'cfield1'} && $input->{'cfield1'} ne "") { 
        foreach my $c(@cfield1List){
            $c->{'selected'} = 0;
            if ($input->{'cfield1'} && $input->{'cfield1'} eq $c->{'value'}){$c->{'selected'} = 1};
        }
    }
    if ($input->{'cfield2'} && $input->{'cfield2'} ne "") {
        foreach my $c(@cfield2List){
            $c->{'selected'} = 0;
            if ($input->{'cfield2'} && $input->{'cfield2'} eq $c->{'value'}){$c->{'selected'} = 1};
        }
    }
my $requestList = eq_ge_getRequestList($dbh);   
$template->param(
    defList         =>  $defList,
    fieldList       =>  to_json($defList),
    srchFieldList   =>  to_json($defList),
    defList1        =>  \@defList1,
    defList2        =>  \@defList2,
    defList3        =>  \@defList3,
    cfield1List     => \@cfield1List,
    cfield2List     => \@cfield2List,
    recFrom         =>  $offset + 1,
    recTo           =>  $recTo,
    rangedPageList  =>  \@rangedPageList,
    requestList1     => $requestList,
    requestList         => to_json($requestList),
);

my $msgValMap={} ;

my $stdMsgMap  =loc_getMsgFile('/search/standard.msg',$msgValMap);
loc_write($template,$stdMsgMap);
tmpl_write($dbh, $cgi, $cookieList, $template);

#-----------------------------------------------------------------------
sub writeSortParam2Tmpl{
    
    $template->param(
        sortOrder       => $sortOrder,
        sortAttr        => $sortAttr,
        sortDown         => ($sortOrder && $sortOrder == 1)  ? 1 : 0 ,
    );
}

sub _eq_definition_getList {

    my ($dbh,$sf) = @_;
    #my $sql = "select id,defType,name from eq_def order by name";
    #my $sth = $dbh->prepare($sql);
    #$sth->execute();
    my @retList = ();
    @retList = (
        {id=> "48", defType=>"item", name=>"Accessories", selected=>0},
        {id=> "40", defType=>"item", name=>"Assigned Person First Name", selected=>0},
        {id=> "41", defType=>"item", name=>"Assigned Person Last Name", selected=>0},
        {id=> "eq_barcode", defType=>"record",name=>"Barcode", selected=>0},
        {id=> "18", defType=>"item", name=>"Building Code", selected=>0},
        {id=> "46", defType=>"item", name=>"Cart Number", selected=>0},
        {id=> "category", defType=>"record", name=>"Category", selected=>0},
        {id=> "31", defType=>"item", name=>"Date Acquired/Assigned/Install", selected=>0},
        {id=> "26", defType=>"item", name=>"District Code", selected=>0},
        {id=> "7", defType=>"item", name=>"District inventory #", selected=>0},
        {id=> "eq_name", defType=>"record",name=>"Equipment Name", selected=>0},
        {id=> "36", defType=>"record", name=>"General Accessories Notes", selected=>0},
        {id=> "33", defType=>"record", name=>"General Notes", selected=>0},
        {id=> "43", defType=>"item", name=>"IP Address", selected=>0},
        {id=> "8", defType=>"item",name=>"Item Designation", selected=>0},
        {id=> "38", defType=>"item", name=>"Items Status Notes", selected=>0},
        {id=> "typeId", defType=>"item",name=>"Item Type", selected=>0},
        {id=> "11", defType=>"item", name=>"Location in building", selected=>0},
        {id=> "44", defType=>"item", name=>"MAC Address", selected=>0},
        {id=> "37", defType=>"item", name=>"Machine Name", selected=>0},
        {id=> "1", defType=>"record", name=>"Manufacturer", selected=>0},
        {id=> "16", defType=>"record", name=>"Manufacturer URL", selected=>0},
        {id=> "3", defType=>"record", name=>"Model", selected=>0},
        {id=> "28", defType=>"record", name=>"Online Manual", selected=>0},
        {id=> "42", defType=>"item", name=>"P.O. Number", selected=>0},
        {id=> "6", defType=>"item", name=>"Price ", selected=>0},
        {id=> "5", defType=>"item", name=>"Serial#", selected=>0},
        {id=> "47", defType=>"item", name=>"Slot Number", selected=>0 },
        {id=> "45", defType=>"item", name=>"Software Key", selected=>0 },
        {id=> "38", defType=>"item", name=>"Status", selected=>0 },
        {id=> "27", defType=>"record", name=>"Supplier URL ", selected=>0 },
        {id=> "39", defType=>"item", name=>"Vendor Name", selected=>0 },
        {id=> "14", defType=>"record", name=>"Warranty Notes", selected=>0 },
    );
    foreach my $r(@retList) {
        if ($r->{'id'} eq $sf){
            $r->{'selected'} = 1;
        }
    }
=item    
    my @list = ();
    foreach my $r(@retList) {
        if ($r->{'defType'} eq 'item'){
            push @list, $r;
        }
    }
    return \@list;
=cut
    return \@retList;
}

sub _eq_sortField_getList {

    my @retList = ();
    @retList = (
        {id=>'eq_name',name=>'Equipment Name' },
        {id=>'1',name=>'Manufacturer' },
        {id=>'3',name=>'Model' },
    );
    foreach my $s(@retList) {
        if ($s->{'id'} eq $sortAttr){
            $s->{'selected'} = 1;
        }
    }
    return \@retList;
}

sub do_SolrSearch {

    my ($input) = @_;
    
    return undef if ($input->{'kw'} eq "" && $input->{'kw1'} eq "" && $input->{'kw2'} eq "" && $input->{'kw3'} eq "");
    my $eq_solr = Opals::Eq_SolrSearch->new(dbh=>$dbh);
    my $lQuery = $eq_solr->eq_slr_buildSearchQuery($input);
    my $params={
        lQuery=>$lQuery,
        displayStyle=> 'record',
    };
    my $rs = $eq_solr->eq_slr_search($params);
    $input->{'hits'} = $rs->{'hits'};
    return $rs;
}

sub _eq_category_getList {

    my ($dbh) = @_;
    my @catList;
    my $sql = "select * from eq_category where parentId=0 order by name";
    my $sth = $dbh->prepare($sql);
    $sth->execute();
    my $subsql = "select * from eq_category where parentId=? order by name";
    my $sth_sub = $dbh->prepare($subsql);
    while ( my $rec = $sth->fetchrow_hashref){
        $sth_sub->execute($rec->{'id'});
        $rec->{'hasChild'} = 0;
        while(my $c = $sth_sub->fetchrow_hashref){
            $rec->{'hasChild'} = 1;
            push @{$rec->{'children'}}, $c;
        }
        push @catList,$rec;
    }
    $sth->finish;
    $sth_sub->finish;
    return \@catList;
}

sub getShowOnSearchFieldList {

    my ($dbh) = @_;
    my $sth = $dbh->prepare("select id,name, showOnSearch from eq_def where showOnSearch=1");
    my @list;
    $sth->execute();
    while (my $f = $sth->fetchrow_hashref()) {
        push @list, $f;
    }
    return \@list;
}

sub getSearchDisplayStyle {
    #display record type or linear (for detroit..)
    my ($dbh) = @_;
    my $sth = $dbh->prepare("select count(*) from eq_def where showOnSearch=1 && defType ='item'");
    $sth->execute();
    my $ret = $sth->fetchrow_array();
    $sth->finish;
    if (!$ret){
        return 0;
    }
    return $ret;
}

sub eq_ge_getRequestList {

    my ($dbh) = @_;
    my $sql = <<_SQL_;
select      u.username, 
            count(distinct rc.rid) as ridCount,
            count(rc.barcode) as bcCount,
            rq.* 
from        (eq_geRecord as rc inner join eq_geRequest rq using(req_id))
                inner join opl_user u on u.uid=rq.uid
group by    rq.req_id
order by    rq.reqDate desc         
_SQL_

    my $sth = $dbh->prepare($sql);
    $sth->execute();
    my @list;
    while (my $rec = $sth->fetchrow_hashref){
        #$rec->{''}$fieldHashList
        if ($rec->{'action'} eq 'update'){
            $rec->{'action'} = "Replace";
            $rec->{'aReplace'} = 1;
            $rec->{'o_codeTxt'} = $fieldHashList->{$rec->{'o_code'}}->{'name'};
        }
        elsif ($rec->{'action'} eq 'changeRecType'){
            $rec->{'action'} = "Change Item Type";
            $rec->{'aChangeRecType'} = 1;
            $rec->{'o_codeTxt'} = $fieldHashList->{$rec->{'o_code'}}->{'name'};
            $rec->{'n_codeTxt'} = $fieldHashList->{$rec->{'n_code'}}->{'name'};
        }
        elsif ($rec->{'action'} eq 'changeCategory'){
            $rec->{'action'} = "Change Record Category";
            $rec->{'aChangeRecCategory'} = 1;
            $rec->{'n_categories'} = _getCategoryName($rec->{'n_data'});
            $rec->{'o_codeTxt'} = $fieldHashList->{$rec->{'o_code'}}->{'name'};
            $rec->{'n_codeTxt'} = $fieldHashList->{$rec->{'n_code'}}->{'name'};
        }
        push @list, $rec;
    }
    $sth->finish;
    return \@list;
}

sub def_getList{

    my ($dbh) = @_;
    my @list = ();
    my $sql = "select id,defType,name from eq_def order by defType,name";
    my $sth = $dbh->prepare($sql);
    $sth->execute();
    my $ret;
    $ret->{'eq_name'} = {'id'=>'eq_name','name'=>'Equipment Name','defType'=>'record'};
    while (my $d = $sth->fetchrow_hashref){
        #push @list,$d;
        if (!$ret->{$d->{'id'}}){
            $ret->{$d->{'id'}}->{'id'} = $d->{'id'};
            $ret->{$d->{'id'}}->{'name'} = $d->{'name'};
            $ret->{$d->{'id'}}->{'defType'} = $d->{'defType'};
        }
    }
    $sth->finish;
    return $ret;
}

sub _getCategoryName {

    my ($dataStr) = @_;
    my @data = split /,/,$dataStr;
    my @categories = ();
    foreach my $d ( @data){
        foreach my $i (@{$categoryList}){
            if ($d == $i->{'id'}){
                push @categories, {
                    'name'  =>    $i->{'name'}
                }
            }
            foreach my $k (@{$i->{'children'}}){
                if ($d == $k->{'id'}){
                    push @categories, {
                        'name'   =>  $k->{'name'}
                    }
                }
            }
        }
    }
    return \@categories;
}

sub _eq_sortField_getList {

    my @retList = ();
    @retList = (
        {id=>'eq_name',name=>'Equipment Name' },
        {id=>'1',name=>'Manufacturer' },
        {id=>'3',name=>'Model' },
    );
    foreach my $s(@retList) {
        if ($s->{'id'} eq $sortAttr){
            $s->{'selected'} = 1;
        }
    }
    return \@retList;
}


