// JavaScript Document
var USB_EMPLOYEE_IMPORT_MODE = 2;
var NORMAL_EMPLOYEE_IMPORT_MODE = 1;  
var EVENT_HEADER_MODE = 2; 
var EMPLOYEE_HEADER_MODE = 1;
var IS_IMPORT_FACE_BY_USB = false;//用usb导入人员时，是否导入人脸:导入：true,不导入：false
function getConfirmImportEditItems(sheetSelectData,szPathFile,oMode)
{
	var tab = document.createElement('table'); 
	tab.style.cssText = "color:#000;line-height:18px;";  	
	tab.cellPadding = "0";
	tab.cellSpacing = "0";
	tab.border = "0";
	tab.width = "100%";
	tab.id = "tab_import_excel";
	var row = tab.insertRow();
	var cell = row.insertCell();
	cell.style.cssText = "padding:0px;padding-left:6px;height:46px;width:140px;";
	
	cell.innerHTML = getLanTextByKey("T_IMPORT_PLS_TIPS");
	cell = row.insertCell();
	var maxSheetSelectWidth = getMaxWidthStringByJson(sheetSelectData,"",1.6);
	//{id:"select_dept",title:getLanTextByKey("T_DEPARTMENT"),placeholder:"",json:{obj:getEasyUISelectMenu("select_dept",maxSelectWidth),data:g_deptObj,mode:UI_MODE_SELECT,default:(g_nDepartmentID == 0 | g_nDepartmentID == -1)?-1:g_nDepartmentID}}
	var obj = new Object();
	obj.mode = VAR_MODE_UIOBJ;
	obj["data"] = sheetSelectData;
	obj["szPathFile"] = szPathFile;
	tab.szPathFile = szPathFile;
	obj["obj"] = getEasyUISelectMenu("select_sheets",maxSheetSelectWidth,"onChangeSheetInfo");
	cell.appendChild(obj["obj"]);
	//setUItoCellByEasyUI(obj,cell,100);
	setSelectUItoCellByEasyUI(obj,cell);
	tab.hideContent = obj;
	//cell.innerHTML = getLanTextByKey("T_EXPORT_CURRENT_PAGE_TIPS");
  onChangeSheetInfo.mode = (oMode == undefined)?null:oMode;
  
	setTimeout(function(){g_initSeleModeVal = true;$("#select_sheets").combobox('select', "0");},50);
	return tab;
}
function getImportCos(isBool)
{
  if(isBool == undefined)
    return (getImportCos.mode != undefined && getImportCos.mode === EVENT_HEADER_MODE)?getEventCosSelectName():getImportCosSelectName();
  else
    return (getImportCos.mode != undefined && getImportCos.mode === EVENT_HEADER_MODE)?getEventCosSelectName(isBool):getImportCosSelectName(isBool);
}
var g_maxImportColAmount = 50;
var g_initSeleModeVal = false;
function onChangeSheetInfo(id)
{
  var oMode = onChangeSheetInfo.mode;
  if(g_initSeleModeVal)
  {
    g_initSeleModeVal = false;
    //onChangeSheetInfo.mode = null;
  }  
  
	var szSheetName = $("#select_sheets").combobox("getText");
	var szSheetIndex = $("#select_sheets").combobox("getValue");
	if(szSheetIndex == "-1")
		return;	
	var tab = document.getElementById("tab_import_excel");
	deleteRowsToIndexByTab(tab,0);
  var seleObj = getImportCos();
	tab.seleObj = seleObj;
	var obj = tab.hideContent;
	var rcObj = getImportRowCol(obj.szPathFile);
	tab.rcObj = rcObj;
	//tab.obj = obj;
	row = tab.insertRow();
	cell = row.insertCell();	
	cell.style.cssText = "padding:0px;padding-left:6px;height:46px;";
	var startInput = getEditInput("import_start_row","","32",16,"onChnangeCol");
	startInput.style.cssText = "width:50px;text-align:center;margin-left:4px;";
	startInput.value = 1;
	startInput.initVal = 1;
	
	var startSp = document.createElement("span");
	startSp.innerText = getLanTextByKey("T_IMPORT_START_ROW_TIPS");
	cell.appendChild(startSp);
	cell.appendChild(startInput);
	
	cell = row.insertCell();	
	var endInput = getEditInput("import_end_row","","32",16,"onChnangeCol");
	endInput.style.cssText = "width:50px;text-align:center;margin-left:4px;";
	endInput.value = rcObj["nRows"];
	endInput.initVal = rcObj["nRows"];
	var endSp = document.createElement("span");
	endSp.style.cssText = "margin-left:4px;";
	endSp.innerText = getLanTextByKey("T_IMPORT_END_ROW_TIPS");
	var btn = document.createElement("a");
	btn.className = "normalbtn";
	btn.href = "javascript:;";
	btn.style.cssText = "margin-left:8px;";
	btn.innerText = getLanTextByKey("T_IMPORT_AUTO_MATCH_COL_TITLE");
	btn.tips = getLanTextByKey("T_IMPORT_AUTO_MATCH_COL_TIPS");
	btn.onclick = autoMatchColHeader;
  
	tab.szSheetName = szSheetName;
	cell.appendChild(endSp);
	cell.appendChild(endInput);
	cell.appendChild(btn);
	setEasyUITooltips(btn,"top");//第 %1 列%1导入到-->%1卡号列
  
	if(oMode != undefined)
  {
    if(oMode["isface"] === IS_IMPORT_FACE_BY_USB)
    {
      setAbtnStatus(btn,true);
      console.log("===btn: " + btn.disabled)
    }  
    else
      setAbtnStatus(btn,false);
  }
  else
    btn.disabled = false;
  
	if(IMPORT_EMPLOYEE_COMPARE_UI_MODE === 1)
		getImportEmpSecondSelectModeUI(tab,rcObj,seleObj,oMode);
	else
		getImportEmpFirstSelectModeUI(tab,rcObj,seleObj,oMode);
	resizePopwin();
}

