#!/usr/bin/perl

use strict;
use CGI;
use Time::localtime;
use JSON;

use Opals::Context;
use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_preference
);

use Opals::Equipment qw(
    eq_itemType_getList
		eq_authCtrlFields_getListByFCode
    eq_getAccessoryListByTypeId
);


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


my $cgi = CGI->new;
my $input = $cgi->Vars();
my ($permission, $cookie, $template) = tmpl_read(
    {
        dbh             => $dbh,
        cgi             => $cgi,
        tmplFile        => 'eqmnt/util/itemAccsMgmt.tmpl',
    }
);
   
my $accCode=48;
my $itemTypeList = eq_itemType_getList($dbh);
my $accessoryList= eq_authCtrlFields_getListByFCode($dbh,$accCode);
my $accessoryListByTypeId = getAccessoryListByTypeId($dbh);

getCountByItemType($dbh);
my $bcList = getBarcodeList($dbh);
$template->param(
  itemTypeList	=> to_json($itemTypeList,{pretty=>1}),
	accessoryList	=> (defined $accessoryList)?to_json($accessoryList):'[]',
	accessoryListByTypeId	=> (defined $accessoryListByTypeId)?to_json($accessoryListByTypeId):'[]',
  bcList        => to_json($bcList)
);

tmpl_write($dbh, $cgi, $cookie, $template);

sub getAccessoryListByTypeId {
  my ($dbh ) = @_;
  my $sql ="select typeId as type, group_concat(accessory) as accs from eq_accsMgmt group by type";
	my $sth = $dbh->prepare($sql);
	$sth->execute();
	my $ret = undef;
  my $defaultAccsList = getDefaultValue($dbh);
  while (my $rec = $sth->fetchrow_hashref()){
    my @tmpAccs = split(',', $rec->{'accs'});
    my $list;
    foreach my $l (@$accessoryList) {
      my $selected=0;
      if (index($rec->{'accs'},$l) != -1){
        $selected=1;
      }
      push @$list,{
        "name" => $l,
        "selected"  => $selected,
        "isSelected"=> $selected
      };
    };
    $ret->{$rec->{'type'}} = $list;
    foreach my $k (keys $defaultAccsList){
      if (!$ret->{$k}){
        $ret->{$k} = $defaultAccsList->{$k};
      }
    }
  }
  return (defined $ret)?$ret:$defaultAccsList;
}

sub getDefaultValue {
  my ($dbh)=@_;
  my $list;
  foreach my $l(@$accessoryList){
    push @$list, {
      "name" => $l,
      "isSelected" => 0,
      "selected" => 0
    }
  };
  my $ret;
  foreach my $i(@$itemTypeList){
    if (!$ret->{$i->{'id'}}){
      $ret->{$i->{'id'}} = $list;
    }
  }
  return $ret;
}

sub getCountByItemType {
  my ($dbh)=@_;
  my $sql="select count(*) from eq_items where typeId=? && deleted='0'";
  my @bind_values=();
  foreach my $t (@$itemTypeList){
    @bind_values=();
    push @bind_values,$t->{'id'};
    $t->{'count'} = $dbh->selectrow_array($sql, undef, @bind_values);
  }
}

sub getBarcodeList{
    my ($dbh,$rid) = @_;
    my @barcodeList = ();
    my $sql = "select r.rname as name, i.* from eq_items i inner join eq_records r using(rid) where r.deleted='0' && i.deleted='0' && i.barcode not regexp '^\_\_\_'";
    if (defined $rid && $rid>0) {
        $sql .= '&& rid = ' . $rid ;
    }
    my $sth = $dbh->prepare($sql);
    $sth->execute();
    my $acs=[];
    while (my $f = $sth->fetchrow_hashref()){
      $acs = getAccessoryList($dbh,$f->{'barcode'});
      push @barcodeList, { 
        name    => $f->{'name'},
        id      => $f->{'id'},
        rid     => $f->{'rid'},
        iid     => $f->{'iid'},
        barcode => $f->{'barcode'},
        copyNo  => $f->{'copyNo'},
        typeId  => $f->{'typeId'},
        accessoryList=>$acs,
        curAccessoryList=>$acs,
        selected => 1,
        changed   => 0
      };
    }
    $sth->finish;
    return \@barcodeList;
}

sub getAccessoryList {

  my ($dbh,$barcode) = @_;
  my $sql= "select accessory from eq_itemAccessory where barcode=? && status=1";
  my @values = ();
  push @values,$barcode;
  my $ret = $dbh->selectcol_arrayref($sql,{},@values );

  return $ret;

}
