#!/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::Log;

use Time::localtime;

use Opals::Eq_SolrSearch;
use Opals::Eq_SolrIndex;

use Opals::Template qw(
    tmpl_read
    tmpl_write
);
use Opals::User qw(
    user_currentUserID
);
use Opals::Tb_Record qw(
    tb_item_findByRId
);



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        => 'txtbk/ajax/search/delExpFromHitList.tmpl',
    }
);
my $uIdInfo = user_currentUserID($dbh,$cgi);
    my $data    = $input->{'data'};
    $data  = decode_json($data);
    my $list = do_DeleteFromhitList($dbh,$data);
    $list = to_json($list,{pretty=>1}); 
    my $log = Opals::Log->new(dbh=>$dbh);
    my $params = {
        module      => "txtbk",
        uid         => $uIdInfo->{'uid'} || 0,
        sessionid   => $uIdInfo->{'sessionid'} || "",
        action      => "delete-hitlist",
        content     => $list
    };
    my $logId = $log->log($params);
    $template->param (
        logId   => $logId,
        result  => $list
    );
tmpl_write($dbh, $cgi, $cookieList, $template);


sub do_DeleteFromhitList {
    my ($dbh,$data) = @_;
    my @list=();
    my $ridList;
    my $sql = "update tb_items set available = 0, deleted = '1', 
        barcode = CONCAT('___', ? , '_', ? ) , modDate = now() where rid = ? && barcode=?";
    my $sqlItemOnLoan = "select barcode from tb_loan where barcode =? && dateReturn is NULL" ;
    my $sth = $dbh->prepare($sql);
    foreach my $d(@{$data}){
        my $onLoan = $dbh->selectrow_array($sqlItemOnLoan,undef,$d->{'barcode'});
        if (!defined $onLoan){
            if (!$ridList->{$d->{'rid'}}){
                $ridList->{$d->{'rid'}} = 1;
            }
            $sth->execute($d->{'barcode'},$d->{'rid'},$d->{'rid'}, $d->{'barcode'});
            push @list, $d;
        }
    }
    foreach my $rid (keys %$ridList){
        my $itemList = tb_item_findByRId($dbh,$rid);
        if (scalar(@$itemList)<=0){
            $dbh->do("update tb_records set deleted='1' where rid=$rid");
        }
    }
    return \@list;
}