var g_hasFirstRowEmpFile = false;
function autoMatchColHeader()
{
  if(this.disabled)
    return;
	var tab = document.getElementById("tab_import_excel");
	var tds = document.getElementsByClassName("td_col_header");
	var nRes = _externalLoadExcel(tab.szPathFile);
	if(nRes < 0)
		return;
	nRes = _externalLoadSheet(tab.szSheetName);
	if(nRes < 0)
		return;
	var colObj = getImportCos(true);
	var len = 1;//tab["rcObj"]["nRows"]
	for(var i = 0; i< len; i++)
	{
		var szValue = "";
		for(var j = 0; j < tab["rcObj"]["nCols"]; j++)
		{
			var obj = {"index":j,"len":tab["rcObj"]["nCols"]};
			szValue += readExcelCell(i, j) + "\t";	
			var txt = "";
			var val = "";
			var valStr = readExcelCell(i, j);
			var nObj = checkSetSelectMenu("select_cols_"+((IMPORT_EMPLOYEE_COMPARE_UI_MODE === 1)?j:j),valStr,colObj,j);	
			if(nObj == undefined)
				continue;		
			if(nObj.ret == undefined)
			{}
			else if(nObj.ret)
				g_hasFirstRowEmpFile = true;
			obj[nObj.key] = valStr;
			obj["cname"] = txt;
		}
	}
	if(g_hasFirstRowEmpFile)
	{
		var sObj = document.getElementById("import_start_row");
		if(parseInt(sObj.value,10) < 2)
			sObj.value = "2";
	}
	closeImportFile();
}

function onChangeColInfo(para)
{
	getAllColSelectMenu();	
}
function getAllColSelectMenu()
{
	var str = "select_cols_";	
	var count = 0;
	var seleObj = document.getElementById(str+(count++));
	while(seleObj != undefined)
	{
		var val = $("#"+seleObj.id).combobox("getValue");
		
		if(val != -1)
		{
			setAbtnStatus(document.getElementById("comfirm_ok_btn"),false);
			return;	
		}
		seleObj = document.getElementById(str+(count++));
	}
	setAbtnStatus(document.getElementById("comfirm_ok_btn"),true);
}

