<?php
/**
 * 领导机构新增完成
 * $Id: government_new_result.php,v 1.1 2020/01/03 11:18:46  Exp $
 * @author lixq
 * @package manager.public_html
 */
// 底层包含
require_once("manager_include.inc");

// 登录检查
require_once("check_login.inc");

// 权限检查
if (!checkAuthority("2")) {
	// エラー表示
	$layout_pages = array();
	$layout_pages["left"] = "menu.inc";
	$layout_pages["right"] = "error.inc";
	$message = "权限不足，请联系系统管理员。";
	require_once(MANAGER_TEMPLATE_DIR_PATH . "/layout/leftmenu_layout.inc");
	exit;
}

$csv_file = FileUploadUtil::getScalarFile($_FILES["csv_file"]);
$file_type = strrchr($csv_file->name, ".");
$file_size = $csv_file->size;

$csv_error_msg = "";

if ($file_size < 1) {
  // 检查文件大小
  $csv_error_msg = "请选择CSV文件";
}else{
  
  // ファイルを読みます
  $reader = new CsvReader($csv_file->tmp_name, ",");
  $reader->parse();
  $csv_file_content = $reader->getResult();
  // コラム数チェック
  if (count($csv_file_content) < 1 || count($csv_file_content[0]) != 4) {
    ErrorLogger::doOutput("count_file_rows:" . count($csv_file_content) . "count_file_field:" . count($csv_file_content[0]), "government_new_result.php");
    $csv_error_msg = "文件出现错误，请检查";
  }else{
    foreach ($csv_file_content as $index=>$tmp) {
      if($index == 0){
        continue;
      }
      $province = trim($tmp[0]);
      if(empty($province)){
        continue;
      }
      $city = trim($tmp[1]);
      $district = trim($tmp[2]);
      $title = trim($tmp[3]);
      // check
      if (empty($title)) {
        if(empty($city) && empty($district)){
          $title = $province . "教育厅";
        }else if(!empty($city) && empty($district)){
          $title = $province . $city . "教育局";
        }else if(!empty($city) && !empty($district)){
          $title = $province . $city . $district . "教育局";
        }
      }
      $params = [];
      $params["delete_flg"] = false;
      $params["province"] = $province;
      $params["city"] = $city;
      $params["district"] = $district;
      $params["title"] = $title;
      $government_count = GovernmentMst::getListCount($params);
      if($government_count < 1){
        // DBに保存
        $government_mst = new GovernmentMst();
        $government_mst->province = $province;
        $government_mst->city = $city;
        $government_mst->district = $district;
        $government_mst->title= $title;
        $government_mst->save();
      }
    }
  }
}

if (!empty($csv_error_msg)) {
  $layout_pages = array();
  $layout_pages["left"] = "menu.inc";
  $layout_pages["right"] = "government_new.inc";
  $layout_pages["menu_clicked"] = "5-2";
  require_once(MANAGER_TEMPLATE_DIR_PATH . "/layout/leftmenu_layout.inc");
  exit;
}
// ページ
$layout_pages = array();
$layout_pages["left"] = "menu.inc";
$layout_pages["right"] = "government_new_result.inc";
$layout_pages["menu_clicked"] = "5-2";
require_once(MANAGER_TEMPLATE_DIR_PATH . "/layout/leftmenu_layout.inc");
exit;