<?php
//共通
require_once '../../base/common.php';

/**
 * af502x共通カスタム関数
 */

/*得意先名、店舗名取得 */
function getSpnm($dbutil, $data) {
  $valutil = new getValueUtil();
  $ret03 = $valutil->allMastData("0","afm03",$data["cucd"]);
  $ret032 = $valutil->allMastData("0","afm032",$data["cuscd"],$data["cucd"]);
  $ret_array = array(
    "cunm" => $ret03["cunm"],
    "spnm" => $ret032["spnm"],
  );
  return $ret_array;
}
//CSV取込み実行
//$header:
//  wseq : 取込み時指定
//返り値：各種情報 ret : OK=true, NG=false
function doGetCsv($dbutil, $header) {
  global $stringUtil;
$logger = new logger(basename(__FILE__));
$logger->info("===doGetCsv_start===",$header);

  $valutil = new getValueUtil();
  $csvutil = new csvUtil();

	$ret_array = array(
    "wseq" => "",
    "smode" => "", //0:未処理, 1:チェック実行, 2:チェック正常終了で取込実行
    "lcnt1" => "",
    "lcnt2" => "",
    "lcnt3" => "",
    "lcnt4" => "",
    "ret" => "0",
		"msg" => "",
    "retwseq" => ""
	);

  try {
    //ヘッダー情報
    $kbn = $header["kbn"];
    $cucd = $header["cucd"];
    $cuscd = $header["cuscd"];

    //afm90より読み込み情報取得
    $sql = file_get_contents("./sql/search90.sql");
    $delParams = array();
    $delParams["scls1"] = $kbn;
    $result = $dbutil->selectNoCount($sql, $delParams);
    if ($result == null) {
      $w_firstline = 1; //1行目から
      $w_lastline = 0;  //最終行読み飛ばしなし
    } else {
      $w_firstline = $result[0]["first_line"];
      $w_lastline = $result[0]["last_line"];
    }

$logger->info('first_line='.$w_firstline.', lastline='.$w_lastline);

    $tblid = 'AF502X'.$kbn;
    $uniq_file_name = "/var/tmp/".$header["file_name"];

    //読み込み
    $wseq = $dbutil->nextVal("innerwseq");  //csv用
    $ret_array["wseq"] = $wseq;

    $ret_array['smode'] = '0'; //未処理

    //CSV取込み ---------------------------
    // ファイルが読み込み可能か？
    if (is_readable($uniq_file_name)) {
      $csv = file($uniq_file_name);
      $idx = 0;
      //impcsvInsert
  		foreach ($csv as $key => $val) {
        $idx++;

        $text = str_replace("\r\n", '', $val);
        if($idx >= $w_firstline) {  //読み込み開始行
          if (!$stringUtil->isEmpty($text)) {
            $ret_ins = $csvutil->insertIMPCSV($dbutil, $wseq, '0', $tblid, $idx, $text);
//$logger->info($wseq.':'.$idx.':'.$tblid,$ret_ins);
          }
        }
  		}
      //最終行読み飛ばし
      if ($w_lastline == "1") {
        $sql = file_get_contents("./sql/delete.sql");
        $delParams = array();
        $delParams["wseq"] = $wseq;
        $delParams["tbl_id"] = $tblid;
        $delParams["idx"] = $idx;
        $result = $dbutil->delete($sql, $delParams);
      }
      $dbutil->commit();
$sql = "select count(*) cnt from impcsv where wseq=".$wseq;
$ret_cnt = $dbutil->select($sql);

$logger->info('insert ok wseq='.$wseq.':'.$ret_cnt[0]["cnt"].'件');

      if ($idx > 1) { //データあり
        $ret_array['smode'] = '1'; //チェック済
        //PL/SQL チェック Call
        $whereParams['wseq']['in'] = $wseq;
        $whereParams['tblid']['in'] = $tblid;
        $whereParams['kbn']['in'] = $kbn;
        $whereParams['cucd']['in'] = $cucd;
        $whereParams['cuscd']['in'] = $cuscd;
        $whereParams['ktktcd']['in'] = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["LGKTKTCD"];
        $whereParams['chgcd']['in'] = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["CHGCD"];
        $whereParams['ret']['out'] = '';
$logger->info("where>>>",$whereParams);
        $sql = file_get_contents("./sql/callCheckCsv.sql");
$logger->info("01>>".$sql);
        $arry_inf = $dbutil->call($sql, $whereParams);
        $w_ret = $arry_inf["ret"];
$logger->info('01_res>>', $arry_inf);
        if ($stringUtil->isEmpty($w_ret) || $w_ret == -1 || $w_ret == -9) {
          if ($w_ret == -1) {
            $ret_array['ret'] = '-1'; //ロックエラー
            throw new userException($tblid, "ロックエラー",$whereParams);
          } else {
            $ret_array['ret'] = '99'; //エラー
            throw new userException($tblid, "エラー：その他のエラー(-99)",$whereParams);
          }
        } else {
          if ($w_ret != '0') {
            $ret_array['ret'] = '1'; //エラーあり
          }
          //結果取得
          $result = $valutil->getCntImpcsv($wseq);
          $ret_array['lcnt1'] = $result['cnt1'];  //総件数
          $ret_array['lcnt2'] = $result['cnt2'];  //正常
          $ret_array['lcnt3'] = $result['cnt3'];  //ワーニング
          $ret_array['lcnt4'] = $result['cnt4'];  //ERR
        }
      } else {
        $ret_array['ret'] = '9'; //エラー
      }
    } else {  //取込みデータなし
      $ret_array['ret'] = '9'; //エラー
    }

$sql = "select count(*) cnt from impcsv where wseq=".$wseq;
$ret_cnt2 = $dbutil->select($sql);

$logger->info('check ok wseq='.$wseq.':'.$ret_cnt2[0]["cnt"].'件');

    if($ret_array['ret'] == '0') { //チェック正常終了
      $ret_array['smode'] = '2'; //取込み済
      //PL/SQL 登録 Call
      $whereParams['wseq']['in'] = $wseq;
      $whereParams['tblid']['in'] = $tblid;
      $whereParams['kbn']['in'] = $kbn;
      $whereParams['cucd']['in'] = $cucd;
      $whereParams['cuscd']['in'] = $cuscd;
      $whereParams['ktktcd']['in'] = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["LGKTKTCD"];
      $whereParams['chgcd']['in'] = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["CHGCD"];
      $whereParams['ret']['out'] = '';
      $sql = file_get_contents("./sql/callRegCsv.sql");
$logger->info($sql);
$logger->info("where>>>",$whereParams);
      $arry_inf2 = array();
      $arry_inf2 = $dbutil->call($sql, $whereParams);
      $ret_array["ret"] = $arry_inf2["ret"];
$logger->info('02_res>>', $arry_inf2);
      if ($ret_array["ret"] != "0") {
        if ($ret_array["ret"] == "-1") {
          $ret_array['ret'] = '99'; //エラー
          throw new userException($tblid, "エラー：ロックエラー",$whereParams);
        } elseif ($ret_array["ret"] == "-2") {
          $ret_array['ret'] = '99'; //エラー
          throw new userException($tblid, "エラー：在庫引当エラー",$whereParams);
        } else {
          $ret_array['ret'] = '99'; //エラー
          throw new userException($tblid, "エラー：その他のエラー(-99)",$whereParams);
        }
      }
      //結果取得
      $result = $valutil->getCntImpcsv($wseq);
      $ret_array['lcnt1'] = $result['cnt1'];
      $ret_array['lcnt2'] = $result['cnt2'];
      $ret_array['lcnt3'] = $result['cnt3'];
      $ret_array['lcnt4'] = $result['cnt4'];
    }

$sql = "select count(*) cnt from impcsv where wseq=".$wseq;
$ret_cnt3 = $dbutil->select($sql);

$logger->info('insert ok wseq='.$wseq.':'.$ret_cnt3[0]["cnt"].'件');


  Dsp_ErrData:
  } catch(userException $ue) {
    $ret_array['ret'] = '99'; //エラー
    $ret_array['msg'] = $ue->getErrorMessage(); //エラー

  //  $dbutil->rollback();

  } catch(Exception $e) {
    $ret_array['ret'] = '99'; //エラー
    $ret_array['msg'] = $e->getMessage(); //エラー

  //  $dbutil->rollback();

  } finally {
//    $logger->info("response", $response );
  //  print( json_encode($response) );
  }

endFunction:
	return $ret_array;
}

?>
