//RUNAS
import win;
import win.ui;
import win.ui.mask;
import win.ui.toolbar;
import win.ui.accelerator;
import fonts.fontAwesome;
import console;
import config;
import flexcell;
import teUtils;
import teMenu;
/*DSG{{*/
var mainForm = win.form(text="TabEditor--";right=1399;bottom=799;bgcolor=16777215)
mainForm.add(
custom={cls="custom";text="自定义控件";left=0;top=36;right=1400;bottom=800;ah=1;aw=1;bgcolor=12639424;db=1;dl=1;dr=1;dt=1;z=2};
plus={cls="plus";left=0;top=0;right=1400;bottom=36;bgcolor=16777215;border={left=1;top=1;right=1;color=-6250332};clipBk=false;clipch=1;dl=1;dr=1;dt=1;font=LOGFONT(h=-18);forecolor=16777215;notify=1;repeat="stretch";z=1}
)
/*}}*/

//整理内存
import process;
import raw;
EmptyWorkingSet := ::Psapi.api("EmptyWorkingSet","bool(pointer hanld)")
mainForm.release = function(){
    var hanld = process.OpenProcess(0x1f0fff,false,process.getId())
    EmptyWorkingSet(hanld)
    raw.closehandle(hanld)
}
var frmChild = mainForm.loadForm("\dlg\searchForm.aardio");

//菜单控件初始化
g_teMenus = teMenu.TeMenu(mainForm.plus);

//flexcell控件初始化
g_flexcell = flexcell.FlexGrid(mainForm.custom,,,1);
g_flexcell.setTheme(flexcell.FlexGrid.themeWps);
g_flexcell.isModified = false;
g_flexcell.ShowResizeTip = true;
teUtils.initFlexCellShow(g_flexcell);
g_flexcell.AllowFilter = false;

var showModifyStyle = function(){
    g_flexcell.isModified = true;
    if(teUtils.getCurFilePath() == null){
		g_teMenus.disabled(0, 3, true);
    }
    else {
		g_teMenus.disabled(0, 3, false);
    }
	g_teMenus.disabled(0, 4, false);
    mainForm.text = string.replace(mainForm.text, '[ ][\*]', "");
    mainForm.text += " *";
}

var showUnmodifyStyle = function(){
    g_flexcell.isModified = false;
	g_teMenus.disabled(0, 3, true);
	g_teMenus.disabled(0, 4, true);
    mainForm.text = string.replace(mainForm.text, '[ ][\*]', "");
}
showUnmodifyStyle();

/*菜单{{*/
//menu-新建
g_teMenus.newFile = function(ctrl){
	return function(){
		var curRow = g_flexcell.ActiveCell().Row;
		var curCol = g_flexcell.ActiveCell().Col;
		g_flexcell.FrozenRows = 0;
		g_flexcell.FrozenCols = 0;
		g_flexcell.range(0,0,0,g_flexcell.colCount).ClearBackColor();
		g_flexcell.range(0,0,g_flexcell.rowCount,0).ClearBackColor();
		
		g_flexcell.isModified = true;//避免 ModifyStyle, UnmodifyStyle 切换闪烁
		g_flexcell.clear();
		teUtils.initFlexCellShow(g_flexcell);
		showUnmodifyStyle();
	}
}

//menu-打开
g_teMenus.openFile = function(ctrl){
	return function(){
		var curRow = g_flexcell.ActiveCell().Row;
		var curCol = g_flexcell.ActiveCell().Col;
		g_flexcell.FrozenRows = 0;
		g_flexcell.FrozenCols = 0;
		g_flexcell.range(0,0,g_flexcell.rowCount,g_flexcell.colCount).ClearBackColor();
		var frmMask = win.ui.mask(mainForm,true)
		var t = teUtils.getTxtTableData();
		frmMask.show(true);
		win.delay(500);
		if(t){
			g_flexcell.AutoRedraw = false;
			g_flexcell.setTable(t,,t.fields);
			g_flexcell.column(0).AutoFit();
			g_flexcell.AutoRedraw = true;
			g_flexcell.Refresh();
		}
		frmMask.show(false);
		showModifyStyle();
	}
}

