Datatemplate.js 79.8 KB
Newer Older
U
unknown 已提交
1 2
/**
 * 数据模板数据结构.
U
unknown 已提交
3
 * @typedef {Array} DatatemplateData
U
unknown 已提交
4
 * @example
U
unknown 已提交
5
 [ //数据模板数据条目
U
unknown 已提交
6 7
 		{
           "org": [{
U
unknown 已提交
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
                "distinguishedName": "张三@bf007525-99a3-4178-a474-32865bdddec8@I",
                "id": "bf007525-99a3-4178-a474-32865bdddec8",
                "name": "张三",
                "person": "0c828550-d8ab-479e-9880-09a59332f1ed",
                "unit": "9e6ce205-86f6-4d84-96e1-83147567aa8d",
                "unitLevelName": "兰德纵横/市场营销部",
                "unitName": "市场营销部"
            }],
            "org_1": [{
                "distinguishedName": "张三@bf007525-99a3-4178-a474-32865bdddec8@I",
                "id": "bf007525-99a3-4178-a474-32865bdddec8",
                "name": "张三",
                "person": "0c828550-d8ab-479e-9880-09a59332f1ed",
                "unit": "9e6ce205-86f6-4d84-96e1-83147567aa8d",
                "unitLevelName": "兰德纵横/市场营销部",
                "unitName": "市场营销部"
            }, {
                "distinguishedName": "李四@bf007525-99a3-4178-a474-32865bdddec8@I",
                "id": "bf007525-99a3-4178-a474-32865bdddec8",
                "name": "李四",
                "person": "0c828550-d8ab-479e-9880-09a59332f1ed",
                "unit": "9e6ce205-86f6-4d84-96e1-83147567aa8d",
                "unitLevelName": "兰德纵横/市场营销部",
                "unitName": "市场营销部"
            }],
            "number": "111",
            "textfield": "杭州",
            "attachment": [
                {
                    "activityName": "拟稿",
                    "extension": "jpg",
                    "id": "9514758e-9e28-4bfe-87d7-824f2811f173",
                    "lastUpdateTime": "2020-12-09 21:48:03",
                    "length": 452863.0,
                    "name": "111.jpg",
                    "person": "李四@lisi@P"
                }
            ]
        },
U
unknown 已提交
47
 	...
U
unknown 已提交
48
 ]
U
unknown 已提交
49 50 51 52 53 54
 */
MWF.xDesktop.requireApp("process.Xform", "$Module", null, false);
/** @class Datatemplate 数据模板组件。
 * @example
 * //可以在脚本中获取该组件
 * //方法1:
U
unknown 已提交
55
 * var datatemplate = this.form.get("name"); //获取组件
U
unknown 已提交
56
 * //方法2
U
unknown 已提交
57
 * var datatemplate = this.target; //在组件事件脚本中获取
U
unknown 已提交
58 59 60 61 62
 * @extends MWF.xApplication.process.Xform.$Module
 * @o2category FormComponents
 * @o2range {Process|CMS}
 * @hideconstructor
 */