function getImportEmpSecondSelectModeUI(tab,rcObj,seleObj)
{
	var aCToC = getLanTextByKey("T_IMPORT_EMP_COL_COL_TIPS").split("%1");
	var maxColSelectWidth = getMaxWidthStringByJson(seleObj,"",1.8);alert('rcObj["nCols"] = ' + rcObj["nCols"]);
	for(var i = 0; i < rcObj["nCols"]; i++)
	{
		row = tab.insertRow();
		cell = row.insertCell();	
		cell.id = "td_col_header_"+i;
		cell.className = "td_col_header";
		cell.style.cssText = "padding:0px;padding-left:6px;height:42px;";
		
		cell.innerHTML = "<font color='blue'>" + aCToC[0] + " " +convertExcelColHeader(i) + " " + aCToC[1] + " </font>"  + aCToC[2];
		cell.initVal = cell.innerHTML;
		
		cell = row.insertCell();
		var obj = new Object();
		obj.mode = VAR_MODE_UIOBJ;
		obj["data"] = seleObj;
		obj["obj"] = getEasyUISelectMenu("select_cols_"+i,maxColSelectWidth,"onChangeColInfo");
		cell.appendChild(obj["obj"]);
		setSelectUItoCellByEasyUI(obj,cell);
		if(i + 1 >= g_maxImportColAmount)
			break;
	}
}

function getImportEmpFirstSelectModeUI(tab,rcObj,seleObj,oMode)
{
	var seleColObjs = getSeleColObjsBySheet(rcObj);	
  var seleColObjsPropertyAmount = 1;
  for(var key in seleColObjs)
    seleColObjsPropertyAmount++;
	var maxColSelectWidth = getMaxWidthStringByJson(seleColObjs,"",1.8);
	var crow = tab.insertRow();
	var pcell = crow.insertCell();
	pcell.colSpan = 2;
	var tabChild = document.createElement('table'); 
	tabChild.style.cssText = "color:#000;line-height:18px;";  	
	tabChild.cellPadding = "0";
	tabChild.cellSpacing = "0";
	tabChild.border = "0";
	//tabChild.width = "100%";
	pcell.appendChild(tabChild);
	
	for(var i = 0; i < seleObj.length; i++)
	{	
		if(seleObj[i+1] == undefined)
			break;
		var row = tabChild.insertRow();
		var cell = row.insertCell();
		cell.id = "td_col_header_"+i;
		cell.seleid = "select_cols_"+i;
		cell.className = "td_col_header";
		cell.style.cssText = "padding:0px;padding-left:6px;height:42px;border:#ccc solid 0px;";
		cell.cname = seleObj[(IMPORT_EMPLOYEE_COMPARE_UI_MODE === 1)?i:i+1]["cname"];
		if(IMPORT_EMPLOYEE_COMPARE_UI_MODE === 1)
			cell.innerHTML = seleObj[i + 1]["text"];
		else
		{
			cell.innerHTML = seleObj[i + 1]["text"];
		}
		cell = row.insertCell();	
		cell.style.cssText = "padding:0px;padding-left:1rem;height:42px;border:#ccc solid 0px;";
		cell.innerHTML = '<span style="margin-left:1rem;margin-right:1rem;"> '+getLanTextByKey("T_IMPORT_EMP_COL2_COL1_TIPS")+' </span>';	
		var obj = new Object();
		obj.mode = VAR_MODE_UIOBJ;
		obj["data"] = seleColObjs;
		obj["obj"] = getEasyUISelectMenu("select_cols_"+i,maxColSelectWidth,"onChangeColInfo");
		cell.appendChild(obj["obj"]);
    if(oMode != null)
    {
      if(oMode["mode"] === 2 && i < oMode["data"].length && seleColObjsPropertyAmount > 2)
        obj["default"] = oMode["data"][i];
    } 
		setSelectUItoCellByEasyUI(obj,cell);
	}	
}
function getSeleColObjsBySheet(rcObj)
{
	var seleColObjs = {};
	var txt = getLanTextByKey("T_EXCEL_COL_NO_NAME");
	seleColObjs["-1"] = getLanTextByKey("T_NOT_IMPORT_EMP_TIPS");
	for(var i = 0; i < rcObj["nCols"]; i++)
		seleColObjs[i+""] = txt.replace("%1",convertExcelColHeader(i));
	return seleColObjs;
}
function convertExcelColHeader(index)
{
	var ordA = 'A'.charCodeAt(0); 
	var ordZ = 'Z'.charCodeAt(0); 
	var len = ordZ - ordA + 1; 
	var s = ""; 
	while( index >= 0 ) 
	{ 
		s = String.fromCharCode(index % len + ordA) + s; 
		index = Math.floor(index / len) - 1; 
	}
	return s;
}

