#!/usr/bin/perl

#use utf8;
#use strict;

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

use CGI;
use JSON;
use Digest::SHA qw(
    sha512_base64
);

use Opals::Context;
use Opals::Constant;
use Opals::Log;
use Opals::Eq_SolrIndex;
use Opals::Eq_GlobalEditor;


use Opals::User qw(
    user_currentUserID
);
use Opals::Session qw(
    SessionHdl_clearVar
);

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

my $cgi = CGI->new;
my $ret;


if ($ENV{'REQUEST_METHOD'} eq "POST") {
  my $input = decode_json($cgi->param('POSTDATA'));
  open debug, ">/tmp/EQ";
  print debug "input: ", to_json($input,{pretty=>1}), "\n";
  print debug "action :", $input->{'action'}, "\n";
  saveDataIntoTbl($dbh,$input);
=item 
  if ($input->{'action'} eq "setItemConsumable"){
    my $ge = Opals::Eq_GlobalEditor->new(dbh=>$dbh);
    $ge->eq_ge_process();
  }
=cut  
  $ret->{'status'}=1;
  close debug;
}

print "Content-type: application/json\n\n";
print to_json($ret,{pretty=>1});



sub saveDataIntoTbl {
    my ($dbh,$params) = @_;
    my $sessionID = $cgi->cookie('globalSessionID');
    my $loginUId    = $uIdInfo->{'uid'} || 0;
    my $action = $params->{'action'};
    my $field =  $params->{'field'};
    my $o_data = $params->{'o_data'};
    my $n_data = $params->{'n_data'};
    my $o_code = $params->{'o_code'} || "";
    my $n_code = $params->{'n_code'} || "";
    my $ssVarName = $params->{'ssVarName'};
    my $status = "waiting";
    if ($action eq "update"){
        $o_code = $field;
        $n_code = $field;
    }
    my $digest    = sha512_base64(time . rand(time));
 
    my $sth = $dbh->prepare(<<_STH_);
select count(*) as count from opl_sessionVar where ssid=? && var='$ssVarName'
_STH_
    $sth->execute($sessionID);
    my ($c) =$sth->fetchrow_array;
    if(!$c || $c==0){
        return TRUE;
    }
    $sth = $dbh->prepare(<<_STH_);
insert into eq_geRequest (digest,uid, o_code, n_code, o_data, n_data, reqDate, action,status) 
values (?,?,?,?,?,?,now(),?,?)
_STH_
    $sth->execute($digest,$loginUId,$o_code,$n_code,$o_data,$n_data,$action,$status) || return FALSE;
    $sth->finish;
    
    my $newReqid;
    $sth = $dbh->prepare(<<_STH_);
select req_id from eq_geRequest
where digest=?
_STH_
    $sth->execute($digest) || return FALSE;
    ($newReqid) = $sth->fetchrow_array;
    $sth->finish;

    $sth = $dbh->prepare(<<_STH_);
insert into eq_geRecord (req_id ,rid,barcode) 
select distinct $newReqid, rid,barcode from opl_sessionVar 
where ssid=? && var='$ssVarName'
_STH_
    $sth->execute($sessionID) || return FALSE;
    $sth->finish;
     # ===== clear selected from session ======
    SessionHdl_clearVar($dbh,$sessionID,$ssVarName);


    if ($params->{'action'} eq "setItemConsumable"){
      my $ge = Opals::Eq_GlobalEditor->new(dbh=>$dbh);
      $ge->eq_ge_process();
    }

    return TRUE;
}


sub eq_ge_process {
    
    my ($dbh) = @_;
    my $sth = $dbh->prepare(<<_SQL_);
select * 
from    eq_geRequest 
where   status in ('waiting','processing') order by req_id
_SQL_

    my $sth_rid = $dbh->prepare(<<_SQL_);
select * 
from    eq_geRecord
where req_id = ? && status='waiting'
_SQL_
    
    $sth->execute();
    my ($req_id,$action);
    while (my $request = $sth->fetchrow_hashref){
        $req_id = $request->{'req_id'};
        $action = $request->{'action'};
        $sth_rid->execute($request->{'req_id'});
        my $record;
        while (my $rec = $sth_rid->fetchrow_hashref){
            push @{$record->{$rec->{'rid'}}};
        }
    }
}