U
unknown 已提交
63
MWF.xApplication.process.Xform.Datatemplate = MWF.APPDatatemplate = new Class(
U
unknown 已提交
64 65 66 67 68 69
	/** @lends MWF.xApplication.process.Xform.Datatemplate# */
	{
		Implements: [Events],
		Extends: MWF.APP$Module,
		isEdit: false,
		options: {
U
unknown 已提交
70 71 72 73 74
			/**
			 * 所有内容加载后执行(包括异步加载)。
			 * @event MWF.xApplication.process.Xform.Datatemplate#afterLoad
			 * @see {@link https://www.yuque.com/o2oa/ixsnyt/hm5uft#i0zTS|组件事件说明}
			 */
U
unknown 已提交
75
			/**
U
unknown 已提交
76
			 * 每初始化一个条目,但未加载的时候触发,通过this.event可以获取条目对象。
U
unknown 已提交
77 78 79 80
			 * @event MWF.xApplication.process.Xform.Datatemplate#beforeLoadLine
			 * @see {@link https://www.yuque.com/o2oa/ixsnyt/hm5uft#i0zTS|组件事件说明}
			 */
			/**
U
unknown 已提交
81
			 * 每一个条目加载后时候触发,通过this.event可以获取条目对象。
U
unknown 已提交
82 83 84 85
			 * @event MWF.xApplication.process.Xform.Datatemplate#afterLoadLine
			 * @see {@link https://www.yuque.com/o2oa/ixsnyt/hm5uft#i0zTS|组件事件说明}
			 */
			/**
U
unknown 已提交
86 87 88
			 * 区段合并后的展现包含此事件,加载条目前执行。通过this.event.sectionKeyList获取所有区段标识,
			 * 通过this.event.data获取数据。
			 * @event MWF.xApplication.process.Xform.Datatemplate#loadSectionData
U
unknown 已提交
89 90 91
			 * @see {@link https://www.yuque.com/o2oa/ixsnyt/hm5uft#i0zTS|组件事件说明}
			 */
			/**
U
unknown 已提交
92 93 94
			 * 区段合并后的展现包含此事件,该事件在每组区段数据条目加载前执行。通过this.event.sectionKey获取当前区段标识,
			 * 通过this.event.sectionData获取当前区段数据。
			 * @event MWF.xApplication.process.Xform.Datatemplate#beforeloadSectionLines
U
unknown 已提交
95 96 97
			 * @see {@link https://www.yuque.com/o2oa/ixsnyt/hm5uft#i0zTS|组件事件说明}
			 */
			/**
U
unknown 已提交
98 99 100
			 * 区段合并后的展现包含此事件,该事件在每组区段数据条目加载后执行。通过this.event.sectionKey获取当前区段标识,
			 * 通过this.event.sectionData获取当前区段数据,通过this.event.sectionLineList获取当前区段的所有条目。
			 * @event MWF.xApplication.process.Xform.Datatemplate#afterloadSectionLines
U
unknown 已提交
101 102
			 * @see {@link https://www.yuque.com/o2oa/ixsnyt/hm5uft#i0zTS|组件事件说明}
			 */
U
unknown 已提交
103
			/**
U
unknown 已提交
104
			 * 添加条目时触发。通过this.event.line可以获取对应的条目对象,this.event.ev可以获得事件触发的Event。
U
unknown 已提交
105
			 * @event MWF.xApplication.process.Xform.Datatemplate#addLine
U
unknown 已提交
106 107 108
			 * @see {@link https://www.yuque.com/o2oa/ixsnyt/hm5uft#i0zTS|组件事件说明}
			 */
			/**
U
unknown 已提交
109
			 * 删除条目前触发。通过this.event可以获取对应的条目对象。
U
unknown 已提交
110
			 * @event MWF.xApplication.process.Xform.Datatemplate#deleteLine
U
unknown 已提交
111 112 113 114
			 * @see {@link https://www.yuque.com/o2oa/ixsnyt/hm5uft#i0zTS|组件事件说明}
			 */
			/**
			 * 删除条目后触发。
U
unknown 已提交
115
			 * @event MWF.xApplication.process.Xform.Datatemplate#afterDeleteLine
U
unknown 已提交
116 117 118 119
			 * @see {@link https://www.yuque.com/o2oa/ixsnyt/hm5uft#i0zTS|组件事件说明}
			 */
			/**
			 * 导出excel的时候触发,this.event指向导出的数据,您可以通过修改this.event来修改数据。
U
unknown 已提交
120
			 * @event MWF.xApplication.process.Xform.Datatemplate#export
U
unknown 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
			 * @see {@link https://www.yuque.com/o2oa/ixsnyt/hm5uft#i0zTS|组件事件说明}
			 * @example
			 * <caption>this.event数据格式如下:</caption>
			 * {
			 *  	data : [
			 *   		["姓名","性别","学历","专业","出生日期","毕业日期"], //标题
			 *  		[ "张三","男","大学本科","计算机","2001-1-2","2019-9-2" ], //第一行数据
			 *  		[ "李四","男","大学专科","数学","1998-1-2","2018-9-2" ]  //第二行数据
			 * 	], //导出的数据
			 *     colWidthArray : [100, 50, 100, 200, 150, 150], //每列宽度
			 *     title : "xxxx" //导出的excel文件标题
			 * }
			 */
			/**
			 * 在导入excel,进行数据校验后触发,this.event指向导入的数据。
U
unknown 已提交
136
			 * @event MWF.xApplication.process.Xform.Datatemplate#validImport
U
unknown 已提交
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
			 * @see {@link https://www.yuque.com/o2oa/ixsnyt/hm5uft#i0zTS|组件事件说明}
			 * @example
			 * <caption>this.event数据格式如下:</caption>
			 * {
			 *  	data : [
			 *  	   {
			 *  	 	"姓名" : "张三",
			 *  	 	"性别" : "男",
			 *  	 	"学历" : "大学本科",
			 *  	    "专业" : "计算机",
			 *  	    "出生日期" : "aa01-1-2",
			 *  	 	"毕业日期" : "2019-9-2",
			 *  	 	"errorTextList" : [
			 *  	 	    "第5列:aa01-1-2不是正确的日期格式。"
			 *  	 	] //校验出的错误信息,如果改行数据正确,则无该字段
			 *  	 }
			 *  	 ...
			 *     ], //导入的数据
			 *     "validted" : true  //是否校验通过,可以在本事件中修改该参数,确定是否强制导入
			 * }
			 */
			/**
U
unknown 已提交
159
			 * 在导入excel,数据校验成功将要设置回数据模板的时候触发,this.event指向整理过的导入数据,格式见{@link DatatemplateData}。
U
unknown 已提交
160
			 * @event MWF.xApplication.process.Xform.Datatemplate#import
U
unknown 已提交
161 162
			 * @see {@link https://www.yuque.com/o2oa/ixsnyt/hm5uft#i0zTS|组件事件说明}
			 */
U
unknown 已提交
163 164
			"moduleEvents": ["queryLoad","postLoad","load", "afterLoad", "loadSectionData", "beforeloadSectionLines", "afterloadSectionLines",
				"beforeLoadLine", "afterLoadLine","addLine", "deleteLine", "afterDeleteLine","export", "import", "validImport"]
U
unknown 已提交
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
		},

		initialize: function(node, json, form, options){
			this.node = $(node);
			this.node.store("module", this);
			this.json = json;
			this.form = form;
			this.field = true;
		},

		_loadUserInterface: function(){
			this.fireEvent("queryLoad");

			this.editModules = [];
			this.node.setStyle("overflow-x", "auto");
			this.node.setStyle("overflow-y", "hidden");

U
unknown 已提交
182
			this.editable = !(this.readonly || (this.json.isReadonly === true));
U
unknown 已提交
183 184 185 186
			if (this.editable && this.json.editableScript && this.json.editableScript.code){
				this.editable = this.form.Macro.exec(((this.json.editableScript) ? this.json.editableScript.code : ""), this);
			}

U
unknown 已提交
187
			this.getRelativeId();
U
unknown 已提交
188

U
unknown 已提交
189 190 191 192 193 194 195
			//允许导入
			this.importenable  = this.editable && (this.importActionIdList.length > 0) &&
				(this.json.impexpType === "impexp" || this.json.impexpType === "imp");

			//允许导出
			this.exportenable  = (this.exportActionIdList.length > 0) && (this.json.impexpType === "impexp" || this.json.impexpType === "exp");

U
unknown 已提交
196
			debugger;
U
unknown 已提交
197
			this.data = this._getValue();
U
unknown 已提交
198 199 200 201
			if( !this._getBusinessData() ){
				this.isNew = true;
				this._setValue(this.data);
			}
U
unknown 已提交
202

U
unknown 已提交
203 204 205
			//object表示数据是区段合并状态
			this.unionMode = o2.typeOf(this.data)==="object";

U
unknown 已提交
206 207
			this.lineList = [];

U
unknown 已提交
208 209 210
			//this.data为object的时候才有值
			// this.lineMap = {};

U
unknown 已提交
211 212 213 214
			// this.totalModules = [];
			this._loadStyles();

			//获取html模板和json模板
U
unknown 已提交
215
			this.getTemplate();
U
unknown 已提交
216 217

			//设置节点外的操作:添加、删除、导入、导出
U
unknown 已提交
218 219
			this.setOuterActionsEvents();

U
unknown 已提交
220 221 222
			//隐藏节点
			this.node.getChildren().hide();

U
unknown 已提交
223
			this.fireEvent("load");
U
unknown 已提交
224 225 226 227
			this._loadDataTemplate(function(){
				// this._loadImportExportAction();
				this.fireEvent("postLoad");
			}.bind(this));
U
unknown 已提交
228
		},
U
unknown 已提交
229 230 231 232 233 234 235 236 237 238 239 240 241
		getRelativeId: function(){
			this.outerAddActionIdList = (this.json.outerAddActionId || "").split(",");
			this.outerDeleteActionIdList = (this.json.outerDeleteActionId || "").split(",");
			this.outerSelectAllIdList = (this.json.outerSelectAllId || "").split(",");

			this.addActionIdList = (this.json.addActionId || "").split(",");
			this.deleteActionIdList = (this.json.deleteActionId || "").split(",");
			this.sequenceIdList = (this.json.sequenceId || "").split(",");
			this.selectorId = this.json.selectorId;

			this.importActionIdList = (this.json.importActionId || "").split(",");
			this.exportActionIdList = (this.json.exportActionId || "").split(",");
		},
U
unknown 已提交
242 243 244 245 246 247 248 249 250 251 252 253 254
		getTemplate: function(){
			this.templateJson = {};
			this.templateHtml = this.node.get("html");
			var moduleNodes = this.form._getModuleNodes(this.node);
			moduleNodes.each(function (node) {
				if (node.get("MWFtype") !== "form") {
					var json = this.form._getDomjson(node);
					this.templateJson[json.id] = json ;
				}
			}.bind(this));
		},
		_loadStyles: function(){
			this.node.setStyles(this.json.styles);
U
unknown 已提交
255
			this.node.set(this.json.properties);
U
unknown 已提交
256
		},
U
unknown 已提交
257
		setOuterActionsEvents: function(){
U
unknown 已提交
258

U
unknown 已提交
259
			//判断不在数据模板中,但是在表单内的Id
U
unknown 已提交
260 261 262
			var getModules = function (idList) {
				var list = [];
				idList.each( function (id) {
U
unknown 已提交
263
					if( !this.templateJson.hasOwnProperty(id) && this.form.all[id] ){
U
unknown 已提交
264 265 266 267
						list.push( this.form.all[id] );
					}
				}.bind(this));
				return list;
U
unknown 已提交
268 269 270
			}.bind(this);

			this.bindEvent = function () {
U
unknown 已提交
271
				this.addActionList = getModules( [].concat(this.addActionIdList, this.outerAddActionIdList) );
U
unknown 已提交
272 273
				this.addActionList.each( function (module) {
					module.node.addEvents({"click": function(e){
U
unknown 已提交
274 275
							this._addLine(e);
						}.bind(this)});
U
unknown 已提交
276
					if( !this.editable )module.node.hide();
U
unknown 已提交
277
				}.bind(this));
U
unknown 已提交
278

U
unknown 已提交
279
				this.deleteActionList = getModules( [].concat( this.outerDeleteActionIdList ) );
U
unknown 已提交
280 281
				this.deleteActionList.each( function (module) {
					module.node.addEvents({"click": function(e){
U
unknown 已提交
282 283
							this._deleteSelectedLine(e);
						}.bind(this)});
U
unknown 已提交
284
					if( !this.editable )module.node.hide();
U
unknown 已提交
285
				}.bind(this));
U
unknown 已提交
286

U
unknown 已提交
287 288
				this.selectAllList = getModules( this.outerSelectAllIdList );
				this.selectAllList.each( function (module) {
U
unknown 已提交
289
					// module.setData(""); //默认不选中
U
unknown 已提交
290
					module.node.addEvents({"click": function(e){
U
unknown 已提交
291 292
							this._checkSelectAll(e);
						}.bind(this)});
U
unknown 已提交
293
					if( !this.editable )module.node.hide();
U
unknown 已提交
294
				}.bind(this));
U
unknown 已提交
295
				this.selectAllSelector = this.selectAllList[0];
U
unknown 已提交
296 297 298
				if(this.selectAllSelector){
					this.unselectAll();
				}
U
unknown 已提交
299

U
unknown 已提交
300 301 302
				this.importActionList = getModules( this.importActionIdList );
				this.importActionList.each( function (module) {
					module.node.addEvents({"click": function(e){
U
unknown 已提交
303 304
							this.importFromExcel();
						}.bind(this)});
U
unknown 已提交
305
					if( !this.editable )module.node.hide();
U
unknown 已提交
306
				}.bind(this));
U
unknown 已提交
307

U
unknown 已提交
308 309 310 311 312 313
				this.exportActionList = getModules( this.exportActionIdList );
				this.exportActionList.each( function (module) {
					module.node.addEvents({"click": function(e){
							this.exportToExcel();
						}.bind(this)})
				}.bind(this));
U
unknown 已提交
314 315

				this.fireEvent("afterLoad");
U
unknown 已提交
316 317 318
				//加载完成以后,删除事件
				this.form.removeEvent("afterModulesLoad", this.bindEvent );
			}.bind(this);
U
unknown 已提交
319

U
unknown 已提交
320 321
			//去要表单的所有组件加载完成以后再去获取外部组件
			this.form.addEvent("afterModulesLoad", this.bindEvent );
U
unknown 已提交
322 323 324
		},
		_getValue: function(){
			if (this.moduleValueAG) return this.moduleValueAG;
U
unknown 已提交
325
			var value = this._getBusinessData();
U
unknown 已提交
326 327
			if (!value){
				if (this.json.defaultData && this.json.defaultData.code) value = this.form.Macro.exec(this.json.defaultData.code, this);
U
unknown 已提交
328
				if (!value.then) if (o2.typeOf(value)==="object") value = [value];
U
unknown 已提交
329
			}
U
unknown 已提交
330 331 332 333 334 335
			if(!value){
				value = [];
				var count = this.json.defaultCount ? this.json.defaultCount.toInt() : 0;
				for( var i=0; i<count; i++ )value.push({})
			}
			return value;
U
unknown 已提交
336 337 338 339 340
		},
		getValue: function(){
			return this._getValue();
		},

U
unknown 已提交
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
		_setValue: function(value){
			if (!!value && o2.typeOf(value.then)=="function"){
				var p = o2.promiseAll(value).then(function(v){
					this.__setValue(v);
				}.bind(this), function(){});
				this.moduleValueAG = p;
				p.then(function(){
					this.moduleValueAG = null;
				}.bind(this), function(){
					this.moduleValueAG = null;
				}.bind(this));
			}else{
				this.moduleValueAG = null;
				this.__setValue(value);
			}
		},
		__setValue: function(value){
			this._setBusinessData(value);
			this.moduleValueAG = null;
			return value;
		},

U
unknown 已提交
363
		_loadDataTemplate: function(callback){
U
unknown 已提交
364 365
			var p = o2.promiseAll(this.data).then(function(v){
				this.data = v;
U
unknown 已提交
366
				// if (o2.typeOf(this.data)=="object") this.data = [this.data];
U
unknown 已提交
367
				this._loadLineList(callback);
U
unknown 已提交
368 369 370 371 372 373 374 375 376 377 378 379
				this.moduleValueAG = null;
				return v;
			}.bind(this), function(){
				this.moduleValueAG = null;
			}.bind(this));
			this.moduleValueAG = p;
			if (this.moduleValueAG) this.moduleValueAG.then(function(){
				this.moduleValueAG = null;
			}.bind(this), function(){
				this.moduleValueAG = null;
			}.bind(this));
		},
U
unknown 已提交
380
		_loadLineList: function(callback){
U
unknown 已提交
381
			if(this.unionMode){ //区段合并后显示
U
unknown 已提交
382
				this.lineList_sectionkey = {};
U
unknown 已提交
383
				var index = 0;
U
unknown 已提交
384 385 386 387 388 389 390 391 392 393 394
				var sectionKeyList = Object.keys(this.data);
				//$union默认放最后
				sectionKeyList.sort(function (a, b) {
					if( a === "$union" ){
						return 1;
					}else if( b === "$union" ){
						return -1;
					}else{
						return 0;
					}
				});
U
unknown 已提交
395 396 397 398
				this.fireEvent("loadSectionData", [{
					"sectionKeyList": sectionKeyList,
					"data": this.data
				}]);
U
unknown 已提交
399 400
				Array.each(sectionKeyList, function (sectionKey, i) {
					var list = this.data[sectionKey];
U
unknown 已提交
401 402 403 404
					this.fireEvent("beforeloadSectionLines", [{
						"sectionKey": sectionKey,
						"sectionData": list
					}]);
U
unknown 已提交
405
					var sectionLineList = [];
U
unknown 已提交
406
					this.lineList_sectionkey[sectionKey] = sectionLineList;
U
unknown 已提交
407
					list.each(function(data, idx){
U
unknown 已提交
408
						var isNew = this.isNew || (o2.typeOf(this.newLineIndex) === "number" ? (idx === this.newLineIndex && sectionKey === this.newLineSectionKey ): false);
U
unknown 已提交
409
						var div = new Element("div").inject(this.node);
U
unknown 已提交
410
						var line = this._loadLine(div, data, index, isNew, idx, sectionKey);
U
unknown 已提交
411
						this.lineList.push(line);
U
unknown 已提交
412
						sectionLineList.push(line);
U
unknown 已提交
413 414
						index++;
					}.bind(this));
U
unknown 已提交
415 416 417 418 419
					this.fireEvent("afterloadSectionLines", [{
						"sectionKey": sectionKey,
						"sectionData": list,
						"sectionLineList" : sectionLineList
					}]);
U
unknown 已提交
420 421 422 423
				}.bind(this));
				this.newLineIndex = null;
				this.newLineSectionKey = null;
			}else{
U
unknown 已提交
424
				this.data.each(function(data, idx){
U
unknown 已提交
425
					var isNew = this.isNew || (o2.typeOf(this.newLineIndex) === "number" ? idx === this.newLineIndex : false);
U
unknown 已提交
426
					var div = new Element("div").inject(this.node);
U
unknown 已提交
427
					var line = this._loadLine(div, data, idx, isNew);
U
unknown 已提交
428
					this.lineList.push(line);
U
unknown 已提交
429
				}.bind(this));
U
unknown 已提交
430
				this.newLineIndex = null;
U
unknown 已提交
431
			}
U
unknown 已提交
432
			this.isNew = false;
U
unknown 已提交
433 434
			if (callback) callback();
		},
U
unknown 已提交
435 436 437 438 439 440 441 442 443 444 445 446 447 448
		isMax : function(){
			var maxCount = this.json.maxCount ? this.json.maxCount.toInt() : 0;
			if( this.editable && maxCount > 0 ) {
				if( this.lineList.length >= maxCount )return true;
			}
			return false;
		},
		isMin : function(){
			var minCount = this.json.minCount ? this.json.minCount.toInt() : 0;
			if( this.editable && minCount > 0 ) {
				if( this.lineList.length <= minCount )return true;
			}
			return false;
		},
U
unknown 已提交
449
		_loadLine: function(container, data, index, isNew, indexInSection, sectionKey){
U
unknown 已提交
450
			var line = new MWF.xApplication.process.Xform.Datatemplate.Line(container, this, data, {
U
unknown 已提交
451 452
				index : index,
				indexText : (index+1).toString(),
U
unknown 已提交
453
				indexInSection: indexInSection,
U
unknown 已提交
454
				indexInSectionText: typeOf(indexInSection) === "number" ?  (index+1).toString() : null,
U
unknown 已提交
455
				sectionKey: sectionKey,
U
unknown 已提交
456 457
				isEdited : this.editable,
				isNew : isNew
U
unknown 已提交
458
			});
U
unknown 已提交
459
			this.fireEvent("beforeLoadLine", [line]);
U
unknown 已提交
460
			line.load();
U
unknown 已提交
461
			this.fireEvent("afterLoadLine", [line]);
U
unknown 已提交
462 463
			return line;
		},
U
unknown 已提交
464 465 466 467 468 469 470 471 472 473 474 475
		_setLineData: function(line, d){
			var index = line.options.index;
			var data;
			if( line.options.sectionKey ){ //区段合并后的数据
				data = this.getData();
				var sectionData = data[line.options.sectionKey];
				sectionData[index] = d;
			}else{
				data = this.getData();
				data[index] = d;
			}
			this.setData( data );
U
unknown 已提交
476
		},
U
unknown 已提交
477
		_addLine: function(ev, sectionKey, d){
U
unknown 已提交
478

U
unknown 已提交
479 480 481 482 483 484 485 486 487 488 489
			if( this.isMax() ){
				var text = MWF.xApplication.process.Xform.LP.maxItemCountNotice.replace("{n}",this.json.maxCount);
				this.form.notice(text,"info");
				return false;
			}

			var data = this.getData();
			var newLine;
			if( this.unionMode ){
				var key =  sectionKey || "$union";
				this.newLineSectionKey = key;
U
unknown 已提交
490 491
				if(!data[key]) data[key] = [];
				var sectionData = data[key];
U
unknown 已提交
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
				sectionData.push(d || {});
				var index = sectionData.length-1;
				this.newLineIndex = index;
				this.setData( data );
				newLine = this.getSectionLine(key, index);
			}else{
				data.push(d || {});
				var index = data.length-1;
				this.newLineIndex = index;
				this.setData( data );
				newLine = this.getLine(index);
			}

			this.fireEvent("addLine",[{"line":newLine, "ev":ev}]);
			return newLine;
		},
U
unknown 已提交
508
		_insertLine: function(ev, beforeLine){
U
unknown 已提交
509
			if( this.isMax() ){
U
unknown 已提交
510 511
				var text = MWF.xApplication.process.Xform.LP.maxItemCountNotice.replace("{n}",this.json.maxCount);
				this.form.notice(text,"info");
U
unknown 已提交
512 513
				return false;
			}
U
unknown 已提交
514
			//使用数据驱动
U
unknown 已提交
515

U
unknown 已提交
516
			var data, newLine;
U
unknown 已提交
517
			if( beforeLine.options.sectionKey ){ //区段合并后的数据
U
unknown 已提交
518 519 520
				var key = beforeLine.options.sectionKey;
				this.newLineSectionKey = key;
				var index = beforeLine.options.indexInSection+1;
U
unknown 已提交
521
				data = this.getData();
U
unknown 已提交
522 523 524 525 526
				var sectionData = data[key];
				sectionData.splice(index, 0, {});
				this.newLineIndex = index;
				this.setData( data );
				newLine = this.getSectionLine( key, index);
U
unknown 已提交
527
			}else{
U
unknown 已提交
528
				var index = beforeLine.options.index+1;
U
unknown 已提交
529 530
				data = this.getData();
				data.splice(index, 0, {});
U
unknown 已提交
531 532 533
				this.newLineIndex = index;
				this.setData( data );
				newLine = this.getLine( index );
U
unknown 已提交
534
			}
U
unknown 已提交
535 536
			this.fireEvent("addLine",[{"line":newLine, "ev":ev}]);
			return newLine;
U
unknown 已提交
537
		},
U
unknown 已提交
538 539 540 541 542 543 544
		_insertLineByIndex: function(ev, sectionKey, index, d){
			if( this.isMax() ){
				var text = MWF.xApplication.process.Xform.LP.maxItemCountNotice.replace("{n}",this.json.maxCount);
				this.form.notice(text,"info");
				return false;
			}
			//使用数据驱动
U
unknown 已提交
545
			var data, newLine;
U
unknown 已提交
546
			if( sectionKey ){ //区段合并后的数据
U
unknown 已提交
547
				this.newLineSectionKey = sectionKey;
U
unknown 已提交
548
				data = this.getData();
U
unknown 已提交
549
				if(!data[sectionKey]) data[sectionKey] = [];
U
unknown 已提交
550 551 552
				var sectionData = data[sectionKey];
				if( o2.typeOf(sectionData) !== "array" || sectionData.length < index )return null;
				sectionData.splice(index, 0, d||{});
U
unknown 已提交
553 554 555
				this.newLineIndex = index;
				this.setData( data );
				newLine = this.getSectionLine( sectionKey, index);
U
unknown 已提交
556 557 558 559
			}else{
				data = this.getData();
				if(data.length < index )return null;
				data.splice(index, 0, d||{});
U
unknown 已提交
560 561 562
				this.newLineIndex = index;
				this.setData( data );
				newLine = this.getLine( index );
U
unknown 已提交
563
			}
U
unknown 已提交
564 565
			this.fireEvent("addLine",[{"line":newLine, "ev":ev}]);
			return newLine;
U
unknown 已提交
566
		},
U
unknown 已提交
567 568 569
		_deleteSelectedLine: function(ev){
			var selectedLine = this.lineList.filter(function (line) { return line.selected; });
			if( selectedLine.length === 0 ){
U
unknown 已提交
570
				this.form.notice( MWF.xApplication.process.Xform.LP.selectItemNotice,"info");
U
unknown 已提交
571 572 573
				return false;
			}
			var minCount = this.json.minCount ? this.json.minCount.toInt() : 0;
U
unknown 已提交
574
			if( minCount > 0 ){
U
unknown 已提交
575
				if( this.lineList.length - selectedLine.length < minCount ){
U
unknown 已提交
576 577
					var text = MWF.xApplication.process.Xform.LP.minItemNotice.replace("{n}", minCount );
					this.form.notice(text,"info");
U
unknown 已提交
578 579 580
					return false;
				}
			}
U
unknown 已提交
581
			var _self = this;
U
unknown 已提交
582
			this.form.confirm("warn", ev, MWF.xApplication.process.Xform.LP.deleteDatagridLineTitle, MWF.xApplication.process.Xform.LP.deleteSelectedItemNotice, 300, 120, function(){
U
unknown 已提交
583

U
unknown 已提交
584
				_self._delLines( selectedLine );
U
unknown 已提交
585

U
unknown 已提交
586 587 588 589 590 591 592
				this.close();

			}, function(){
				this.close();
			}, null, null, this.form.json.confirmStyle);

		},
U
unknown 已提交
593
		_delLines: function(lines){
U
unknown 已提交
594
			var _self = this;
U
unknown 已提交
595 596
			var data = _self.getData();

U
unknown 已提交
597 598
			var saveFlag = false;

U
unknown 已提交
599
			lines.reverse().each(function(line){
U
unknown 已提交
600
				_self.fireEvent("deleteLine", [line]);
U
unknown 已提交
601

U
unknown 已提交
602 603
				if(line.deleteAttachment())saveFlag = true;

U
unknown 已提交
604 605 606
				if( line.options.sectionKey ){ //区段合并后的数据
					var sectionData = data[line.options.sectionKey];
					sectionData.splice(line.options.indexInSection, 1);
U
unknown 已提交
607
				}else{
U
unknown 已提交
608
					data.splice(line.options.index, 1);
U
unknown 已提交
609
				}
U
unknown 已提交
610

U
unknown 已提交
611
				_self.fireEvent("afterDeleteLine");
U
unknown 已提交
612 613 614
			});

			_self.setData( data );
U
unknown 已提交
615
			if(saveFlag)this.form.saveFormData();
U
unknown 已提交
616 617 618 619 620 621 622 623 624
		},
		_deleteLine: function(ev, line){
			if( this.isMin() ){
				var text = MWF.xApplication.process.Xform.LP.minItemCountNotice.replace("{n}", this.json.minCount );
				this.form.notice(text,"info");
				return false;
			}
			var _self = this;
			this.form.confirm("warn", ev, MWF.xApplication.process.Xform.LP.deleteDatagridLineTitle, MWF.xApplication.process.Xform.LP.deleteDatagridLine, 300, 120, function(){
U
unknown 已提交
625
				_self._delLine(line);
U
unknown 已提交
626
				this.close();
U
unknown 已提交
627 628 629
			}, function(){
				this.close();
			}, null, null, this.form.json.confirmStyle);
U
unknown 已提交
630
		},
U
unknown 已提交
631
		_delLine: function(line){
U
unknown 已提交
632 633
			this.fireEvent("deleteLine", [line]);

U
unknown 已提交
634
			var saveFlag = line.deleteAttachment();
U
unknown 已提交
635 636 637 638 639 640 641 642 643 644
			//使用数据驱动
			var data = this.getData();
			if( line.options.sectionKey ){ //区段合并后的数据
				var sectionData = data[line.options.sectionKey];
				sectionData.splice(line.options.indexInSection, 1);
			}else {
				data.splice(line.options.index, 1);
			}
			this.setData( data );
			this.fireEvent("afterDeleteLine");
U
unknown 已提交
645
			if(saveFlag)this.form.saveFormData();
U
unknown 已提交
646
		},
U
unknown 已提交
647 648 649 650 651 652 653 654
		_checkSelectAll: function () {
			var selectData = this.selectAllSelector.getData();
			var selected;
			if(o2.typeOf(selectData)==="array"){
				selected = selectData.contains(this.json.outerSelectAllSelectedValue);
			}else{
				selected = selectData === this.json.outerSelectAllSelectedValue;
			}
U
unknown 已提交
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
			this.selected = selected;
			this.lineList.each(function (line) {
				this.selected ? line.select() : line.unselect();
			}.bind(this))
		},
		selectAll: function(){
			this.selected = true;
			if(this.selectAllSelector)this.selectAllSelector.setData(this.json.outerSelectAllSelectedValue);
		},
		unselectAll: function(){
			this.selected = false;
			if( this.selectAllSelector.getOptionsObj ){
				var options = this.selectAllSelector.getOptionsObj();
				var value = "";
				var arr = options.valueList || [];
				for( var i=0; i<arr.length; i++ ){
					var v = arr[i];
					if( v !== this.json.outerSelectAllSelectedValue ){
						value = v;
						break;
					}
				}
				this.selectAllSelector.setData(value);
			}else{
				this.selectAllSelector.setData("")
U
unknown 已提交
680 681
			}
		},
U
unknown 已提交
682 683 684 685

		editValidation: function(){
			var flag = true;
			this.editModules.each(function(field, key){
U
unknown 已提交
686
				if (field.json.type!=="sequence" && field.validationMode ){
U
unknown 已提交
687 688 689 690 691 692
					field.validationMode();
					if (!field.validation()) flag = false;
				}
			}.bind(this));
			return flag;
		},
U
unknown 已提交
693
		exportToExcel: function(){
U
unknown 已提交
694 695
			this.exporter = new MWF.xApplication.process.Xform.Datatemplate.Exporter(this);
			this.exporter.exportToExcel();
U
unknown 已提交
696 697
		},
		importFromExcel: function(){
U
unknown 已提交
698 699
			this.importer = new MWF.xApplication.process.Xform.Datatemplate.Importer(this);
			this.importer.importFromExcel();
U
unknown 已提交
700
		},
U
unknown 已提交
701

U
unknown 已提交
702 703 704 705

		_afterLoaded: function(){
		},
		/**
U
unknown 已提交
706
		 * @summary 重置数据模板的值为默认值或置空。
U
unknown 已提交
707 708 709 710 711 712 713 714
		 *  @example
		 * this.form.get('fieldId').resetData();
		 */
		resetData: function(){
			this.setData(this._getValue());
		},
		/**当参数为Promise的时候,请查看文档: {@link  https://www.yuque.com/o2oa/ixsnyt/ws07m0|使用Promise处理表单异步}<br/>
		 * 当表单上没有对应组件的时候,可以使用this.data[fieldId] = data赋值。
U
unknown 已提交
715
		 * @summary 为数据模板赋值。
U
unknown 已提交
716
		 * @param data{DatatemplateData|Promise|Array} 必选,数组或Promise.
U
unknown 已提交
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
		 * @example
		 *  this.form.get("fieldId").setData([]); //赋空值
		 * @example
		 *  //如果无法确定表单上是否有组件,需要判断
		 *  if( this.form.get('fieldId') ){ //判断表单是否有无对应组件
		 *      this.form.get('fieldId').setData( data );
		 *  }else{
		 *      this.data['fieldId'] = data;
		 *  }
		 *@example
		 *  //使用Promise
		 *  var field = this.form.get("fieldId");
		 *  var promise = new Promise(function(resolve, reject){ //发起异步请求
		 *    var oReq = new XMLHttpRequest();
		 *    oReq.addEventListener("load", function(){ //绑定load事件
		 *      resolve(oReq.responseText);
		 *    });
		 *    oReq.open("GET", "/data.json"); //假设数据存放在data.json
		 *    oReq.send();
		 *  });
		 *  promise.then( function(){
		 *    var data = field.getData(); //此时由于异步请求已经执行完毕,getData方法获得data.json的值
		 * })
		 *  field.setData( promise );
		 */
		setData: function(data){
			if (!data){
				data = this._getValue();
			}
			this._setData(data);
		},
		_setData: function(data){
			var p = o2.promiseAll(this.data).then(function(v){
U
unknown 已提交
750
				this.data = v;
U
unknown 已提交
751
				// if (o2.typeOf(data)==="object") data = [data];
U
unknown 已提交
752 753 754 755 756 757 758 759 760 761 762 763 764 765
				this.__setData(data);
				this.moduleValueAG = null;
				return v;
			}.bind(this), function(){
				this.moduleValueAG = null;
			}.bind(this));
			this.moduleValueAG = p;
			if (this.moduleValueAG) this.moduleValueAG.then(function(){
				this.moduleValueAG = null;
			}.bind(this), function(){
				this.moduleValueAG = null;
			}.bind(this));
		},
		__setData: function(data){
U
unknown 已提交
766
			// if( typeOf( data ) === "object" && typeOf(data) === "array"  ){
U
unknown 已提交
767
			this._setBusinessData(data);
U
unknown 已提交
768 769 770 771 772
			this.data = data;

			if (this.data){
				for (var i=0; i<this.lineList.length; i++){
					this.lineList[i].clear();
U
unknown 已提交
773 774
				}
			}
U
unknown 已提交
775 776 777

			this.lineList = [];
			this._loadDataTemplate()
U
unknown 已提交
778 779
		},
		/**
U
unknown 已提交
780
		 * @summary 判断数据模板是否为空.
U
unknown 已提交
781 782 783 784 785 786 787 788 789
		 * @example
		 * if( this.form.get('fieldId').isEmpty() ){
		 *     this.form.notice('至少需要添加一条数据', 'warn');
		 * }
		 * @return {Boolean} 是否为空
		 */
		isEmpty: function(){
			var data = this.getData();
			if( !data )return true;
U
unknown 已提交
790
			if( o2.typeOf( data ) === "array" ){
U
unknown 已提交
791
				return data.length === 0;
U
unknown 已提交
792
			}
U
unknown 已提交
793 794 795
			if( o2.typeOf( data ) === "object" ){
				return Object.keys(data).length === 0;
			}
U
unknown 已提交
796 797
			return false;
		},
U
unknown 已提交
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
		//api 相关开始
		/**
		 * 获取对应的条目。该方法在有无区段的情况下都可以使用。
		 * @param {Number} index 条目序号,从零开始
		 * @return {MWF.xApplication.process.Xform.Datatemplate.Line | Null} 对应的数据模板条目
		 * @example
		 * //获取数据模板“dt1”的第一个条目。
		 * var line = this.form.get("dt1").getLine(0);
		 * //获取第一个条目subject字段的值
		 * var data = line.getModule("subject").getData();
		 * //设置subject字段的值
		 * line.getModule("subject").setData("test1");
		 */
		getLine: function(index){
			var line = this.lineList[index];
			return line || null;
		},
		/**
		 * 在数据模板末尾添加条目。如果当前是区段合并后的数据,会往区段标识为$union的区段中插入条目。
		 * @param {Object} [data] 添加条目的数据。
		 * @return {MWF.xApplication.process.Xform.Datatemplate.Line} 添加的数据模板条目
		 * @example
		 * var line = this.form.get("dt1").addLine();
		 */
		addLine: function( data ){
U
unknown 已提交
823
			return this._addLine( null, null, data );
U
unknown 已提交
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
		},
		/**
		 * 在数据模板指定位置添加条目。
		 * @param {Number} index 条目序号,从零开始,如果下标超过当前数据模板条目数,插入失败并返回null。
		 * @param {Object} [data] 添加条目的数据。
		 * @return {MWF.xApplication.process.Xform.Datatemplate.Line | Null} 插入的数据模板条目
		 * @example
		 * var line = this.form.get("dt1").insertLine(0);
		 */
		insertLine: function(index, data){
			return this._insertLineByIndex(null, null, index, data);
		},
		/**
		 * 删除指定位置的条目。
		 * @param {Number} index 条目序号,从零开始,如果下标超过当前数据模板条目数,删除失败。
		 * @example
		 * //直接删除第一个条目
		 * this.form.get("dt1").deleteLine(0);
		 */
		deleteLine: function(index, ev){
			var line = this.lineList[index];
			if( !line )return null;
			// if( ev ){
			// 	this._deleteLine(ev, line);
			// }else{
U
unknown 已提交
849
			this._delLine(line);
U
unknown 已提交
850 851
			// }
		},
U
unknown 已提交
852
		/**
U
unknown 已提交
853
		 * 获取对应表单组件。该方法在有无区段的情况下都可以使用。
U
unknown 已提交
854 855 856 857 858 859 860 861 862 863 864 865 866 867
		 * @param {Number} index 条目序号,从零开始
		 * @param {String} id 组件标识
		 * @return {FormComponent} 对应表单组件
		 * @example
		 * //获取数据模板“dt1”的第一个条目的subject字段。
		 * var module = this.form.get("dt1").getModule(0, "subject");
		 * //获取subject字段的值
		 * var data = module.getData();
		 * //设置subject字段的值
		 * module.setData("test1");
		 */
		getModule: function(index, id){
			var line = this.lineList[index];
			if( !line )return null;
U
unknown 已提交
868 869 870
			return line.getModule(id);
		},

U
unknown 已提交
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903

		/**
		 * 该方法在区段合并后可以使用,用来获取区段合并后对应的条目。
		 * @param {String} sectionKey 区段标识
		 * @param {Number} index 对应区段中的条目序号,从零开始
		 * @return {MWF.xApplication.process.Xform.Datatemplate.Line} 对应的数据模板条目
		 * @example
		 * //假设在流程中有节点A->B,在A中的数据模板中设置了区段,区段依据是部门,B中没有设置区段。
		 * //流转的时候,在A节点“开发部@kfb@U”的处理人添加了数据模板。
		 * //现在在节点B,获取数据模板“dt1”->“开发部@kfb@U”区段下的第一个条目。
		 * var line = this.form.get("dt1").getSectionLine("开发部@kfb@U",0);
		 * //获取第一个条目subject字段的值
		 * var data = line.getModule("subject").getData();
		 * //设置subject字段的值
		 * line.getModule("subject").setData("test1");
		 */
		getSectionLine: function(sectionKey,index){
			if( !this.unionMode )return;
			var lineList = this.lineList_sectionkey[sectionKey];
			if( !lineList )return null;
			var line = lineList[index];
			return line || null;
		},
		/**
		 * 该方法在区段合并后可以使用,用来在数据模板指定区段后添加条目。
		 * @param {String} sectionKey 区段标识,如果数据中无对应区段会自动创建一个区段
		 * @param {Object} [data] 添加条目的数据。
		 * @return {MWF.xApplication.process.Xform.Datatemplate.Line} 添加的数据模板条目
		 * @example
		 * var line = this.form.get("dt1").addSectionLine("开发部@kfb@U", 0);
		 */
		addSectionLine: function(sectionKey, data){
			if( !this.unionMode )return;
U
unknown 已提交
904
			return this._addLine(null,  sectionKey, data);
U
unknown 已提交
905 906 907 908 909 910 911 912 913 914 915 916 917
		},
		/**
		 * 该方法在区段合并后可以使用,用来在数据模板指定位置添加条目。
		 * @param {String} sectionKey 区段标识,如果数据中无对应区段会自动创建一个区段。
		 * @param {Number} index 对应区段中的条目序号,从零开始,如果下标超过当前区段条目数,插入失败并返回null。
		 * @param {Object} [data] 添加条目的数据。
		 * @return {MWF.xApplication.process.Xform.Datatemplate.Line} 插入的数据模板条目
		 * @example
		 * var line = this.form.get("dt1").insertSectionLine("开发部@kfb@U", 0);
		 */
		insertSectionLine: function(sectionKey, index, data){
			if( !this.unionMode )return;
			if( !this.data[sectionKey] ){
U
unknown 已提交
918
				return this._addLine(null, sectionKey, data);
U
unknown 已提交
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937
			}else{
				return this._insertLineByIndex(null, sectionKey, index, data);
			}
		},
		/**
		 * 该方法在区段合并后可以使用,删除指定位置的条目。
		 * @param {String} sectionKey 对应区段中的条目序号
		 * @param {Number} index 对应区段中的条目序号,从零开始,如果下标超过当前数据模板条目数,删除失败。
		 * @example
		 * //直接删除第一个条目
		 * this.form.get("dt1").deleteSectionLine("开发部@kfb@U", 0);
		 */
		deleteSectionLine: function(sectionKey, index, ev){
			if( !this.unionMode )return;
			var line = this.getSectionLine(sectionKey, index);
			if( !line )return null;
			// if( ev ){
			// 	this._deleteLine(ev, line);
			// }else{
U
unknown 已提交
938
				this._delLine(line);
U
unknown 已提交
939 940
			// }
		},
U
unknown 已提交
941 942 943 944 945 946 947 948
		/**
		 * 该方法在区段合并后可以使用,用来获取区段合并后对应表单组件。
		 * @param {String} sectionKey 区段标识
		 * @param {Number} index 对应区段中的条目序号,从零开始
		 * @param {String} id 组件标识
		 * @return {FormComponent} 对应表单组件
		 * @example
		 * //假设在流程中有节点A->B,在A中的数据模板中设置了区段,区段依据是部门,B中没有设置区段。
U
unknown 已提交
949 950
		 * //流转的时候,在A节点“开发部@kfb@U”的处理人添加了数据模板条目。
		 * //现在流转到了节点B,那么获取上述处理人在数据模板“dt1”添加的第一个节点的标题字段如下:
U
unknown 已提交
951
		 * var dataTemplate = this.form.get("dt1"); //获取数据模板dt1
U
unknown 已提交
952
		 * var module = dataTemplate.getSectionModule("开发部@kfb@U", 0, "subject"); //获取标题字段
U
unknown 已提交
953 954 955 956 957
		 * //获取subject字段的值
		 * var data = module.getData();
		 * //设置subject字段的值
		 * module.setData("test1");
		 */
U
unknown 已提交
958 959
		getSectionModule: function(sectionKey, index, id){
			if( !this.unionMode )return;
U
unknown 已提交
960 961 962 963 964
			var lineList = this.lineList_sectionkey[sectionKey];
			if( !lineList )return null;
			var line = lineList[index];
			if( !line )return null;
			return line.getModule(id);
U
unknown 已提交
965
		},
U
unknown 已提交
966
		//api 相关
U
unknown 已提交
967 968 969 970 971 972 973 974 975

		/**
		 * 在脚本中使用 this.data[fieldId] 也可以获取组件值。
		 * 区别如下:<br/>
		 * 1、当使用Promise的时候<br/>
		 * 使用异步函数生成器(Promise)为组件赋值的时候,用getData方法立即获取数据,可能返回修改前的值,当Promise执行完成以后,会返回修改后的值。<br/>
		 * this.data[fieldId] 立即获取数据,可能获取到异步函数生成器,当Promise执行完成以后,会返回修改后的值。<br/>
		 * {@link https://www.yuque.com/o2oa/ixsnyt/ws07m0#EggIl|具体差异请查看链接}<br/>
		 * 2、当表单上没有对应组件的时候,可以使用this.data[fieldId]获取值,但是this.form.get('fieldId')无法获取到组件。
U
unknown 已提交
976
		 * @summary 获取数据模板数据.
U
unknown 已提交
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
		 * @example
		 * var data = this.form.get('fieldId').getData();
		 *@example
		 *  //如果无法确定表单上是否有组件,需要判断
		 *  var data;
		 *  if( this.form.get('fieldId') ){ //判断表单是否有无对应组件
		 *      data = this.form.get('fieldId').getData();
		 *  }else{
		 *      data = this.data['fieldId']; //直接从数据中获取字段值
		 *  }
		 *  @example
		 *  //使用Promise
		 *  var field = this.form.get("fieldId");
		 *  var promise = new Promise(function(resolve, reject){ //发起异步请求
		 *    var oReq = new XMLHttpRequest();
		 *    oReq.addEventListener("load", function(){ //绑定load事件
		 *      resolve(oReq.responseText);
		 *    });
		 *    oReq.open("GET", "/data.json"); //假设数据存放在data.json
		 *    oReq.send();
		 *  });
		 *  promise.then( function(){
		 *    var data = field.getData(); //此时由于异步请求已经执行完毕,getData方法获得data.json的值
		 * })
		 *  field.setData( promise );
U
unknown 已提交
1002
		 * @return {DatatemplateData}
U
unknown 已提交
1003 1004
		 */
		getData: function(){
U
unknown 已提交
1005 1006 1007
			if( this.importer ){
				this.importer.destroySimulateModule();
			}
U
unknown 已提交
1008
			if (this.editable!==false){
U
unknown 已提交
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
				// var data = [];
				// this.lineList.each(function(line, index){
				// 	data.push(line.getData())
				// });
				//
				// this.data = data;
				//
				// this._setBusinessData(this.data);
				//
				// return (this.data.length) ? this.data : [];
				return this._getBusinessData();
U
unknown 已提交
1020 1021 1022 1023
			}else{
				return this._getBusinessData();
			}
		},
U
unknown 已提交
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
		_getSectionKey: function(){
			if (this.json.section!=="yes"){
				return "";
			}else {
				switch (this.json.sectionBy){
					case "person":
						return layout.desktop.session.user.id;
					case "unit":
						return (this.form.businessData.task) ? this.form.businessData.task.unit : "";
					case "activity":
						return (this.form.businessData.work) ? this.form.businessData.work.activity : "";
					case "splitValue":
						return (this.form.businessData.work) ? this.form.businessData.work.splitValue : "";
					case "script":
						if( this.json.sectionByScript && this.json.sectionByScript.code){
							return this.form.Macro.exec(this.json.sectionByScript.code, this) || "";
						}else{
							return "";
						}
					default:
						return "";
				}
			}
		},
U
unknown 已提交
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
		createErrorNode: function(text){
			var node = new Element("div");
			var iconNode = new Element("div", {
				"styles": {
					"width": "20px",
					"height": "20px",
					"float": "left",
					"background": "url("+"../x_component_process_Xform/$Form/default/icon/error.png) center center no-repeat"
				}
			}).inject(node);
			var textNode = new Element("div", {
				"styles": {
					"line-height": "20px",
					"margin-left": "20px",
					"color": "red",
					"word-break": "keep-all"
				},
				"text": text
			}).inject(node);
			return node;
		},
		notValidationMode: function(text){
			if (!this.isNotValidationMode){
				this.isNotValidationMode = true;
				this.node.store("borderStyle", this.node.getStyles("border-left", "border-right", "border-top", "border-bottom"));
				this.node.setStyle("border", "1px solid red");

				this.errNode = this.createErrorNode(text).inject(this.node, "after");
				this.showNotValidationMode(this.node);
			}
		},
		showNotValidationMode: function(node){
			var p = node.getParent("div");
			if (p){
				if (p.get("MWFtype") == "tab$Content"){
					if (p.getParent("div").getStyle("display")=="none"){
						var contentAreaNode = p.getParent("div").getParent("div");
						var tabAreaNode = contentAreaNode.getPrevious("div");
						var idx = contentAreaNode.getChildren().indexOf(p.getParent("div"));
						var tabNode = tabAreaNode.getLast().getFirst().getChildren()[idx];
						tabNode.click();
						p = tabAreaNode.getParent("div");
					}
				}
				this.showNotValidationMode(p);
			}
		},
		validationMode: function(){
			if (this.isNotValidationMode){
				this.isNotValidationMode = false;
				this.node.setStyles(this.node.retrieve("borderStyle"));
				if (this.errNode){
					this.errNode.destroy();
					this.errNode = null;
				}
			}
		},

		validationConfigItem: function(routeName, data){
			var flag = (data.status=="all") ? true: (routeName == data.decision);
			if (flag){
				var n = this.getData();
U
unknown 已提交
1110 1111 1112 1113 1114 1115 1116
				if( o2.typeOf(n)==="object"){
					var arr = [];
					Object.each( n, function (d, key) {
						if(o2.typeOf(d) === "array")arr = arr.concat(d);
					});
					n = arr;
				}
U
unknown 已提交
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
				var v = (data.valueType=="value") ? n : n.length;
				switch (data.operateor){
					case "isnull":
						if (!v){
							this.notValidationMode(data.prompt);
							return false;
						}
						break;
					case "notnull":
						if (v){
							this.notValidationMode(data.prompt);
							return false;
						}
						break;
					case "gt":
						if (v>data.value){
							this.notValidationMode(data.prompt);
							return false;
						}
						break;
					case "lt":
						if (v<data.value){
							this.notValidationMode(data.prompt);
							return false;
						}
						break;
					case "equal":
						if (v==data.value){
							this.notValidationMode(data.prompt);
							return false;
						}
						break;
					case "neq":
						if (v!=data.value){
							this.notValidationMode(data.prompt);
							return false;
						}
						break;
					case "contain":
						if (v.indexOf(data.value)!=-1){
							this.notValidationMode(data.prompt);
							return false;
						}
						break;
					case "notcontain":
						if (v.indexOf(data.value)==-1){
							this.notValidationMode(data.prompt);
							return false;
						}
						break;
				}
			}
			return true;
		},
		validationConfig: function(routeName, opinion){
			if (this.json.validationConfig){
				if (this.json.validationConfig.length){
					for (var i=0; i<this.json.validationConfig.length; i++) {
						var data = this.json.validationConfig[i];
						if (!this.validationConfigItem(routeName, data)) return false;
					}
				}
				return true;
			}
			return true;
		},
		/**
		 * @summary 根据组件的校验设置进行校验。
		 *  @param {String} [routeName] - 可选,路由名称.
		 *  @example
		 *  if( !this.form.get('fieldId').validation() ){
		 *      return false;
		 *  }
		 *  @return {Boolean} 是否通过校验
		 */
		validation: function(routeName, opinion){
			if (this.isEdit){
				if (!this.editValidation()){
					return false;
				}
			}
			if (!this.validationConfig(routeName, opinion))  return false;

			if (!this.json.validation) return true;
			if (!this.json.validation.code) return true;

			this.currentRouteName = routeName;
			var flag = this.form.Macro.exec(this.json.validation.code, this);
			this.currentRouteName = "";

			if (!flag) flag = MWF.xApplication.process.Xform.LP.notValidation;
U
unknown 已提交
1208
			if (flag.toString()!=="true"){
U
unknown 已提交
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
				this.notValidationMode(flag);
				return false;
			}
			return true;
		},
		getAttachmentRandomSite: function(){
			var i = (new Date()).getTime();
			return this.json.id+i;
		}
	});