//menu-保存
g_teMenus.saveFile = function(ctrl){
	return function(){
		teUtils.saveTxtTableData(g_flexcell.getVlistData());
		showUnmodifyStyle();
	}
}

//menu-另存为
g_teMenus.saveAsFile = function(ctrl){
	return function(){
		teUtils.saveAsTxtTableData(g_flexcell.getVlistData());
		showUnmodifyStyle();
	}
}

//menu-设置背景色
g_teMenus.setBackground = function(ctrl){
	return function(){
		g_flexcell.selection().BackColor = color.rgbReverse(ctrl.backgroundColor);
	}
}
import win.ui.ctrl.pick;
g_teMenus.setBackgroundRClick = function(ctrl){
	var colorPick = win.ui.ctrl.pick(mainForm);
	colorPick.onColorChange = function(clr){
		ctrl.skin({
			background={
				active=clr;
				default=clr;
				hover=clr
			};
			foreground={
				hover = color.argb(0,0,0,20);
				active = color.argb(0,0,0,40)
			};
			color={
				active=0xE8000000;
				default=0xFF000000;
				disabled=0xFF6D6D6D
			}
		})
	}
	colorPick.setColor(ctrl.backgroundColor);
	var x,y = win.getMessagePos();
	colorPick.setPos(x,y);
	colorPick.doModal();
}

//menu-设置前景色
g_teMenus.setForeground = function(ctrl){
	return function(){
		g_flexcell.selection().ForeColor = color.rgbReverse(ctrl.argbColor);
	}
}
g_teMenus.setForegroundRClick = function(ctrl){
	var colorPick = win.ui.ctrl.pick(mainForm);
	colorPick.onColorChange = function(clr){
		ctrl.skin({
			background={};
			foreground={
				hover = color.argb(0,0,0,20);
				active = color.argb(0,0,0,40)
			};
			color={
				active=clr;
				default=clr;
				disabled=clr
			}
		})
	}
	colorPick.setColor(ctrl.argbColor);
	var x,y = win.getMessagePos();
	colorPick.setPos(x,y);
	colorPick.doModal();
}

class FlexFreeeItem {
	bool change = false;
    int start_row = 0;
    int start_col = 0;
    int end_row = 0;
    int end_col = 0;
}
var flexFreeeCol = FlexFreeeItem();
var flexFreeeRow = FlexFreeeItem();

var setFlexFreee = function(freee){
	if(flexFreeeCol.change){
		g_flexcell.range(flexFreeeCol.start_row, 
						flexFreeeCol.start_col, 
						flexFreeeCol.end_row, 
						flexFreeeCol.end_col).setBorders(2/*_FlexCell2_Edge_Right*/, 0/*_FlexCell2_BorderStyle_cellFlat*/ );
	}
	if(flexFreeeRow.change){
		g_flexcell.range(flexFreeeRow.start_row, 
						flexFreeeRow.start_col, 
						flexFreeeRow.end_row, 
						flexFreeeRow.end_col).setBorders(8/*_FlexCell2_Edge_Bottom*/ , 0/*_FlexCell2_BorderStyle_cellFlat*/ );
	}
	if(!freee){return true;}
	g_flexcell.range(flexFreeeCol.start_row, flexFreeeCol.start_col, flexFreeeCol.end_row, flexFreeeCol.end_col
					).setBorders(2/*_FlexCell2_Edge_Right*/, 1/*_FlexCell2_BorderStyle_cellFlat*/);
	g_flexcell.range(flexFreeeRow.start_row, flexFreeeRow.start_col, flexFreeeRow.end_row, flexFreeeRow.end_col
					).setBorders(8/*_FlexCell2_Edge_Bottom*/ , 1/*_FlexCell2_BorderStyle_cellFlat*/);;
}