function getImportFilePaths()
{
  var szFilter = "Excel files(*.xlsx;*.xls)|*.xlsx;*.xls|";                  
	var szTitle = getLanTextByKey("T_IMPORT_SELECT_FILE_TIPS");
  var nRes = _externalSelectMultiFile(szFilter, szTitle); 
  var nPath = [];
  if(nRes == null)
    return nPath;
  /*else if(nRes.indexOf("\\") < 0)
    return nPath;
  var aPath = nRes.split("\\");  
  
  var dir = "";
  for(var i = 0; i < aPath.length - 1; i++)
    dir += aPath[i] + "\\";
  */
  if(nRes.indexOf("|") < 0)
    nPath.push(nRes);
  var aFileName = nRes.split("|");  
  for(var i = 1; i < aFileName.length; i++)
    nPath.push(aFileName[0]+ ((aFileName[0].charAt(aFileName[0].length - 1) != "\\")?"\\":"") + aFileName[i]); 
  return nPath;
}
function getExcelSheets(obj)
{
  //打开导入文件
	//var obj = {"szPathFile":getImportFilePath()};	
  console.log("obj.szPathFile="+obj.szPathFile);
	var nRes = _externalLoadExcel(obj.szPathFile);
	//获取Excel文件内的sheet数与sheet名
	var ncSheet = _externalGetSheetCount();
	console.log("ncSheet="+ncSheet);
  if(ncSheet === 0)
     obj["errorCode"] = ERROR_READ_EXCEL_FILE;
	obj.aSzName = Array();	
	for(var i = 0; i < ncSheet; i++)
		(obj.aSzName)[i] = _externalGetSheetName(i);//nIdx >= 0 && nIdx < ncSheet
	//上面的sheet名也可以由用户手动输入
	
	return obj;
}
function getExcelSheetRowCol(szPathFile,szSheetName)
{
  //console.log("szPathFile="+szPathFile+", szSheetName="+szSheetName);
  var nRes = _externalLoadExcel(szPathFile);
  //console.log(nRes);
  if(nRes !== true)
    return null;
	var nSheetRes = _externalLoadSheet(szSheetName);
  //console.log(nSheetRes);
  if(nSheetRes !== true)
    return null;
	var obj = {};
	//获取sheet的行数
	obj["nRows"] = parseInt(_externalGetSheetRows(),10);
	//获取sheet的列数
	obj["nCols"] =  parseInt(_externalGetSheetCols(),10);
	
	return obj;
}
function openExcelFile(szPathFile)
{
  return _externalLoadExcel(szPathFile);
}

function openExcelSheet(szSheetName)
{
  return _externalLoadSheet(szSheetName);
}
function readExcelCell(nRow, nCol)
{
	return _externalGetCellString(nRow, nCol);
}
function closeImportFile()
{
	return _externalUnloadExcel();	
}
function startSaveEvent()
{
  return _externalStartSaveEvent();
}
function stopSaveEvent()
{
  return _externalStopSaveEvent();
}
function addEventRecord(item)
{
  return _externalSaveRecord(item["employeeId"], item["card"], item["date"], AS_ME_EVENT_TYPE_LEGAL_FACE);  
}