MWF.xApplication.process.Xform.Datatemplate.Line =  new Class({
	Implements: [Options, Events],
	options: {
U
unknown 已提交
1223
		isNew: false,
U
unknown 已提交
1224 1225
		isEdited : true,
		index : 0,
U
unknown 已提交
1226 1227
		indexText : "0",
		indexInSection: null, //区段合并后数据的data[sectionKey][index]
U
unknown 已提交
1228
		indexInSectionText: null,
U
unknown 已提交
1229
		sectionKey: null //区段合并后数据的key
U
unknown 已提交
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
	},
	initialize: function (node, template, data, options) {

		this.setOptions(options);

		this.node = node;
		this.template = template;
		this.data = data;
		this.form = this.template.form;

U
unknown 已提交
1240 1241
		this.modules = [];
		this.all = {};
U
unknown 已提交
1242
		this.all_templateId = {};
U
unknown 已提交
1243 1244 1245

		this.fields = [];
		this.allField = {};
U
unknown 已提交
1246
		this.allField_templateId = {};
U
unknown 已提交
1247 1248 1249 1250 1251 1252 1253 1254 1255

		this.addActionList = [];
		this.deleteActionList = [];
		this.sequenceNodeList = [];
		this.selector = null;
		this.importActionList = [];
		this.exportActionList = [];


U
unknown 已提交
1256
	},
U
unknown 已提交
1257
	load: function(){
U
unknown 已提交
1258 1259
		this.node.set("html", this.template.templateHtml);
		var moduleNodes = this.form._getModuleNodes(this.node);
U
unknown 已提交
1260 1261 1262
		//this.options.sectionKey 为区段合并后的数据
		//this.template._getSectionKey() 为当前在区段状态下
		var sectionKey = this.options.sectionKey || this.template._getSectionKey();
U
unknown 已提交
1263 1264 1265 1266
		moduleNodes.each(function (node) {
			if (node.get("MWFtype") !== "form") {
				var _self = this;

U
unknown 已提交
1267 1268 1269 1270
				var tJson = this.form._getDomjson(node);
				if( tJson ){
					var json = Object.clone(tJson);

U
unknown 已提交
1271 1272
					if( !this.options.isEdited )json.isReadonly = true;

U
unknown 已提交
1273 1274 1275
					var templateJsonId = json.id;

					var id;
U
unknown 已提交
1276
					var index = this.template.unionMode ? this.options.indexInSection : this.options.index;
U
unknown 已提交
1277 1278 1279 1280 1281 1282
					if( sectionKey ){
						id = this.template.json.id + ".." + sectionKey + ".."+ index + ".." + json.id;
					}else{
						id = this.template.json.id + ".." + index + ".." + json.id;
					}
					json.id = id;
U
unknown 已提交
1283
					node.set("id", id);
U
unknown 已提交
1284

U
unknown 已提交
1285
					if( json.type==="Attachment" || json.type==="AttachmentDg" ){
U
unknown 已提交
1286
						json.type = "AttachmentDg";
U
unknown 已提交
1287
						json.site = this.getAttachmentSite(json, templateJsonId, sectionKey);
U
unknown 已提交
1288 1289
					}

U
unknown 已提交
1290 1291 1292 1293
					if (this.form.all[id]) this.form.all[id] = null;
					if (this.form.forms[id])this.form.forms[id] = null;

					var module = this.form._loadModule(json, node, function () {});
U
unknown 已提交
1294 1295 1296 1297 1298 1299 1300

					if( json.type==="Attachment" || json.type==="AttachmentDg" ){
						module.addEvent("change", function(){
							_self.form.saveFormData();
						}.bind(this))
					}

U
unknown 已提交
1301 1302
					this.form.modules.push(module);

U
unknown 已提交
1303 1304
					this.modules.push(module);
					this.all[id] = module;
U
unknown 已提交
1305
					this.all_templateId[templateJsonId] = module;
U
unknown 已提交
1306

U
unknown 已提交
1307
					if (module.field) {
U
unknown 已提交
1308 1309 1310
						if(this.data.hasOwnProperty(templateJsonId)){
							module.setData(this.data[templateJsonId]);
						}
U
unknown 已提交
1311
						this.allField[id] = module;
U
unknown 已提交
1312
						this.allField_templateId[templateJsonId] = module;
U
unknown 已提交
1313 1314
						this.fields.push( module );
					}
U
unknown 已提交
1315

U
unknown 已提交
1316
					this.setEvents(module, templateJsonId);
U
unknown 已提交
1317 1318 1319

				}
			}
U
unknown 已提交
1320
		}.bind(this));
U
unknown 已提交
1321 1322 1323 1324 1325

		if(this.options.isNew){
			this.data = this.getData();
			this.options.isNew = false;
		}
U
unknown 已提交
1326
	},
U
unknown 已提交
1327 1328 1329
	getModule: function(templateJsonId){
		return this.all_templateId[templateJsonId];
	},
U
unknown 已提交
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
	getAttachmentSite: function(json, templateJsonId, sectionKey){
		//确保site最长为64,否则后台会报错

		var index = this.options.indexInSection || this.options.index;

		var baseSite;
		baseSite =  "." + index + "."  + (json.site || templateJsonId);

		var maxLength;
		var sectionId = "";
		if( sectionKey ){
			maxLength = Math.floor((63 - baseSite.length)/2 );

			sectionId = (sectionKey.length > maxLength) ? sectionKey.substr(sectionKey.length-maxLength, maxLength) : sectionKey;
			sectionId = "." + sectionId;
		}else{
			maxLength = 64 - baseSite.length;
		}

		var templateId = this.template.json.id;
		templateId = (templateId.length > maxLength) ? templateId.substr(templateId.length-maxLength, maxLength) : templateId;

		return templateId + sectionId + baseSite;
	},
U
unknown 已提交
1354 1355 1356 1357
	setEvents: function (module, id) {
		if( this.template.addActionIdList.contains( id )){
			this.addActionList.push( module );
			module.node.addEvent("click", function (ev) {
U
unknown 已提交
1358
				this.template._insertLine( ev, this )
U
unknown 已提交
1359
			}.bind(this))
U
unknown 已提交
1360
			if( !this.template.editable )module.node.hide();
U
unknown 已提交
1361
		}
U
unknown 已提交
1362 1363 1364 1365 1366 1367

		if( this.template.deleteActionIdList.contains(id)){
			this.deleteActionList.push( module );
			module.node.addEvent("click", function (ev) {
				this.template._deleteLine( ev, this )
			}.bind(this))
U
unknown 已提交
1368
			if( !this.template.editable )module.node.hide();
U
unknown 已提交
1369 1370
		}

U
unknown 已提交
1371 1372
		if( this.template.selectorId === id){
			this.selector = module;
U
unknown 已提交
1373
			// module.setData(""); //默认不选择
U
unknown 已提交
1374 1375 1376
			module.node.addEvent("click", function (ev) {
				this.checkSelect();
			}.bind(this))
U
unknown 已提交
1377 1378
			if( !this.template.editable )module.node.hide();
			this.unselect();
U
unknown 已提交
1379
		}
U
unknown 已提交
1380

U
unknown 已提交
1381 1382
		if( this.template.sequenceIdList.contains(id)){
			this.sequenceNodeList.push( module );
U
unknown 已提交
1383
			var indexText = (this.template.unionMode && this.template.json.sequenceBySection) ?  this.options.indexInSectionText : this.options.indexText;
U
unknown 已提交
1384
			if(this.form.getModuleType(module) === "label"){
U
unknown 已提交
1385
				module.node.set("text", indexText );
U
unknown 已提交
1386
			}else{
U
unknown 已提交
1387
				module.set( indexText );
U
unknown 已提交
1388 1389
			}
		}
U
unknown 已提交
1390

U
unknown 已提交
1391 1392 1393
		//???
		// if( this.template.importActionIdList.contains(id))this.importActionList.push( module );
		// if( this.template.exportActionIdList.contains(id))this.exportActionList.push( module );
U
unknown 已提交
1394

U
unknown 已提交
1395 1396
	},
	checkSelect: function () {
U
unknown 已提交
1397 1398 1399 1400 1401 1402
		var selectData = this.selector.getData();
		var selected;
		if(o2.typeOf(selectData)==="array"){
			selected = selectData.contains(this.template.json.selectorSelectedValue);
		}else{
			selected = selectData === this.template.json.selectorSelectedValue;
U
unknown 已提交
1403
		}
U
unknown 已提交
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
		this.selected = selected;
	},
	select: function(){
		this.selected = true;
		if(this.selector)this.selector.setData(this.template.json.selectorSelectedValue);
	},
	unselect: function(){
		this.selected = false;
		if( this.selector.getOptionsObj ){
			var options = this.selector.getOptionsObj();
			var value = "";
			var arr = options.valueList || [];
			for( var i=0; i<arr.length; i++ ){
				var v = arr[i];
				if( v !== this.template.json.selectorSelectedValue ){
					value = v;
					break;
				}
			}
			this.selector.setData(value);
		}else{
			this.selector.setData("")
		}
U
unknown 已提交
1427
	},
U
unknown 已提交
1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
	reload: function(){
		for(var key in this.all){
			var module = this.all[key];
			this.form.modules.erase(module);
			if (this.form.all[key]) delete this.form.all[key];
			if (this.form.forms[key])delete this.form.forms[key];
		}
		this.node.empty();
		this.load();
	},
U
unknown 已提交
1438 1439 1440 1441 1442 1443 1444 1445 1446 1447
	clear: function () { //把module清除掉
		for(var key in this.all){
			var module = this.all[key];
			this.form.modules.erase(module);
			if (this.form.all[key]) delete this.form.all[key];
			if (this.form.forms[key])delete this.form.forms[key];
		}
		this.node.destroy();
	},
	getData: function () {
U
unknown 已提交
1448
		var data = this.data;
U
unknown 已提交
1449
		for( var key in this.allField){
U
unknown 已提交
1450
			var module = this.allField[key];
U
unknown 已提交
1451
			var id = key.split("..").getLast();
U
unknown 已提交
1452
			if( module.json.type==="Attachment" || module.json.type==="AttachmentDg" ){
U
unknown 已提交
1453 1454 1455 1456
				data[id] = module._getBusinessData();
			}else{
				data[id] = module.getData();
			}
U
unknown 已提交
1457 1458
		}
		return data;
U
unknown 已提交
1459 1460 1461
	},
	setData: function (data) {
		this.template._setLineData(this, data);
U
unknown 已提交
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
	},
	deleteAttachment: function(){
		var saveFlag = false;
		for( var key in this.allField){
			var module = this.allField[key];
			if( module.json.type==="Attachment" || module.json.type==="AttachmentDg" ){
				var array = module._getBusinessData();
				(array || []).each(function(d){
					saveFlag = true;
					this.form.workAction.deleteAttachment(d.id, this.form.businessData.work.id);
				}.bind(this))
			}
		}
		return saveFlag;
U
unknown 已提交
1476
	}
U
unknown 已提交
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
});