//menu-冻结行&列
g_teMenus.freeeRowCol = function(ctrl){
	return function(){
		var curRow = g_flexcell.ActiveCell().Row;
		var curCol = g_flexcell.ActiveCell().Col;
		
		setFlexFreee(false);
		
		//绘制冻结列的右侧边框线
		flexFreeeCol.change = true;
		flexFreeeCol.start_row = curRow+1;
		flexFreeeCol.start_col = curCol;
		flexFreeeCol.end_row = g_flexcell.rowCount;
		flexFreeeCol.end_col = curCol;
		
		//绘制冻结行的底部边框线
		flexFreeeRow.change = true;
		flexFreeeRow.start_row = curRow;
		flexFreeeRow.start_col = curCol+1;
		flexFreeeRow.end_row = curRow;
		flexFreeeRow.end_col = g_flexcell.colCount;
		
		setFlexFreee(true);
		
		//冻结行
		g_flexcell.FrozenRows = curRow;
		//冻结列
		g_flexcell.FrozenCols = curCol;
	}
}

//menu-取消冻结
g_teMenus.unfreeeRowCol = function(ctrl){
	return function(){
		setFlexFreee(false);
		g_flexcell.FrozenRows = 0;
		g_flexcell.FrozenCols = 0;
	}
}

//menu-导出 Sqlite3
g_teMenus.exportSqlite3 = function(ctrl){
	return function(){
	}
}

//menu-导出 txt
g_teMenus.exportTxt = function(ctrl){
	return function(){
	}
}

//menu-关于
g_teMenus.showAbout = function(ctrl){
	return function(){
		//g_flexcell.AboutBox();
	}
}

//menu-帮助
g_teMenus.showHelp = function(ctrl){
	return function(){
		mainForm.release();
	}
}

g_teMenus.setCommandFunc(0, 1, g_teMenus.newFile);
g_teMenus.setCommandFunc(0, 2, g_teMenus.openFile);
g_teMenus.setCommandFunc(0, 3, g_teMenus.saveFile);
g_teMenus.setCommandFunc(0, 4, g_teMenus.saveAsFile);
g_teMenus.setCommandFunc(0, 5, g_teMenus.setBackground);
g_teMenus.setRightClickFunc(0, 5, g_teMenus.setBackgroundRClick);
g_teMenus.setCommandFunc(0, 6, g_teMenus.setForeground);
g_teMenus.setRightClickFunc(0, 6, g_teMenus.setForegroundRClick);
g_teMenus.setCommandFunc(0, 7, g_teMenus.freeeRowCol);
g_teMenus.setCommandFunc(0, 8, g_teMenus.unfreeeRowCol);
g_teMenus.setCommandFunc(0, 9, g_teMenus.exportSqlite3);
g_teMenus.setCommandFunc(0, 10, g_teMenus.exportTxt);
g_teMenus.setCommandFunc(0, 11, g_teMenus.showAbout);
g_teMenus.setCommandFunc(1, 1, g_teMenus.showHelp);
/*}}*/

pre_searched_row = null;
pre_searched_col = null;

/*消息回调{{*/
g_flexcell.onCellChange = function(Row,Col){
	if(!g_flexcell.isModified){
		showModifyStyle();
	}
    g_flexcell.isModified = true;
}

g_flexcell.onClick = function(Row,Col){
	var row,col=owner.toRelativeRow(Row),owner.toRelativeCol(Col);
}

g_flexcell.onMouseUp = function(Button , Shift, x, y){
	/*** 鼠标按键放开。
		 Button 当前按下的鼠标按钮：1：左按钮；2：右按钮；4：中间按钮；同时按下时执行位或操作。
		 Shift 功能键状态：1：SHIFT；2：CTRL；4：ALT；同时按下时执行位或操作。
		 x,y 鼠标指针当前位置 	***/
	if(Button == 2){
		g_flexcell.cell(g_flexcell.MouseRow,g_flexcell.MouseCol).Select();
	}
	if(pre_searched_row != null and pre_searched_col != null){
		g_flexcell.Cell(pre_searched_row, pre_searched_col).BackColor = 0xffffff;
	}
}

g_flexcell.onSelChange = function(FirstRow,FirstCol,LastRow,LastCol){
	/*** 在Selection选择范围改变时发生。参数：起始行，起始列，结束行，结束列 ***/
	var row1,col1=owner.toRelativeRow(FirstRow),owner.toRelativeCol(FirstCol);
	var row2,col2=owner.toRelativeRow(LastRow),owner.toRelativeCol(LastCol);
	console.log(row1, col1, row2, col2)
}
/*}}*/

//搜索窗口
var openSearchForm = function(){
	frmChild.show();
}

var accelerator = win.ui.accelerator({
    { 
        ctrl = true; vkey = 'F'#; 
        oncommand = function() openSearchForm();
    };
},mainForm );

research_flag = true;
searchNextContent = function(data, firstRow, firstCol, lastRow, lastCol, isRangeSearch, selFirstRow, selFirstCol, str){
	if(isRangeSearch){// 从一个范围开始搜索
		//console.dump("从一个范围开始搜索");
		var tempRow = firstRow;
		var tempCol = firstCol;
		firstRow = pre_searched_row != null and research_flag ? pre_searched_row : firstRow;
		firstCol = pre_searched_col != null and research_flag ? pre_searched_col : firstCol;
		for i,v in table.eachIndex(data){
			if(i < firstRow or i > lastRow){
				continue;
			}
			for i2,v2 in table.eachIndex(data.fields){
				//console.debug("当前搜索行列：", i, i2);
				if(i2 < firstCol or i2 > lastCol){
					continue;
				}
				if (i == pre_searched_row and i2 == pre_searched_col){
					continue;
				}
				if(v[v2] == str){
					research_flag = true;
					pre_searched_row = i;
					pre_searched_col = i2;
					return i, i2;
				}
			}
			firstCol = tempRow;
			firstCol = tempCol;
		}
		// 搜不到了，重头搜索
		if(research_flag){
			research_flag = false;
			row, col = searchNextContent(data, selFirstRow, selFirstCol, lastRow, lastCol, isRangeSearch, selFirstRow, selFirstCol, str);
			return row, col;
		}
		research_flag = true;
	}
	else {// 从一个点开始搜索
		//console.dump("从一个点开始搜索");
		for i,v in table.eachIndex(data){
			if(i < firstRow){
				continue;
			}
			for i2,v2 in table.eachIndex(data.fields){
				//console.debug("当前搜索行列：", i, i2);
				if(i2 < firstCol){
					continue
				}
				if(i == firstRow and i2 == firstCol){
					continue;
				}
				if(v[v2] == str){
					research_flag = true;
					return i, i2;
				}
			}
			firstCol = 1;
		}
		// 搜不到了，重头搜索
		if(research_flag){
			research_flag = false;
			//console.dump("搜不到了，重头搜索");
			row, col = searchNextContent(data, 1, 1, 1, 1, isRangeSearch, selFirstRow, selFirstCol, str);
			return row, col;
		}
		research_flag = true;
	}
}

subscribe("search_prev",function(...){
	// TODO
	console.dump(...);
} )


subscribe("search_next",function(...){
	var curSelection = g_flexcell.selection();
	var firstRow = curSelection.FirstRow;
	var firstCol = curSelection.FirstCol;
	var lastRow = curSelection.LastRow;
	var lastCol = curSelection.LastCol;
	var isRangeSearch = false;
	if(firstRow != lastRow or firstCol != lastCol){
		isRangeSearch = true;
	}
	if(pre_searched_row != null and pre_searched_col != null){
		g_flexcell.Cell(pre_searched_row, pre_searched_col).BackColor = 0xffffff;
	}
	var row, col = searchNextContent(g_flexcell.getVlistData(), firstRow, firstCol, lastRow, lastCol, isRangeSearch, firstRow, firstCol, ...);
	//console.dump(row, col);
	if(row != null && col != null){
		if(isRangeSearch){
			if(pre_searched_row != null and pre_searched_col != null){
				g_flexcell.Cell(pre_searched_row, pre_searched_col).BackColor = 0xff00ff;
			}
			g_flexcell.Cell(row, col).EnsureVisible();
		}
		else {
			pre_searched_row = null;
			pre_searched_col = null;
			g_flexcell.cell(row, col).Select();
		}
	}
	else {
		frmChild.msgbox("找不到正在搜索的数据")
	}
	curSelection.release();
} )

import win.ui.minmax;
win.ui.minmax(mainForm,860,400);

mainForm.show();
return win.loopMessage();