MWF.xApplication.process.Xform.Datatemplate.Exporter = new Class({
	Implements: [Options, Events],
	options: {
	},
	initialize: function (template, options) {

		this.setOptions(options);

		this.template = template;
		this.form = this.template.form;

	},
	exportToExcel : function () {
		var resultArr = [];
		var titleArr = this.template.json.excelFieldConfig.map(function(config){
			return config.title;
		});
U
unknown 已提交
1496
		if( this.template.unionMode ){
U
unknown 已提交
1497
			titleArr.push( MWF.xApplication.process.Xform.LP.systemField );
U
unknown 已提交
1498
		}
U
unknown 已提交
1499 1500
		resultArr.push( titleArr );

U
unknown 已提交
1501

U
unknown 已提交
1502 1503 1504 1505
		this.template.lineList.each(function (line, index) {
			resultArr.push( this.getLineExportData(line, index) );
		}.bind(this));

U
unknown 已提交
1506 1507 1508
		var colWidthArr = this.getColWidthArray();
		var excelName = this.getExcelName();

U
unknown 已提交
1509 1510 1511
		var arg = {
			data : resultArr,
			colWidthArray : colWidthArr,
U
unknown 已提交
1512
			title : excelName
U
unknown 已提交
1513
		};
U
unknown 已提交
1514 1515
		this.fireEvent("export", [arg]);

U
unknown 已提交
1516 1517
		new MWF.xApplication.process.Xform.Datatemplate.ExcelUtils( this.template ).exportToExcel(
			resultArr,
U
unknown 已提交
1518 1519
			arg.title || excelName,
			colWidthArr,
U
unknown 已提交
1520 1521
			this.getDateIndexArray()  //日期格式列下标
		);
U
unknown 已提交
1522 1523 1524 1525 1526 1527 1528 1529
	},
	getLineExportData: function(line, index ){
		var exportData = [];
		this.template.json.excelFieldConfig.each(function (config) {

			var module = line.all_templateId[config.field];
			var json = module ? module.json : "";

U
unknown 已提交
1530
			if ( !module || !json || !this.isAvaliableField( json ) ) {
U
unknown 已提交
1531 1532 1533 1534 1535
				exportData.push("");
			}else{
				var value = module.getData();
				var text = "";

U
unknown 已提交
1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580

				if( value ){
					switch (module.json.type) {
						case "Org":
						case "Reader":
						case "Author":
						case "Personfield":
						case "Orgfield":
							if (o2.typeOf(value) === "array") {
								var textArray = [];
								value.each(function (item) {
									if (o2.typeOf(item) === "object") {
										textArray.push(item.distinguishedName);
									} else {
										textArray.push(item);
									}
								}.bind(this));
								text = textArray.join(", \n");
							} else if (o2.typeOf(value) === "object") {
								text = value.distinguishedName;
							} else {
								text = value;
							}
							break;
						case "Combox":
						case "Address":
							text = o2.typeOf(value) === "array" ? value.join(", ") : value;
							break;
						case "Checkbox":
							var options = module.getOptionsObj();
							var value = o2.typeOf(value) === "array" ? value : [value];
							var arr = [];
							value.each( function( a, i ){
								var idx = options.valueList.indexOf( a );
								arr.push( idx > -1 ? options.textList[ idx ] : "") ;
							});
							text = arr.join(", ");
							break;
						case "Radio":
						case "Select":
							var options = module.getOptionsObj();
							var idx = options.textList.indexOf( value );
							text = idx > -1 ? options.valueList[ idx ] : "";
							break;
						case "Textarea":
U
unknown 已提交
1581
							text = value;
U
unknown 已提交
1582 1583 1584 1585 1586 1587 1588
							break;
						case "Calendar":
							text = value;
							break;
						default:
							text = value;
							break;
U
unknown 已提交
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
					}
				} else if ( json.type === "Label" && module.node) {
					text = module.node.get("text");
				}

				if( !text && o2.typeOf(text) !== "number" ){
					text = "";
				}

				exportData.push( text );
			}
U
unknown 已提交
1600
		}.bind(this));
U
unknown 已提交
1601 1602 1603
		if( this.template.unionMode ){
			exportData.push( line.options.sectionKey );
		}
U
unknown 已提交
1604
		return exportData;
U
unknown 已提交
1605
	},
U
unknown 已提交
1606 1607
	isAvaliableField : function(json){
		if (["Image","Button","ImageClipper","Attachment","AttachmentDg","Label"].contains( json.type) )return false; //图片,附件,Label不导入导出
U
unknown 已提交
1608 1609 1610 1611 1612 1613 1614
		return true;
	},
	getExcelName: function(){
		var title;
		if( this.form.json.excelName && this.form.json.excelName.code ){
			title = this.form.Macro.exec(this.form.json.excelName.code, this);
		}else{
U
unknown 已提交
1615
			title = MWF.xApplication.process.Xform.LP.datatemplateExportDefaultName;
U
unknown 已提交
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643
		}
		var titleA = title.split(".");
		if( ["xls","xlst"].contains( titleA[titleA.length-1].toLowerCase() ) ){
			titleA.splice( titleA.length-1 );
		}
		title = titleA.join(".");
		return title;
	},
	getColWidthArray : function(){
		var colWidthArr = [];
		this.template.json.excelFieldConfig.each(function (config) {
			var json = this.form.json.moduleList[config.field];
			if ( !json ){
				colWidthArr.push(150);
			}else if ( ["Org","Reader","Author","Personfield","Orgfield"].contains(json.type)) {
				colWidthArr.push(340);
			} else if (json.type === "Address") {
				colWidthArr.push(170);
			} else if (json.type === "Textarea") {
				colWidthArr.push(260);
			} else if (json.type === "Htmleditor") {
				colWidthArr.push(500);
			} else if (json.type === "Calendar") {
				colWidthArr.push(150);
			} else {
				colWidthArr.push(150);
			}
		}.bind(this));
U
unknown 已提交
1644 1645 1646
		if( this.template.unionMode ){
			colWidthArr.push(340);
		}
U
unknown 已提交
1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
		return colWidthArr;
	},
	getDateIndexArray : function(){
		var dateIndexArr = []; //日期格式列下标
		this.template.json.excelFieldConfig.each(function (config, i) {
			var json = this.form.json.moduleList[config.field];
			if (json && json.type === "Calendar") {
				dateIndexArr.push(i);
			}
		}.bind(this));
		return dateIndexArr;
	},

	exportWithImportDataToExcel : function ( columnList, importedData ) {

		var resultArr = [];
U
unknown 已提交
1663 1664 1665 1666 1667 1668
		var titleArr = this.template.json.excelFieldConfig.map(function(config){
			return config.title;
		});
		if( this.template.unionMode ){
			titleArr.push( MWF.xApplication.process.Xform.LP.systemField );
		}
U
unknown 已提交
1669 1670 1671
		titleArr.push( MWF.xApplication.process.Xform.LP.validationInfor );
		resultArr.push( titleArr );

U
unknown 已提交
1672 1673 1674 1675 1676

		// this.template.lineList.each(function (line, index) {
		// 	resultArr.push( this.getLineExportData(line, index) );
		// }.bind(this));

U
unknown 已提交
1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
		importedData.each( function( lineData, lineIndex ){
			var array = [];
			columnList.each( function (obj, i) {
				array.push( ( lineData[ obj.text ] || '' ).replace(/&#10;/g, "\n") );
			});
			array.push( lineData.errorTextListExcel ? lineData.errorTextListExcel.join("\n") : ""  );

			resultArr.push( array );
		}.bind(this));

U
unknown 已提交
1687 1688 1689 1690
		var colWidthArr = this.getColWidthArray();
		colWidthArr.push(300); //提示信息

		var excelName = this.getExcelName();
U
unknown 已提交
1691

U
unknown 已提交
1692 1693 1694 1695 1696 1697
		var arg = {
			data : resultArr,
			colWidthArray : colWidthArr,
			title : excelName
		};
		this.fireEvent("export", [arg]);
U
unknown 已提交
1698

U
unknown 已提交
1699 1700 1701 1702 1703 1704
		new MWF.xApplication.process.Xform.Datatemplate.ExcelUtils( this.template ).exportToExcel(
			resultArr,
			arg.title || excelName,
			colWidthArr,
			this.getDateIndexArray()  //日期格式列下标
		);
U
unknown 已提交
1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
	}
});

MWF.xApplication.process.Xform.Datatemplate.Importer = new Class({
	Implements: [Options, Events],
	options: {
	},
	initialize: function (template, options) {

		this.setOptions(options);

		this.template = template;
		this.form = this.template.form;

	},
U
unknown 已提交
1720 1721
	isAvaliableField : function(json, module, type){
		if (["Image","Button","ImageClipper","Attachment","AttachmentDg","Label"].contains( json.type) )return false; //图片,附件,Label不导入导出
U
unknown 已提交
1722 1723 1724
		return true;
	},
	importFromExcel : function () {
U
unknown 已提交
1725 1726 1727
		var fieldArray = this.getFieldArray();
		var dateColArray = this.getDateIndexArray(); //日期列
		var orgTitleArray = this.getOrgTitleArray();
U
unknown 已提交
1728

U
unknown 已提交
1729
		new MWF.xApplication.process.Xform.Datatemplate.ExcelUtils( this.template ).upload( dateColArray, function (data) {
U
unknown 已提交
1730 1731

			var checkAndImport = function () {
U
unknown 已提交
1732 1733
				if( !this.checkData( fieldArray, data ) ){
					this.openErrorDlg( fieldArray, data );
U
unknown 已提交
1734
				}else{
U
unknown 已提交
1735
					this.importData( fieldArray, data )
U
unknown 已提交
1736
				}
U
unknown 已提交
1737
				this.destroySimulateModule();
U
unknown 已提交
1738 1739
			}.bind(this);

U
unknown 已提交
1740 1741
			if( orgTitleArray.length > 0 ){
				this.listAllOrgData( orgTitleArray, data, function () {
U
unknown 已提交
1742 1743 1744 1745 1746 1747 1748 1749 1750
					checkAndImport();
				}.bind(this));
			}else{
				checkAndImport();
			}


		}.bind(this));
	},
U
unknown 已提交
1751
	destroySimulateModule: function(){
U
unknown 已提交
1752
		if( !this.simelateModuleMap )return;
U
unknown 已提交
1753 1754 1755 1756 1757 1758 1759 1760
		var keys = Object.keys(this.simelateModuleMap);
		keys.each(function (key, i) {
			var module = this.simelateModuleMap[key];
			if( module ){
				var id = module.json.id;
				if( this.form.businessData.data.hasOwnProperty(id) )delete this.form.businessData.data[id];
				delete this.simelateModuleMap[key];
			}
U
unknown 已提交
1761
		}.bind(this))
U
unknown 已提交
1762 1763 1764 1765 1766 1767
		this.simelateModuleMap = null;

		if(this.simulateNode){
			this.simulateNode.destroy();
			this.simulateNode = null;
		}
U
unknown 已提交
1768 1769
	},
	loadSimulateModule: function(){
U
unknown 已提交
1770 1771 1772
		if( this.simelateModuleMap ){
			this.destroySimulateModule();
		}
U
unknown 已提交
1773 1774 1775
		//加载模拟字段
		this.simelateModuleMap = {};
		this.simulateNode = new Element("div").inject(this.template.node);
U
unknown 已提交
1776
		this.simulateNode.hide();
U
unknown 已提交
1777 1778 1779 1780 1781
		this.simulateNode.set("html", this.template.templateHtml);
		var moduleNodes = this.form._getModuleNodes(this.simulateNode);
		moduleNodes.each(function (node) {
			if (node.get("MWFtype") !== "form") {
				var _self = this;
U
unknown 已提交
1782

U
unknown 已提交
1783 1784 1785
				var tJson = this.form._getDomjson(node);
				if( tJson && this.isAvaliableField(tJson) ){
					var json = Object.clone(tJson);
U
unknown 已提交
1786

U
unknown 已提交
1787
					var templateJsonId = json.id;
U
unknown 已提交
1788

U
unknown 已提交
1789 1790 1791 1792 1793 1794
					json.id = "dtSimulate_"+json.id;
					node.set("id", json.id);

					if (!MWF["APP" + json.type]) {
						MWF.xDesktop.requireApp("process.Xform", json.type, null, false);
					}
U
unknown 已提交
1795
					var module = new MWF["APP" + json.type](node, json, this.form);
U
unknown 已提交
1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838

					this.simelateModuleMap[templateJsonId] = module;

					module.load();

				}
			}
		}.bind(this));
	},
	getFieldArray: function(){
		this.loadSimulateModule();
		var fieldArray = []; //日期格式列下标
		this.template.json.excelFieldConfig.each(function (config, i) {
			fieldArray.push({
				"text": config.title,
				"field": config.field,
				"index": i,
				"module": this.simelateModuleMap[config.field],
				"json": this.form.json.moduleList[config.field]
			})
		}.bind(this));
		return fieldArray;
	},
	getDateIndexArray : function(){
		var dateIndexArr = []; //日期格式列下标
		this.template.json.excelFieldConfig.each(function (config, i) {
			var json = this.form.json.moduleList[config.field];
			if (json && json.type === "Calendar") {
				dateIndexArr.push(i);
			}
		}.bind(this));
		return dateIndexArr;
	},
	getOrgTitleArray : function(){
		var orgTitleArr = []; //日期格式列下标
		this.template.json.excelFieldConfig.each(function (config, i) {
			var json = this.form.json.moduleList[config.field];
			if (json && ["Org","Reader","Author","Personfield","Orgfield"].contains(json.type) ) {
				orgTitleArr.push(config.title);
			}
		}.bind(this));
		return orgTitleArr;
	},
U
unknown 已提交
1839 1840 1841 1842 1843 1844 1845 1846
	parseImportedData: function(fieldArray, idata, ignoreSectionKey){
		var data;
		var sectionData;
		if( !ignoreSectionKey && this.template.unionMode ){
			sectionData = {};
		}else{
			data = [];
		}
U
unknown 已提交
1847

U
unknown 已提交
1848
		var sectionKey;
U
unknown 已提交
1849

U
unknown 已提交
1850
		idata.each( function( ilineData ){
U
unknown 已提交
1851 1852
			var lineData = {};

U
unknown 已提交
1853
			fieldArray.each( function (obj, i) {
U
unknown 已提交
1854 1855
				var index = obj.index;
				var module = obj.module;
U
unknown 已提交
1856
				var json = obj.json;
U
unknown 已提交
1857 1858
				var text = obj.text;

U
unknown 已提交
1859
				var d = ilineData[text] || "";
U
unknown 已提交
1860 1861

				var value;
U
unknown 已提交
1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915
				if( d === "" || d === undefined || d === null ){
					value = "";
				}else{
					switch (json.type) {
						case "Org":
						case "Reader":
						case "Author":
						case "Personfield":
						case "Orgfield":
							var arr = d.split(/\s*,\s*/g ); //空格,空格
							if( arr.length === 0 ){
								value = this.getOrgData( d );
							}else{
								value = [];
								arr.each( function(d, idx){
									var obj = this.getOrgData( d );
									value.push( obj );
								}.bind(this));
							}
							break;
						case "Combox":
						case "Address":
							arr = d.split(/\s*,\s*/g ); //空格,空格
							value = arr.length === 0  ? arr[0] : arr;
							break;
						case "Checkbox":
							arr = d.split(/\s*,\s*/g ); //空格,空格
							var options = module.getOptionsObj();
							arr.each( function( a, i ){
								var idx = options.textList.indexOf( a );
								arr[ i ] = idx > -1 ? options.valueList[ idx ] : a;
							});
							value = arr.length === 1  ? arr[0] : arr;
							break;
						case "Radio":
						case "Select":
							value = d.replace(/&#10;/g,""); //换行符&#10;
							var options = module.getOptionsObj();
							var idx = options.textList.indexOf( value );
							value = idx > -1 ? options.valueList[ idx ] : value;
							break;
						case "Textarea":
							value = d.replace(/&#10;/g,"\n"); //换行符&#10;
							break;
						case "Calendar":
							value = d.replace(/&#10;/g,""); //换行符&#10;
							if( value ){
								var format;
								if (!json.format){
									if (json.selectType==="datetime" || json.selectType==="time"){
										format = (json.selectType === "time") ? "%H:%M" : (Locale.get("Date").shortDate + " " + "%H:%M")
									}else{
										format = Locale.get("Date").shortDate;
									}
U
unknown 已提交
1916
								}else{
U
unknown 已提交
1917
									format = json.format;
U
unknown 已提交
1918
								}
U
unknown 已提交
1919
								value = Date.parse( value ).format( format );
U
unknown 已提交
1920
							}
U
unknown 已提交
1921 1922 1923 1924 1925
							break;
						default:
							value = d.replace(/&#10;/g,""); //换行符&#10;
							break;
					}
U
unknown 已提交
1926 1927
				}

U
unknown 已提交
1928
				lineData[ json.id ] = value;
U
unknown 已提交
1929 1930 1931

			}.bind(this));

U
unknown 已提交
1932
			if(sectionData){
U
unknown 已提交
1933
				sectionKey = ilineData[ MWF.xApplication.process.Xform.LP.systemField ];
U
unknown 已提交
1934 1935 1936 1937 1938
				if( !sectionData[sectionKey])sectionData[sectionKey] = [];
				sectionData[sectionKey].push( lineData );
			}else{
				data.push( lineData );
			}
U
unknown 已提交
1939 1940
		}.bind(this));

U
unknown 已提交
1941
		return sectionData || data;
U
unknown 已提交
1942 1943 1944 1945 1946
	},
	importData: function(fieldArray, idata){

		var data = this.parseImportedData(fieldArray, idata);

U
unknown 已提交
1947
		this.template.fireEvent("import", [data] );
U
unknown 已提交
1948

U
unknown 已提交
1949
		this.template.setData( data );
U
unknown 已提交
1950 1951 1952
		this.form.notice( MWF.xApplication.process.Xform.LP.importSuccess );

	},
U
unknown 已提交
1953
	openErrorDlg : function(fieldArray, eData){
U
unknown 已提交
1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965
		var _self = this;

		var objectToString = function (obj, type) {
			if(!obj)return "";
			var arr = [];
			Object.each(obj,  function (value, key) {
				if( type === "style" ){
					arr.push( key + ":"+ value +";" )
				}else{
					arr.push( key + "='"+ value +"'" )
				}
			})
U
unknown 已提交
1966
			return arr.join(" ")
U
unknown 已提交
1967 1968
		}

U
unknown 已提交
1969
		var htmlArray = ["<table "+ objectToString( this.template.json.impExpTableProperties ) +" style='"+objectToString( this.template.json.impExpTableStyles, "style" )+"'>"];
U
unknown 已提交
1970

U
unknown 已提交
1971
		var titleStyle = objectToString(this.template.json.impExpTableTitleStyles, "style");
U
unknown 已提交
1972 1973
		htmlArray.push("<tr>");
		fieldArray.each(function (obj, i) {
U
unknown 已提交
1974 1975
			htmlArray.push( "<th style='"+titleStyle+"'>"+obj.text+"</th>" );
		});
U
unknown 已提交
1976 1977
		htmlArray.push("<th style='"+titleStyle+"'> "+MWF.xApplication.process.Xform.LP.validationInfor +"</th>");
		htmlArray.push("</tr>" );
U
unknown 已提交
1978

U
unknown 已提交
1979
		var contentStyles = Object.clone( this.template.json.impExpTableContentStyles );
U
unknown 已提交
1980 1981 1982
		if( !contentStyles[ "border-bottom" ] && !contentStyles[ "border" ] )contentStyles[ "border-bottom" ] = "1px solid #eee";
		var contentStyle = objectToString( Object.merge( contentStyles, {"text-align":"left"}) , "style" );

U
unknown 已提交
1983
		eData.each( function( lineData, lineIndex ){
U
unknown 已提交
1984 1985

			htmlArray.push( "<tr>" );
U
unknown 已提交
1986
			fieldArray.each( function (obj, i) {
U
unknown 已提交
1987 1988 1989 1990 1991 1992 1993 1994
				htmlArray.push( "<td style='"+contentStyle+"'>"+ ( lineData[ obj.text ] || '' ).replace(/&#10;/g,"<br/>") +"</td>" ); //换行符&#10;
			});
			htmlArray.push( "<td style='"+contentStyle+"'>"+( lineData.errorTextList ? lineData.errorTextList.join("<br/>") : "" )+"</td>" );
			htmlArray.push( "</tr>" );

		}.bind(this));
		htmlArray.push( "</table>" );

U
unknown 已提交
1995 1996 1997 1998 1999
		var width = this.template.json.impExpDlgWidth || 1000;
		var height = this.template.json.impExpDlgHeight || 700;
		width = width.toInt();
		height = height.toInt();

U
unknown 已提交
2000 2001 2002 2003 2004 2005 2006
		var div = new Element("div", { style : "padding:10px;", html : htmlArray.join("") });
		var dlg = o2.DL.open({
			"style" : this.form.json.dialogStyle || "user",
			"title": MWF.xApplication.process.Xform.LP.importFail,
			"content": div,
			"offset": {"y": 0},
			"isMax": true,
U
unknown 已提交
2007 2008
			"width": width,
			"height": height,
U
unknown 已提交
2009 2010 2011 2012
			"buttonList": [
				{
					"type": "exportWithError",
					"text": MWF.xApplication.process.Xform.LP.datagridExport,
U
unknown 已提交
2013
					"action": function () { _self.exportWithImportDataToExcel(fieldArray, eData); }
U
unknown 已提交
2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026
				},
				{
					"type": "cancel",
					"text": MWF.LP.process.button.cancel,
					"action": function () { dlg.close(); }
				}
			],
			"onPostClose": function(){
				dlg = null;
			}.bind(this)
		});

	},
U
unknown 已提交
2027 2028 2029 2030
	exportWithImportDataToExcel: function(fieldArray, eData){
		var exporter = new MWF.xApplication.process.Xform.Datatemplate.Exporter(this.template);
		exporter.exportWithImportDataToExcel(fieldArray, eData)
	},
U
unknown 已提交
2031
	checkData : function( fieldArray, idata ){
U
unknown 已提交
2032 2033 2034 2035 2036
		var flag = true;

		var lp = MWF.xApplication.process.Xform.LP;
		var columnText =  lp.importValidationColumnText;
		var columnTextExcel = lp.importValidationColumnTextExcel;
U
unknown 已提交
2037
		var excelUtil = new MWF.xApplication.process.Xform.Datatemplate.ExcelUtils( this.template );
U
unknown 已提交
2038

U
unknown 已提交
2039
		var parsedData = this.parseImportedData(fieldArray, idata, true);
U
unknown 已提交
2040 2041

		idata.each( function(lineData, lineIndex){
U
unknown 已提交
2042 2043 2044 2045

			var errorTextList = [];
			var errorTextListExcel = [];

U
unknown 已提交
2046 2047
			var parsedLineData = (parsedData && parsedData[lineIndex]) ? parsedData[lineIndex] : [];

U
unknown 已提交
2048
			fieldArray.each( function (obj, i) {
U
unknown 已提交
2049
				var index = obj.index;
U
unknown 已提交
2050
				var json = obj.json;
U
unknown 已提交
2051 2052 2053 2054 2055 2056 2057
				var module = obj.module;
				var text = obj.text;

				var colInfor = columnText.replace( "{n}", index );
				var colInforExcel = columnTextExcel.replace( "{n}", excelUtil.index2ColName( index-1 ) );

				var d = lineData[text] || "";
U
unknown 已提交
2058
				var parsedD = parsedLineData[json.id] || "";
U
unknown 已提交
2059

U
unknown 已提交
2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071
				if(d){

					switch (json && json.type) {
						case "Org":
						case "Reader":
						case "Author":
						case "Personfield":
						case "Orgfield":
							var arr = d.split(/\s*,\s*/g ); //空格,空格
							arr.each( function(d, idx){
								var obj = this.getOrgData( d );
								if( obj.errorText ){
U
unknown 已提交
2072 2073
									errorTextList.push( colInfor + obj.errorText + lp.fullstop );
									errorTextListExcel.push( colInforExcel + obj.errorText + lp.fullstop );
U
unknown 已提交
2074 2075 2076 2077 2078 2079 2080
								}
							}.bind(this));
							break;
						case "Number":
							if (parseFloat(d).toString() === "NaN"){
								errorTextList.push( colInfor + d + lp.notValidNumber + lp.fullstop );
								errorTextListExcel.push( colInforExcel + d + lp.notValidNumber + lp.fullstop );
U
unknown 已提交
2081
							}
U
unknown 已提交
2082 2083 2084 2085 2086 2087 2088 2089 2090 2091
							break;
						case "Calendar":
							if( !( isNaN(d) && !isNaN(Date.parse(d) ))){
								errorTextList.push(colInfor + d + lp.notValidDate + lp.fullstop );
								errorTextListExcel.push( colInforExcel + d + lp.notValidDate + lp.fullstop );
							}
							break;
						default:
							break;
					}
U
unknown 已提交
2092
				}
U
unknown 已提交
2093
				if (module && module.setData && json.type !== "Address"){
U
unknown 已提交
2094
					var hasError = false;
U
unknown 已提交
2095
					if(["Org","Reader","Author","Personfield","Orgfield"].contains(json.type)){
U
unknown 已提交
2096 2097
						if(o2.typeOf(parsedD)==="array" && parsedD.length){
							hasError = parsedD.some(function (item) { return item.errorText; })
U
unknown 已提交
2098 2099
						}
					}
U
unknown 已提交
2100 2101 2102 2103 2104 2105 2106 2107
					if(!hasError){
						module.setData(parsedD);
						module.validationMode();
						if (!module.validation() && module.errNode){
							errorTextList.push(colInfor + module.errNode.get("text"));
							errorTextListExcel.push( colInforExcel + module.errNode.get("text"));
							module.errNode.destroy();
						}
U
unknown 已提交
2108 2109 2110
					}
				}
			}.bind(this));
U
unknown 已提交
2111
			if( this.template.unionMode ){
U
unknown 已提交
2112
				if( !lineData[ MWF.xApplication.process.Xform.LP.systemField ] && !lineData["系统字段"] ){
U
unknown 已提交
2113 2114 2115
					var colInfor = columnText.replace( "{n}", fieldArray.length+1 );
					var colInforExcel = columnTextExcel.replace( "{n}", excelUtil.index2ColName(fieldArray.length) );

U
unknown 已提交
2116 2117
					errorTextList.push( colInfor + MWF.xApplication.process.Xform.LP.systemFieldEmptyNotice );
					errorTextList.push( colInforExcel + MWF.xApplication.process.Xform.LP.systemFieldEmptyNotice );
U
unknown 已提交
2118 2119
				}
			}
U
unknown 已提交
2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130

			if(errorTextList.length>0){
				lineData.errorTextList = errorTextList;
				lineData.errorTextListExcel = errorTextListExcel;
				flag = false;
			}

		}.bind(this));

		var arg = {
			validted : flag,
U
unknown 已提交
2131
			data : idata
U
unknown 已提交
2132
		};
U
unknown 已提交
2133
		this.template.fireEvent( "validImport", [arg] );
U
unknown 已提交
2134 2135 2136

		return arg.validted;
	},
U
unknown 已提交
2137
	getOrgData : function( str ){
U
unknown 已提交
2138 2139 2140 2141
		str = str.trim();
		var flag = str.substr(str.length-2, 2);
		switch (flag.toLowerCase()){
			case "@i":
U
unknown 已提交
2142
				return this.identityMap[str] || {"errorText": str + MWF.xApplication.process.Xform.LP.notExistInSystem };
U
unknown 已提交
2143
			case "@p":
U
unknown 已提交
2144
				return this.personMap[str] || {"errorText":  str + MWF.xApplication.process.Xform.LP.notExistInSystem };
U
unknown 已提交
2145
			case "@u":
U
unknown 已提交
2146
				return this.unitMap[str] ||  {"errorText":  str + MWF.xApplication.process.Xform.LP.notExistInSystem };
U
unknown 已提交
2147
			case "@g":
U
unknown 已提交
2148
				return this.groupMap[str] ||  {"errorText":  str + MWF.xApplication.process.Xform.LP.notExistInSystem };
U
unknown 已提交
2149
			default:
U
unknown 已提交
2150 2151 2152 2153
				return this.identityMap[str] ||
					this.personMap[str] ||
					this.unitMap[str] ||
					this.groupMap[str] ||
U
unknown 已提交
2154 2155 2156 2157
					{"errorText":  str + MWF.xApplication.process.Xform.LP.notExistInSystem };

		}
	},
U
unknown 已提交
2158
	listAllOrgData : function (orgTitleList, iData, callback) {
U
unknown 已提交
2159 2160
		var identityList = [], personList = [], unitList = [], groupList = [];
		if( orgTitleList.length > 0 ){
U
unknown 已提交
2161
			iData.each( function( lineData, lineIndex ){
U
unknown 已提交
2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197
				// if( lineIndex === 0 )return;

				orgTitleList.each( function (title, index) {

					if( !lineData[title] )return;

					var arr = lineData[title].split(/\s*,\s*/g );
					arr.each( function( a ){
						a = a.trim();
						var flag = a.substr(a.length-2, 2);
						switch (flag.toLowerCase()){
							case "@i":
								identityList.push( a ); break;
							case "@p":
								personList.push( a ); break;
							case "@u":
								unitList.push( a ); break;
							case "@g":
								groupList.push( a ); break;
							default:
								identityList.push( a );
								personList.push( a );
								unitList.push( a );
								groupList.push( a );
								break;
						}
					})
				})
			});
			var identityLoaded, personLoaded, unitLoaded, groupLoaded;
			var check = function () {
				if( identityLoaded && personLoaded && unitLoaded && groupLoaded ){
					if(callback)callback();
				}
			};

U
unknown 已提交
2198
			this.identityMap = {};
U
unknown 已提交
2199 2200
			if( identityList.length ){
				o2.Actions.load("x_organization_assemble_express").IdentityAction.listObject({ identityList : identityList }, function (json) {
U
unknown 已提交
2201
					json.data.each( function (d) { this.identityMap[ d.matchKey ] = d; }.bind(this));
U
unknown 已提交
2202 2203 2204 2205 2206 2207 2208 2209
					identityLoaded = true;
					check();
				}.bind(this))
			}else{
				identityLoaded = true;
				check();
			}

U
unknown 已提交
2210
			this.personMap = {};
U
unknown 已提交
2211 2212
			if( personList.length ){
				o2.Actions.load("x_organization_assemble_express").PersonAction.listObject({ personList : personList }, function (json) {
U
unknown 已提交
2213
					json.data.each( function (d) { this.personMap[ d.matchKey ] = d; }.bind(this));
U
unknown 已提交
2214 2215 2216 2217 2218 2219 2220 2221
					personLoaded = true;
					check();
				}.bind(this))
			}else{
				personLoaded = true;
				check();
			}

U
unknown 已提交
2222
			this.unitMap = {};
U
unknown 已提交
2223 2224
			if( unitList.length ){
				o2.Actions.load("x_organization_assemble_express").UnitAction.listObject({ unitList : unitList }, function (json) {
U
unknown 已提交
2225
					json.data.each( function (d) { this.unitMap[ d.matchKey ] = d; }.bind(this));
U
unknown 已提交
2226 2227 2228 2229 2230 2231 2232 2233
					unitLoaded = true;
					check();
				}.bind(this))
			}else{
				unitLoaded = true;
				check();
			}

U
unknown 已提交
2234
			this.groupMap = {};
U
unknown 已提交
2235 2236
			if( groupList.length ){
				o2.Actions.load("x_organization_assemble_express").GroupAction.listObject({ groupList : groupList }, function (json) {
U
unknown 已提交
2237
					json.data.each( function (d) { this.groupMap[ d.matchKey ] = d; }.bind(this));
U
unknown 已提交
2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249
					groupLoaded = true;
					check();
				}.bind(this))
			}else{
				groupLoaded = true;
				check();
			}
		}
	}
});

MWF.xApplication.process.Xform.Datatemplate.ExcelUtils = new Class({
U
unknown 已提交
2250 2251 2252
	initialize: function( datatemplate ){
		this.datatemplate = datatemplate;
		this.form = datatemplate.form;
U
unknown 已提交
2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347
		if (!FileReader.prototype.readAsBinaryString) {
			FileReader.prototype.readAsBinaryString = function (fileData) {
				var binary = "";
				var pt = this;
				var reader = new FileReader();
				reader.onload = function (e) {
					var bytes = new Uint8Array(reader.result);
					var length = bytes.byteLength;
					for (var i = 0; i < length; i++) {
						binary += String.fromCharCode(bytes[i]);
					}
					//pt.result  - readonly so assign binary
					pt.content = binary;
					pt.onload();
				};
				reader.readAsArrayBuffer(fileData);
			}
		}
	},
	_loadResource : function( callback ){
		if( !window.XLSX || !window.xlsxUtils ){
			var uri = "../x_component_Template/framework/xlsx/xlsx.full.js";
			var uri2 = "../x_component_Template/framework/xlsx/xlsxUtils.js";
			COMMON.AjaxModule.load(uri, function(){
				COMMON.AjaxModule.load(uri2, function(){
					callback();
				}.bind(this))
			}.bind(this))
		}else{
			callback();
		}
	},
	_openDownloadDialog: function(url, saveName){
		/**
		 * 通用的打开下载对话框方法,没有测试过具体兼容性
		 * @param url 下载地址,也可以是一个blob对象,必选
		 * @param saveName 保存文件名,可选
		 */
		if( Browser.name !== 'ie' ){
			if(typeof url == 'object' && url instanceof Blob){
				url = URL.createObjectURL(url); // 创建blob地址
			}
			var aLink = document.createElement('a');
			aLink.href = url;
			aLink.download = saveName || ''; // HTML5新增的属性,指定保存文件名,可以不要后缀,注意,file:///模式下不会生效
			var event;
			if(window.MouseEvent && typeOf( window.MouseEvent ) == "function" ) event = new MouseEvent('click');
			else
			{
				event = document.createEvent('MouseEvents');
				event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
			}
			aLink.dispatchEvent(event);
		}else{
			window.navigator.msSaveBlob( url, saveName);
		}
	},

	index2ColName : function( index ){
		if (index < 0) {
			return null;
		}
		var num = 65;// A的Unicode码
		var colName = "";
		do {
			if (colName.length > 0)index--;
			var remainder = index % 26;
			colName =  String.fromCharCode(remainder + num) + colName;
			index = (index - remainder) / 26;
		} while (index > 0);
		return colName;
	},

	upload : function ( dateColIndexArray, callback ) {
		var dateColArray = [];
		dateColIndexArray.each( function (idx) {
			dateColArray.push( this.index2ColName( idx ));
		}.bind(this))


		var uploadFileAreaNode = new Element("div");
		var html = "<input name=\"file\" type=\"file\" accept=\"csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel\" />";
		uploadFileAreaNode.set("html", html);

		var fileUploadNode = uploadFileAreaNode.getFirst();
		fileUploadNode.addEvent("change", function () {
			var files = fileNode.files;
			if (files.length) {
				var file = files.item(0);
				if( file.name.indexOf(" ") > -1 ){
					this.form.notice( MWF.xApplication.process.Xform.LP.uploadedFilesCannotHaveSpaces, "error");
					return false;
				}

				//第三个参数是日期的列
U
unknown 已提交
2348
				this.importFromExcel( file, function(json){
U
unknown 已提交
2349 2350 2351 2352 2353 2354 2355 2356 2357 2358
					//json为导入的结果
					if(callback)callback(json);
					uploadFileAreaNode.destroy();
				}.bind(this), dateColArray ); //["E","F"]

			}
		}.bind(this));
		var fileNode = uploadFileAreaNode.getFirst();
		fileNode.click();
	},
U
unknown 已提交
2359
	exportToExcel : function(array, fileName, colWidthArr, dateIndexArray){
U
unknown 已提交
2360 2361 2362
		// var array = [["姓名","性别","学历","专业","出生日期","毕业日期"]];
		// array.push([ "张三","男","大学本科","计算机","2001-1-2","2019-9-2" ]);
		// array.push([ "李四","男","大学专科","数学","1998-1-2","2018-9-2" ]);
U
unknown 已提交
2363
		// this.exportToExcel(array, "导出数据"+(new Date).format("db"));
U
unknown 已提交
2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430
		this._loadResource( function(){
			var data = window.xlsxUtils.format2Sheet(array, 0, 0, null);//偏移3行按keyMap顺序转换
			var wb = window.xlsxUtils.format2WB(data, "sheet1", undefined);
			var wopts = { bookType: 'xlsx', bookSST: false, type: 'binary' };
			var dataInfo = wb.Sheets[wb.SheetNames[0]];

			var widthArray = [];
			array[0].each( function( v, i ){ //设置标题行样式

				if( !colWidthArr )widthArray.push( {wpx: 100} );

				var at = String.fromCharCode(97 + i).toUpperCase();
				var di = dataInfo[at+"1"];
				// di.v = v;
				// di.t = "s";
				di.s = {  //设置副标题样式
					font: {
						//name: '宋体',
						sz: 12,
						color: {rgb: "#FFFF0000"},
						bold: true,
						italic: false,
						underline: false
					},
					alignment: {
						horizontal: "center" ,
						vertical: "center"
					}
				};
			}.bind(this));

			if( dateIndexArray && dateIndexArray.length ){
				dateIndexArray.each( function( value, index ){
					dateIndexArray[ index ] = this.index2ColName(value);
				}.bind(this))
			}

			for( var key in dataInfo ){
				//设置所有样式,wrapText=true 后 /n会被换行
				if( key.substr(0, 1) !== "!" ){
					var di = dataInfo[key];
					if( !di.s )di.s = {};
					if( !di.s.alignment )di.s.alignment = {};
					di.s.alignment.wrapText = true;

					if( dateIndexArray && dateIndexArray.length ){
						var colName = key.replace(/\d+/g,''); //清除数字
						var rowNum = key.replace( colName, '');
						if( rowNum > 1 && dateIndexArray.contains( colName ) ){
							//di.s.numFmt = "yyyy-mm-dd HH:MM:SS"; //日期列 两种方式都可以
							di.z = 'yyyy-mm-dd HH:MM:SS'; //日期列
						}
					}
				}

			}

			if( colWidthArr ){
				colWidthArr.each( function (w) {
					widthArray.push( {wpx: w} );
				})
			}
			dataInfo['!cols'] = widthArray; //列宽度

			this._openDownloadDialog(window.xlsxUtils.format2Blob(wb), fileName +".xlsx");
		}.bind(this))
	},
U
unknown 已提交
2431
	importFromExcel : function( file, callback, dateColArray ){
U
unknown 已提交
2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495
		this._loadResource( function(){
			var reader = new FileReader();
			var workbook, data;
			reader.onload = function (e) {
				//var data = data.content;
				if (!e) {
					data = reader.content;
				}else {
					data = e.target.result;
				}
				workbook = window.XLSX.read(data, { type: 'binary' });
				//wb.SheetNames[0]是获取Sheets中第一个Sheet的名字
				//wb.Sheets[Sheet名]获取第一个Sheet的数据
				var sheet = workbook.SheetNames[0];
				if (workbook.Sheets.hasOwnProperty(sheet)) {
					// fromTo = workbook.Sheets[sheet]['!ref'];
					// console.log(fromTo);
					var worksheet = workbook.Sheets[sheet];

					if( dateColArray && typeOf(dateColArray) == "array" && dateColArray.length ){
						var rowCount;
						if( worksheet['!range'] ){
							rowCount = worksheet['!range'].e.r;
						}else{
							var ref = worksheet['!ref'];
							var arr = ref.split(":");
							if(arr.length === 2){
								rowCount = parseInt( arr[1].replace(/[^0-9]/ig,"") );
							}
						}
						if( rowCount ){
							for( var i=0; i<dateColArray.length; i++ ){
								for( var j=1; j<=rowCount; j++ ){
									var cell = worksheet[ dateColArray[i]+j ];
									if( cell ){
										delete cell.w; // remove old formatted text
										cell.z = 'yyyy-mm-dd'; // set cell format
										window.XLSX.utils.format_cell(cell); // this refreshes the formatted text.
									}
								}
							}
						}
					}

					var json = window.XLSX.utils.sheet_to_json( worksheet );
					//var data = window.XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheet], {dateNF:'YYYY-MM-DD'});
					if(callback)callback(json);
					// console.log(JSON.stringify(json));
					// break; // 如果只取第一张表,就取消注释这行
				}
				// for (var sheet in workbook.Sheets) {
				//     if (workbook.Sheets.hasOwnProperty(sheet)) {
				//         fromTo = workbook.Sheets[sheet]['!ref'];
				//         console.log(fromTo);
				//         var json = window.XLSX.utils.sheet_to_json(workbook.Sheets[sheet]);
				//         console.log(JSON.stringify(json));
				//         // break; // 如果只取第一张表,就取消注释这行
				//     }
				// }
			};
			reader.readAsBinaryString(file);
		})
	}
});
U
unknown 已提交
2496