/**
* 数据表格数据结构.
* @typedef {array} datatabledata
* @example
{ //数据表格数据条目
"data": [
{
"org": [{
"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"
}
]
}
...
],
"total": {
"number": 222, //总计采用字段id
"textfield": 2
}
}
*/
mwf.xdesktop.requireapp("process.xform", "$module", null, false);
/** @class datatablepc 数据表格组件。表格形式的多行数据编辑组件。
* @o2cn 数据表格pc端
* @example
* //可以在脚本中获取该组件
* //方法1:
* var datatable = this.form.get("name"); //获取组件
* //方法2
* var datatable = this.target; //在组件事件脚本中获取
* @extends mwf.xapplication.process.xform.$module
* @o2category formcomponents
* @since v6.2
* @o2range {process|cms|portal}
* @hideconstructor
*/
mwf.xapplication.process.xform.datatablepc = new class(
/** @lends mwf.xapplication.process.xform.datatablepc# */
{
implements: [events],
extends: mwf.app$module,
isedit: false,
options: {
/**
* 所有内容加载后执行(包括异步加载)。
* @event mwf.xapplication.process.xform.datatablepc#afterload
* @see {@link https://www.yuque.com/o2oa/ixsnyt/hm5uft#i0zts|组件事件说明}
*/
/**
* 每初始化一个条目,但未加载的时候触发,通过this.event可以获取条目对象。
* @event mwf.xapplication.process.xform.datatablepc#beforeloadline
* @see {@link https://www.yuque.com/o2oa/ixsnyt/hm5uft#i0zts|组件事件说明}
*/
/**
* 每一个条目加载后时候触发,通过this.event可以获取条目对象。
* @event mwf.xapplication.process.xform.datatablepc#afterloadline
* @see {@link https://www.yuque.com/o2oa/ixsnyt/hm5uft#i0zts|组件事件说明}
*/
/**
* 数据表格改变时触发。通过this.event.lines可以获取修改的条目数组,this.event.type可以获得修改的类型。
*
*
*
*
*
*
*
*
* this.event.type | 触发类型 | this.event.lines |
---|
addline | 添加一行 | 添加的行数组 |
deleteline | 删除一行 | 删除的行数组 |
editcomplete | 某行完成编辑(点击当前编辑行前面的√执行。同时编辑多行忽略) | 编辑的行数组 |
editmodule | 字段值改变时(同时编辑多行触发此事件,每次编辑单行忽略) | this.event.lines为编辑的行数组 this.event.module为修改的字段 |
move | 通过向上箭头调整行顺序 | 数据表格所有行 |
import | 导入数据后 | 数据表格所有行 |
* @event mwf.xapplication.process.xform.datatablepc#change
* @see {@link https://www.yuque.com/o2oa/ixsnyt/hm5uft#i0zts|组件事件说明}
*/
/**
* 添加条目时触发。通过this.event.line可以获取对应的条目对象,this.event.ev可以获得事件触发的event。
* @event mwf.xapplication.process.xform.datatablepc#addline
* @see {@link https://www.yuque.com/o2oa/ixsnyt/hm5uft#i0zts|组件事件说明}
*/
/**
* 编辑条目时触发(同时编辑多行不触发此事件)。通过this.event可以获取对应的条目对象。
* @event mwf.xapplication.process.xform.datatablepc#editline
* @see {@link https://www.yuque.com/o2oa/ixsnyt/hm5uft#i0zts|组件事件说明}
*/
/**
* 完成编辑条目时触发(点击当前编辑行前面的√执行。同时编辑多行不触发此事件)。通过this.event可以获取对应的条目对象。
* @event mwf.xapplication.process.xform.datatablepc#completelineedit
* @see {@link https://www.yuque.com/o2oa/ixsnyt/hm5uft#i0zts|组件事件说明}
*/
/**
* 取消编辑条目时触发(点击当前编辑行前面的 — 执行。同时编辑多行不触发此事件)。通过this.event可以获取对应的条目对象。
* @event mwf.xapplication.process.xform.datatablepc#cancellineedit
* @see {@link https://www.yuque.com/o2oa/ixsnyt/hm5uft#i0zts|组件事件说明}
*/
/**
* 删除条目前触发。通过this.event可以获取对应的条目对象。
* @event mwf.xapplication.process.xform.datatablepc#deleteline
* @see {@link https://www.yuque.com/o2oa/ixsnyt/hm5uft#i0zts|组件事件说明}
*/
/**
* 删除条目后触发。
* @event mwf.xapplication.process.xform.datatablepc#afterdeleteline
* @see {@link https://www.yuque.com/o2oa/ixsnyt/hm5uft#i0zts|组件事件说明}
*/
/**
* 导出前触发。
* @event mwf.xapplication.process.xform.datatablepc#beforeexport
* @see {@link https://www.yuque.com/o2oa/ixsnyt/hm5uft#i0zts|组件事件说明}
*/
/**
* 导出excel的时候触发,this.event指向导出的数据,您可以通过修改this.event来修改数据。
* @event mwf.xapplication.process.xform.datatablepc#export
* @see {@link https://www.yuque.com/o2oa/ixsnyt/hm5uft#i0zts|组件事件说明}
* @example
* this.event数据格式如下:
* {
* 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指向导入的数据。
* @event mwf.xapplication.process.xform.datatablepc#validimport
* @see {@link https://www.yuque.com/o2oa/ixsnyt/hm5uft#i0zts|组件事件说明}
* @example
* this.event数据格式如下:
* {
* data : [
* {
* "姓名" : "张三",
* "性别" : "男",
* "学历" : "大学本科",
* "专业" : "计算机",
* "出生日期" : "aa01-1-2",
* "毕业日期" : "2019-9-2",
* "errortextlist" : [
* "第5列:aa01-1-2不是正确的日期格式。"
* ] //校验出的错误信息,如果该行数据正确,则无该字段
* }
* ...
* ], //导入的数据
* "validted" : true //是否校验通过,可以在本事件中修改该参数,确定是否强制导入
* }
*/
/**
* 导入前触发。
* @event mwf.xapplication.process.xform.datatablepc#beforeimport
* @see {@link https://www.yuque.com/o2oa/ixsnyt/hm5uft#i0zts|组件事件说明}
*/
/**
* 在导入excel,数据校验成功将要设置回数据表格的时候触发,this.event指向整理过的导入数据,格式见{@link datatabledata}。
* @event mwf.xapplication.process.xform.datatablepc#import
* @see {@link https://www.yuque.com/o2oa/ixsnyt/hm5uft#i0zts|组件事件说明}
*/
/**
* 在导入excel,数据设置回数据表格以后触发,this.event指向整理过的导入数据,格式见{@link datatabledata}。
* @event mwf.xapplication.process.xform.datatablepc#afterimport
* @see {@link https://www.yuque.com/o2oa/ixsnyt/hm5uft#i0zts|组件事件说明}
*/
"moduleevents": ["queryload","postload","load", "afterload",
"beforeloadline", "afterloadline", "change", "addline", "deleteline", "afterdeleteline", "editline",
"completelineedit", "cancellineedit", "beforeexport", "export", "beforeimport", "import", "validimport", "afterimport"]
},
initialize: function(node, json, form, options){
this.node = $(node);
this.node.store("module", this);
this.json = json;
this.form = form;
this.field = true;
this.fieldmoduleloaded = false;
},
load: function(){
this._loadmoduleevents();
if (this.fireevent("queryload")){
this._queryloaded();
// if( this.issectionmergeedit() ){ //区段合并,删除区段值合并数据后编辑
// if( this.json.mergetypeedit === "script" ){
// this._loadmergeeditnodebyscript();
// }else{
// this._loadmergeeditnodebydefault();
// }
// }else{
// this._loaduserinterface();
// }
this._loaduserinterface();
this._loadstyles();
this._loaddomevents();
//this._loadevents();
this._afterloaded();
this.fireevent("afterload");
// this.fireevent("load");
}
},
_loadmergeeditnodebyscript: function(){
if (this.json.sectionmergeeditscript && this.json.sectionmergeeditscript.code) {
var data = this.form.macro.exec(this.json.sectionmergeeditscript.code, this);
this._setbusinessdata( data );
//this._loaduserinterface();
}
},
_loadmergeeditnodebydefault: function(){
var data = this.getsortedsectiondata();
var businessdata = [];
data.each(function(d){
d.data = d.data || {};
businessdata = businessdata.concat( d.data.data || [] );
});
this._setbusinessdata({
data: businessdata
});
//this._loaduserinterface();
},
_loaduserinterface: function(){
// this.fireevent("queryload");
debugger;
//区段合并后编辑
if( this.issectionmergeedit() ){ //区段合并,删除区段值合并数据后编辑
if( this.json.mergetypeedit === "script" ){
this._loadmergeeditnodebyscript();
}else{
this._loadmergeeditnodebydefault();
}
}
//区段合并展现
this.ismergeread = this.issectionmergeread();
//启用区段且显示所有区段
this.sectionby = this._getsectionby();
this.isshowallsection = this.isallsectionshow();
// this.editmodules = [];
// if( !layout.mobile ){
// this.node.setstyle("overflow-x", "auto");
// this.node.setstyle("overflow-y", "hidden");
// }
this.table = this.node.getelement("table");
this.tbody = this.table.getelement("tbody");
this.editable = !(this.readonly || (this.json.isreadonly === true) || (this.form.json.isreadonly === true));
if( this.ismergeread )this.editable = false;
if (this.editable && this.json.editablescript && this.json.editablescript.code){
this.editable = this.form.macro.exec(((this.json.editablescript) ? this.json.editablescript.code : ""), this);
}
this.deleteable = this.json.deleteable !== "no";
this.addable = this.json.addable !== "no";
this.sortable = this.json.sortable !== "no";
//允许导入
this.importenable = this.editable && (this.json.impexptype === "impexp" || this.json.impexptype === "imp");
//允许导出
this.exportenable = this.json.impexptype === "impexp" || this.json.impexptype === "exp";
//是否多行同时编辑
this.multieditmode = this.json.editmode === "multi";
//是否有总计列
this.totalflag = false;
this.totalcolumns = [];
this.totalnumbermoduleids = [];
// this.hiddencolindexlist = [];
if( this.isshowallsection ){
this.data = this._getallsectiondata()
}else if( this.ismergeread ){
this.data = this.getsectionmergereaddata()
}else{
this.data = this.getvalue();
if( !this._getbusinessdata() ){
this.isnew = true;
this._setvalue(this.data);
}
}
this.linelist = [];
this.sectionlinelist = [];
this.loaddatatable();
},
/*
* @summary 重新加载数据表格。
* @example
* this.form.get("fieldid").reload(); //重新加载
*/
reload: function(){
this.reloading = true;
this._removeel();
// this.editmodules = [];
//是否有总计列
this.totalflag = false;
this.totalcolumns = [];
this.totalnumbermoduleids = [];
this.checkmerge( this.getvalue() );
this.clearsubmodules();
this.linelist = [];
this.sectionlinelist = [];
this.loaddatatable();
this.reloading = false;
},
loaddatatable: function(){
this.loading = true;
this._loadstyles();
this._loadtitletr();
this._loadtemplate();
this._loadtotaltr();
this.fireevent("load");
this._loaddatatable(function(){
this._loadimportexportaction();
this.fieldmoduleloaded = true;
this.loading = false;
this.fireevent("postload");
}.bind(this));
},
_removeel: function(){
var node;
if( this.titletr ){
node = this.titletr.getelement("th.mwf_addlineaction");
if( node )node.destroy();
node = this.titletr.getelement("th.mwf_moveaction");
if( node )node.destroy();
}
if( this.templatetr ){
node = this.templatetr.getelement("td.mwf_editaction");
if( node )node.destroy();
node = this.templatetr.getelement("td.mwf_moveaction");
if( node )node.destroy();
}
if( this.totaltr ){
this.totaltr.destroy();
this.totaltr = null;
}
if( this.exportactionnode ){
this.exportactionnode.destroy();
this.totaltr = null;
}
if( this.importactionnode ){
this.importactionnode.destroy();
this.totaltr = null;
}
},
_loadtitletr: function(){
this.titletr = this.table.getelement("tr");
var ths = this.titletr.getelements("th");
if (this.json.border){
ths.setstyles({
"border-bottom": this.json.border,
"border-right": this.json.border
});
}
if (this.json.titlestyles)ths.setstyles(this.json.titlestyles);
//datatable$title module
ths.each(function(th, index){
var json = this.form._getdomjson(th);
th.store("datatable", this);
th.addclass("mwf_origional");
if (json){
var module = this.form._loadmodule(json, th);
this.form.modules.push(module);
if( json.isshow === false ){
th.hide(); //隐藏列
}else if( this.reloading && json.isshow === true){
th.setstyle("display", "");
}
if((json.total === "number") || (json.total === "count"))this.totalflag = true;
}
}.bind(this));
if(this.editable){
var actionth = new element("th.mwf_addlineaction", {"styles": {"width": "46px"}}).inject(this.titletr, "top"); //操作列
if(this.addable){
var addlineaction = new element("div", {
"styles": this.form.css.addlineaction,
"events": {
"click": function(e){
if( this.json.addto === "first" ){
this._insertlinebyindex(e.target, 0);
}else{
this._addline(e.target, true);
}
}.bind(this)
}
}).inject(actionth);
}
var moveth;
if( this.sortable ){
moveth = new element("th.mwf_moveaction", {"styles": this.form.css.gridmoveactioncell || {}}).inject(this.titletr, "bottom"); //总计列
}
if (this.json.border){
array.each([actionth,moveth], function(th){
if(th)th.setstyles({
"border-bottom": this.json.border,
"border-right": this.json.border
})
}.bind(this));
}
if (this.json.titlestyles){
object.each(this.json.titlestyles, function( value, key ){
if( key && key.tolowercase() !== "width" ){
actionth.setstyle(key, value);
if(moveth)moveth.setstyle(key, value);
}
});
}
}
},
_loadtemplate: function(){
// this.templatejson = {};
var trs = this.table.getelements("tr");
this.templatetr = trs[trs.length-1];
this.templatenode = this.templatetr;
var tds = this.templatenode.getelements("td");
this.columncount = tds.length;
if (this.json.border) {
tds.setstyles({
"border-bottom": this.json.border,
"border-right": this.json.border,
"background": "transparent"
});
}
if (this.json.contentstyles)tds.setstyles(this.json.contentstyles);
//datatable$data module
tds.each(function(td, index){
var json = this.form._getdomjson(td);
td.store("datatable", this);
td.addclass("mwf_origional");
if (json){
// var module = this.form._loadmodule(json, td);
// this.form.modules.push(module);
if( json.celltype === "sequence" )td.addclass("mwf_sequence"); //序号列
if( json.isshow === false ){
td.hide(); //隐藏列
}else if( this.reloading && json.isshow === true){
td.setstyle("display", "");
}
}
}.bind(this));
if(this.editable){
var etd = new element("td.mwf_editaction",{"styles": this.json.actionstyles || {}}).inject(this.templatenode, "top"); //操作列
this.columncount = this.columncount 1;
var mtd;
if( this.sortable ){
mtd= new element("td.mwf_moveaction", {"styles": this.form.css.gridmoveactioncell || {}}).inject(this.templatenode, "bottom");
this.columncount = this.columncount 1;
} //排序列
if (this.json.border){
array.each([etd,mtd], function(td){
if(td)td.setstyles({
"border-bottom": this.json.border,
"border-right": this.json.border,
"background": "transparent"
})
}.bind(this));
}
if (this.json.contentstyles){
object.each(this.json.contentstyles, function( value, key ){
if( key && key.tolowercase() !== "width" ){
etd.setstyle(key, value);
if(mtd)mtd.setstyle(key, value);
}
});
// etd.setstyles(this.json.contentstyles);
// if(mtd)mtd.setstyles(this.json.contentstyles);
}
}
this.templatehtml = this.templatenode.get("html");
// var modulenodes = this.form._getmodulenodes(this.templatenode);
// modulenodes.each(function (node) {
// if (node.get("mwftype") !== "form") {
// var json = this.form._getdomjson(node);
// this.templatejson[json.id] = json ;
// }
// }.bind(this));
this.templatenode.hide();
},
_loadtotaltr: function(){
if( !this.totalflag )return;
this.totaltr = new element("tr.mwf_totaltr", {"styles": this.form.css.datagridtotaltr}).inject(this.tbody||this.table);
if( this.isshowsectionkey() && !(this.json.totalrowbysection || [] ).contains("module")){
this.totaltr.hide()
}
if( this.isshowsectionby() && !(this.json.totalrowby || [] ).contains("module") ){
this.totaltr.hide()
}
var ths = this.titletr.getelements("th");
//datatable$title module
ths.each(function(th, index){
var td = new element("td", {"text": "", "styles": this.form.css.datagridtotaltd}).inject(this.totaltr);
if (this.json.amountstyles) td.setstyles(this.json.amountstyles);
var json = this.form._getdomjson(th);
if (json){
if( json.isshow === false ){
td.hide(); //隐藏列
}else if( this.reloading && json.isshow === true){
td.setstyle("display", "");
}
if ((json.total === "number") || (json.total === "count")){
this.totalcolumns.push({
"th" : th,
"td" : td,
"index": index,
"type": json.total
})
}
}
}.bind(this));
var tds = this.templatetr.getelements("td");
//datatable$data module
tds.each(function(td, index){
var json = this.form._getdomjson(td);
if (json){
//总计列
var tcolumn = this.totalcolumns.find(function(a){ return a.index === index });
if(tcolumn){
var modulenodes = this.form._getmodulenodes(td); //获取总计列内的填写组件
if( modulenodes.length > 0 ){
tcolumn.modulejson = this.form._getdomjson(modulenodes[0]);
if(tcolumn.type === "number")this.totalnumbermoduleids.push( tcolumn.modulejson.id );
}
}
}
}.bind(this));
},
_gettotaltr: function(){
return this.totaltr;
},
_loadtotal: function(){
var totaldata = {};
if (!this.totalflag)return totaldata;
if (!this._gettotaltr())this._loadtotaltr();
var data;
if( this.isshowallsection ){
data = { data : [] };
object.each( this.getbusinessdatabyid(), function (d, key) {
if( !["data","total"].contains(key) ){
data.data = data.data.concat( d.data )
}
})
}else if( this.ismergeread ){
data = this.data;
}else{
data = this.getvalue();
}
this.totalcolumns.each(function(column, index){
var json = column.modulejson;
if(!json)return;
var total = this._loadcolumntotal( column, data );
if( typeof(total) !== "null" )totaldata[json.id] = total;
}.bind(this));
data.total = totaldata;
return totaldata;
},
_loadcolumntotal: function(column, data){
var json = column.modulejson;
if(!json)return;
var pointlength = 0; //小数点后的最大数位
var tmpv;
if (column.type === "count"){
tmpv = data.data.length;
}else if(column.type === "number"){
tmpv = new decimal(0);
for (var i=0; i -1 ){
pointlength = math.max(pointlength, v.split(".")[1].length);
}
}
}
}
if( isnan( tmpv ) ) {
column.td.set("text", "");
return;
}
var s = tmpv.tostring(), total;
if( json.decimals && (json.decimals!=="*")){
total = this.formatdecimals( json, s.tofloat());
}else if( pointlength <= 0 || s === "0" ){
total = s;
}else if( s.indexof(".") > -1 ){
var length = s.split(".")[1].length;
total = length < pointlength ? (s "0".repeat(pointlength-length)) : s
}else{
total = s "." "0".repeat(pointlength);
}
column.td.set("text", this.formatseparate( json, total ) );
if( json.currencysymbol ){
new element("span", {"text": json.currencysymbol, "style":"padding-right:5px"}).inject( column.td, "top" );
}
return total;
},
formatdecimals: function( json, v ){
var str;
if (json.decimals && (json.decimals!=="*")) { //小数点数位
var decimals = json.decimals.toint();
var p = math.pow(10, decimals);
var f_x = math.round(v * p) / p;
str = f_x.tostring();
if (decimals > 0) {
var pos_decimal = str.indexof('.');
if (pos_decimal < 0) {
pos_decimal = str.length;
str = '.';
}
var decimalstr = (str).substr(pos_decimal 1, (str).length);
while (decimalstr.length < decimals) {
str = '0';
decimalstr = 0;
}
}
}
return str || v.tostring();
},
formatseparate: function(json, str){
if( typeof( str ) === "number" )str = str.tostring();
if( json.digitstoseparate && parseint(json.digitstoseparate) > 1 ){
var digits = parseint(json.digitstoseparate);
var reg = new regexp( "(\\d{" digits "}\\b)" ,"g");
var arr = str.split(".");
var i = arr[0].split("").reverse().join("")
.replace(reg, "$1,")
.split("").reverse().join("");
str = arr.length > 1 ? ( i "." arr[1] ) : i ;
}
return str;
},
istotalnumbermodule: function( id ){
return this.totalnumbermoduleids.contains(id)
},
isshowsectionkey: function(){
return this.json.showsectionkey && this.ismergeread ;
},
isshowsectionby: function(){
return this.json.showsectionby && this.isshowallsection ;
},
issectiondata: function(){ //数据是否经过区段处理
var data = this.getbusinessdatabyid();
if( o2.typeof( data ) === "object" ){
var keys = object.keys(data);
for( var i=0; i 0 ? this.sectionlinelist[idx-1].getlasttr() : this.templatenode;
if( map[data.sectionkey] ) {
sectionline = map[data.sectionkey];
sectionline.setindex( beforenode, data, idx, isedited, isnew, operation );
}else{
var node = this._createlinenode( beforenode );
sectionline = this._loadsectionline_editsection(node, data, idx, isedited, isnew);
}
if( this.sectionby && this.sectionby === data.sectionkey ){
this.sectionlineedited = sectionline;
}
this.sectionlinelist.push(sectionline);
}.bind(this))
if (callback) callback();
},
_loadsectionline_editsection: function(container, data, index, isedited, isnew){
var sectionline = new mwf.xapplication.process.xform.datatablepc.sectionline(container, this, data, {
index : index,
indextext : (index 1).tostring(),
isnew: isnew,
isedited: typeof(isedited) === "boolean" ? isedited : this.editable,
iseditable: this.editable && this.issectionlineeditable(data),
isdeleteable: this.deleteable && this.issectionlineeditable(data),
isaddable: this.addable && this.issectionlineeditable(data)
});
// this.fireevent("beforeloadline", [line]);
sectionline.load();
// this.fireevent("afterloadline", [line]);
return sectionline;
},
issectionlineeditable: function(data){
return this.isshowallsection && this.sectionby && this.sectionby === data.sectionkey;
},
_loadsectionlinelist: function(callback, operation){
var map = this.unchangedsectionlinemap || {};
this.datawithsectionkey.each(function(data, idx){
var sectionline;
var isedited = false;
var isnew = false;
var beforenode = idx > 0 ? this.sectionlinelist[idx-1].getlasttr() : this.templatenode;
if( map[data.sectionkey] ) {
sectionline = map[data.sectionkey];
sectionline.setindex( beforenode, data, idx, isedited, isnew, operation );
}else {
var node = this._createlinenode( beforenode );
sectionline = this._loadsectionline(node, data, idx, isedited, isnew);
}
this.sectionlinelist.push(sectionline);
}.bind(this))
if (callback) callback();
},
_loadsectionline: function(container, data, index, isedited, isnew){
var sectionline = new mwf.xapplication.process.xform.datatablepc.sectionline(container, this, data, {
index : index,
indextext : (index 1).tostring(),
isnew: isnew,
isedited: typeof(isedited) === "boolean" ? isedited : this.editable,
iseditable: this.editable,
isdeleteable: this.deleteable,
isaddable: this.addable,
ismergeread: this.ismergeread
});
// this.fireevent("beforeloadline", [line]);
sectionline.load();
// this.fireevent("afterloadline", [line]);
return sectionline;
},
_loadlinelist: function(callback, operation){
var map = this.unchangedlinemap || {};
object.each(map, function (line, idx) {
line.setindex( idx.toint() );
});
this.data.data.each(function(data, idx){
if( !data )return;
var idxstr = idx.tostring();
var beforenode = idx > 0 ? this.linelist[idx - 1].node : this.templatenode;
if( map[idxstr] ){
if( !operation || operation === "moveuplist" ){
map[idxstr].node.inject( beforenode, "after" );
}
this.linelist.push( map[idxstr] );
}else{
var isnew = this.isnew || (o2.typeof(this.newlineindex) === "number" ? idx === this.newlineindex : false);
var isedited = (!this.multieditmode && o2.typeof(this.newlineindex) === "number") ? idx === this.newlineindex : this.multieditmode;
var node = this._createlinenode( beforenode );
var line = this._loadline(node, data, idx, isedited, isnew );
this.linelist.push(line);
}
}.bind(this));
this.isnew = false;
this.newlineindex = null;
if (callback) callback();
},
_loadline: function(container, data, index, isedited, isnew){
var line = new mwf.xapplication.process.xform.datatablepc.line(container, this, data, {
index : index,
indextext : (index 1).tostring(),
isnew: isnew,
isedited: typeof(isedited) === "boolean" ? isedited : this.editable,
iseditable: this.editable,
isdeleteable: this.deleteable,
isaddable: this.addable,
ismergeread: this.ismergeread
});
this.fireevent("beforeloadline", [line]);
line.load();
this.fireevent("afterloadline", [line]);
return line;
},
ismax : function(){
var maxcount = this.json.maxcount ? this.json.maxcount.toint() : 0;
if( this.editable && maxcount > 0 ) {
if( this.isshowallsection ){
if( this.sectionlineedited && this.sectionlineedited.linelist.length >= maxcount )return true;
}else{
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.isshowallsection ){
if( this.sectionlineedited && this.sectionlineedited.linelist.length <= mincount )return true;
}else {
if (this.linelist.length <= mincount) return true;
}
}
return false;
},
_setlinedata: function(line, d){
if( line.sectionline ){
var data = this.getbusinessdatabyid();
var sdata = data[ line.sectionline.sectionkey ];
if( sdata && sdata.data ){
sdata.data[line.options.indexinsectionline] = d;
this.setallsectiondata( data, false, "setlinedata" );
}
}else{
var index = line.options.index;
var data = this.getinputdata();
data.data[index] = d;
this.setdata( data, false, "setlinedata" );
}
},
_addline: function(ev, edited, d){
if( !this._completelineedit(ev, true) )return;
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, index, line;
if( this.isshowallsection ){
data = this.getbusinessdatabyid();
var sdata = data[ this.sectionby ];
if( !sdata ){
sdata = data[ this.sectionby ] = { data: [] };
}
index = sdata.data.length;
// if( d && !d.sectionkey )d.sectionkey = this.sectionby;
// sectionkey: this.sectionby
sdata.data.push(d||{});
this.newlineindex = index;
this.setallsectiondata( data, false, "addline");
line = this.sectionlineedited.linelist[index];
line.isnewadd = true;
}else{
index = this.linelist.length;
data = this.getinputdata();
data.data.push(d||{});
this.newlineindex = index;
this.setdata( data , false, "addline");
line = this.getline(index);
line.isnewadd = true;
}
this.validationmode();
this.fireevent("addline", [{"line":line, "ev":ev}]);
this.fireevent("change", [{"lines":[line], "type":"addline"}]);
return line;
},
_insertline: function(ev, beforeline){
if( !this._completelineedit(ev, true) )return;
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, index, line;
if( this.isshowallsection ){
index = beforeline.options.indexinsectionline 1;
data = this.getbusinessdatabyid();
var sdata = data[ this.sectionby ];
if( !sdata ){
sdata = data[ this.sectionby ] = { data: [] };
}
sdata.data.splice(index, 0, {});
this.newlineindex = index;
this.setallsectiondata( data, false, "insertline");
line = this.sectionlineedited.linelist[index];
line.isnewadd = true;
}else {
index = beforeline.options.index 1;
data = this.getinputdata();
data.data.splice(index, 0, {});
this.newlineindex = index;
this.setdata(data, false, "insertline");
line = this.getline(index);
line.isnewadd = true;
}
this.validationmode();
this.fireevent("addline",[{"line":line, "ev":ev}]);
this.fireevent("change", [{"lines":[line], "type":"addline"}]);
return line;
},
_insertlinebyindex: function(ev, index, d){
if( !this._completelineedit(ev, true) )return;
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, line;
if( this.isshowallsection ){
data = this.getbusinessdatabyid();
var sdata = data[ this.sectionby ];
if( !sdata ){
sdata = data[ this.sectionby ] = { data: [] };
}
if (sdata.data.length < index) return null;
sdata.data.splice(index, 0, d || {});
this.newlineindex = index;
this.setallsectiondata( data , false, "insertline" );
line = this.sectionlineedited.linelist[index];
line.isnewadd = true;
}else {
//使用数据驱动
data = this.getinputdata();
if (data.data.length < index) return null;
data.data.splice(index, 0, d || {});
this.newlineindex = index;
this.setdata(data, false, "insertline");
line = this.getline(index);
line.isnewadd = true;
}
this.validationmode();
this.fireevent("addline",[{"line":line, "ev":ev}]);
this.fireevent("change", [{"lines":[line], "type":"addline"}]);
return line;
},
_deleteselectedline: function(ev){
var selectedline = this.linelist.filter(function (line) { return line.selected; });
if( selectedline.length === 0 ){
this.form.notice( mwf.xapplication.process.xform.lp.selectitemnotice,"info");
return false;
}
var mincount = this.json.mincount ? this.json.mincount.toint() : 0;
if( mincount > 0 ){
if( this.linelist.length - selectedline.length < mincount ){
var text = mwf.xapplication.process.xform.lp.minitemnotice.replace("{n}", 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.deleteselecteditemnotice, 300, 120, function(){
_self._dellines( selectedline );
this.close();
}, function(){
this.close();
}, null, null, this.form.json.confirmstyle);
},
_dellines: function(lines){
var _self = this;
var saveflag = false;
var data;
if( this.isshowallsection ){
data = this.getbusinessdatabyid();
}else{
data = _self.getinputdata();
}
lines.reverse().each(function(line){
_self.fireevent("deleteline", [line]);
if(line.deleteattachment())saveflag = true;
if( line.sectionline ){
var d = data[ line.sectionline.sectionkey ];
if( d && d.data ){
d.data.splice(line.options.indexinsectionline, 1);
if(this.currenteditedline === line)this.currenteditedline = null;
}
}else {
data.data.splice(line.options.index, 1);
if (this.currenteditedline === line) this.currenteditedline = null;
}
_self.fireevent("afterdeleteline");
});
if( this.isshowallsection ){
_self.setallsectiondata(data, false, "deletelines");
}else{
_self.setdata( data , false, "deletelines");
}
this.validationmode();
_self.fireevent("change", [{"lines":lines, "type":"deletelines"}]);
if(saveflag)this.saveformdata();
},
_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(){
_self._delline(line);
this.close();
}, function(){
this.close();
}, null, null, this.form.json.confirmstyle);
},
_delline: function(line){
this.fireevent("deleteline", [line]);
var saveflag = line.deleteattachment();
//使用数据驱动
var data;
if( line.sectionline ){
var data = this.getbusinessdatabyid();
var d = data[ line.sectionline.sectionkey ];
if( d && d.data ){
d.data.splice(line.options.indexinsectionline, 1);
}
if(this.currenteditedline === line)this.currenteditedline = null;
this.setallsectiondata( data, false, "deleteline" );
}else{
data = this.getinputdata();
data.data.splice(line.options.index, 1);
if(this.currenteditedline === line)this.currenteditedline = null;
this.setdata( data , false, "deleteline");
}
this.validationmode();
this.fireevent("afterdeleteline");
this.fireevent("change", [{"lines":[line], "type":"deleteline"}]);
if(saveflag)this.saveformdata();
},
_cancellineedit: function(){
var line = this.currenteditedline;
if( !line )return true;
line.validationmode();
if( line.isnewadd ){
// var saveflag = line.deleteattachment();
this._delline( line );
this.currenteditedline = null;
// if(saveflag)this.form.saveformdata();
}else{
// line.data = object.clone(line.getoriginaldatawithcheckattachment());
line.resetdatawithoriginaldata();
line.changeeditmode(false);
this._loadtotal();
if( line.sectionline )line.sectionline._loadtotal();
if(line.attachmentchangeflag){
this.saveformdata();
line.attachmentchangeflag = false;
}
this.currenteditedline = null;
this.fireevent("cancellineedit", [line]);
}
return true;
},
_completelineedit: function( ev, firechange, ignoersave ){
var line = this.currenteditedline;
if( !line )return true;
if( !line.validation() )return false;
var originaldatastr, datastr;
if( firechange ){
if( line.originaldata && o2.typeof(line.originaldata) === "object"){
originaldatastr = json.stringify(line.originaldata)
}
datastr = json.stringify(line.data);
}
line.isnewadd = false;
// line.data = line.getdata();
line.computemoduledata("save");
line.originaldata = object.clone(line.data);
line.changeeditmode(false);
this._loadtotal();
if( line.sectionline )line.sectionline._loadtotal();
if(line.attachmentchangeflag && !ignoersave){
this.saveformdata();
line.attachmentchangeflag = false;
}
this.currenteditedline = null;
this.validationmode();
this.fireevent("completelineedit", [line]);
if( firechange && originaldatastr !== datastr ){
this.fireevent("change", [{"lines":[line], "type":"editcomplete"}]);
}
return true;
},
_moveupline: function(ev, line){
if( this.currenteditedline && !this._completelineedit(null, true) )return false;
var data, updata, curdata;
if( this.isshowallsection ){
if (line.options.indexinsectionline === 0) return;
data = this.getbusinessdatabyid();
var sdata = data[ this.sectionby ];
if( !sdata )return;
updata = sdata.data[line.options.indexinsectionline - 1];
curdata = sdata.data[line.options.indexinsectionline];
sdata.data[line.options.indexinsectionline] = updata;
sdata.data[line.options.indexinsectionline - 1] = curdata;
this.setallsectiondata( data, false, "moveuplist" );
}else {
if (line.options.index === 0) return;
data = this.getinputdata();
updata = data.data[line.options.index - 1];
curdata = data.data[line.options.index];
data.data[line.options.index] = updata;
data.data[line.options.index - 1] = curdata;
this.setdata(data, false, "moveuplist");
}
this.fireevent("change", [{lines: this.linelist, "type":"move"}]);
},
_changeeditedline: function(line){
if( this.currenteditedline ){
if( line === this.currenteditedline )return;
if( !this._completelineedit( null,true ) )return;
}
line.changeeditmode(true);
/**
* 数据表格当前正在编辑的条目,当数据表格为“同时编辑多行”时无此属性。
* @member {mwf.xapplication.process.xform.datatablepc.line | mwf.xapplication.process.xform.datatablemobile.line | null}
* @example
* //获取数据表格“dt1”的正在编辑的条目。
* var line = this.form.get("dt1").currenteditedline;
* //获取数据
* var data = line.getdata();
* //设置数据
* line.setdata({"subject":"111"});
* //获取subject字段的值
* var data = line.get("subject").getdata();
* //设置subject字段的值
* line.get("subject").setdata("test1");
*/
this.currenteditedline = line;
},
// editvalidation: function(){
// var flag = true;
// this.editmodules.each(function(field, key){
// if (field.json.type!=="sequence" && field.validationmode ){
// field.validationmode();
// if (!field.validation()) flag = false;
// }
// }.bind(this));
// return flag;
// },
_afterloaded: function(){
},
// /**
// * @summary 重置数据表格的值为默认值或置空。
// * @example
// * this.form.get('fieldid').resetdata();
// */
resetdata: function(){
//var value = this.getdefaultvalue() || {"data": [], "total":{}};
var value = this.getvalue();
this.setdata( value , false );
},
/**当参数为promise的时候,请查看文档: {@link https://www.yuque.com/o2oa/ixsnyt/ws07m0|使用promise处理表单异步}
* 当表单上没有对应组件的时候,可以使用this.data[fieldid] = data赋值。
* @summary 为数据表格赋值,如果需要设置所有区段数据请使用setallsectiondata方法。
* @param data{datatabledata|promise|array} 必选,数组或promise.
* @param firechange{boolean} 可选,是否触发change事件,默认false.
* @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, firechange, operation){
if (!data){
data = this._getvalue();
}else{
//todo 计算total
}
this._setdata(data, firechange, operation);
},
_setdata: function(data, firechange, operation){
var p = o2.promiseall(this.data).then(function(v){
this.data = v;
// if (o2.typeof(data)==="object") data = [data];
this.__setdata(data, firechange, operation);
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, firechange, operation){
// if( typeof( data ) === "object" && typeof(data.data) === "array" ){
if( this.isshowallsection ){
//兼容外部对编辑当前区段的setdata,内部的setdata不走这里,直接走setallsectiondata
this._seteditedsectiondata(data, firechange, operation);
return;
}else if( this.ismergeread ){
//合并且只读,不允许setdata
throw new error("the data table is merged and read-only, you can use the 'setallsectiondata' method to set all section data");
}
var old;
if(firechange)old = object.clone(this._getbusinessdata() || {});
this._setunchangedlinemap(data, operation);
this._setbusinessdata(data);
this.data = data;
if (this.data){
this.clearsubmodules();
}
this.linelist = [];
this.sectionlinelist = [];
if( this.currenteditedline )this.currenteditedline = null;
this._loaddatatable( function () {
if (firechange && json.stringify(old) !== json.stringify(data)) this.fireevent("change");
this.unchangedlinemap = null;
}.bind(this), operation);
},
_seteditedsectiondata: function(data, firechange, operation){
if( this.isshowallsection ){
var d = this.getbusinessdatabyid();
d[ this.sectionby ] = data || { data: [] };
this.setallsectiondata( d, firechange , operation);
}
},
deleteattachment: function( attid ){
this.form.workaction.deleteattachment(attid, this.form.businessdata.work.id);
},
saveformdata: function(){
this.form.saveformdata();
},
/**
* @summary 当数据表格设置为区段合并展现、区段合并编辑时,可以使用本方法设置所有区段数据。
* @param data{object} 必选,对象.
* @param firechange{boolean} 可选,是否触发change事件,默认false.
* @example
* this.form.get("fieldid").setallsectiondata({}); //赋空值
* @example
* this.data['fieldid'].setallsectiondata({
* "3455b82a-399c-4ee4-b9b9-e70ae40fbaf1": { //区段1的key和data
* "data": [
* {
* "good": "yf",
* "number_2": 11,
* "prize": 1
* }
* ]
* },
* "83de86fc-60bc-4b4c-955c-1085915865a4": { //区段2的key和data
* "data": [
* {
* "good": "yf",
* "number_2": 11,
* "prize": 10
* }
* ]
* }
* });
*/
setallsectiondata: function(data, firechange, operation){
// if( this.issectionmergeedit() ){
// //合并且编辑,不允许setallsectiondata
// throw new error("the data table is in merge editing state, you can use the 'setdata' method to set the data");
// }
var old;
if(firechange)old = object.clone(this.getbusinessdatabyid() || {});
//删除并没有用,因为会对比数据提交,如果要清空可以给data.data = []; data.total = {}
// if( data && data.data )delete data.data;
// if( data && data.total )delete data.total;
this._setunchangedsectionlinemap(data);
this.setbusinessdatabyid(data);
if( operation ){
this.data = this.isshowallsection ? this._getallsectiondata() : data;
}else{
this.checkmerge(data);
}
if (this.data){
this.clearsubmodules();
}
if (firechange && json.stringify(old) !== json.stringify(data)) this.fireevent("change");
this.linelist = [];
this.sectionlinelist = [];
if( this.currenteditedline )this.currenteditedline = null;
this._loaddatatable(function () {
object.each(this.unchangedsectionlinemap, function(sline, key){
sline.isunchangedall = null;
sline.unchangedlinemap = null;
});
this.unchangedsectionlinemap = null;
}.bind(this), operation);
},
checkmerge: function(data){
//区段合并后编辑
var ismergeeidt = this.issectionmergeedit();
if( ismergeeidt ){ //区段合并,删除区段值合并数据后编辑
if( this.json.mergetypeedit === "script" ){
this._loadmergeeditnodebyscript();
}else{
this._loadmergeeditnodebydefault();
}
}
//区段合并展现
this.ismergeread = this.issectionmergeread();
//启用区段且显示所有区段
this.sectionby = this._getsectionby();
this.isshowallsection = this.isallsectionshow();
if( this.isshowallsection ){
this.data = this._getallsectiondata();
}else if( this.ismergeread ) {
this.data = this.getsectionmergereaddata();
}else if( ismergeeidt ){
this.data = this._getbusinessdata()
}else{
this.data = data;
}
},
_setunchangedsectionlinemap: function( data, operation ){
if( !data ){
return;
}
var map = {};
if( this.sectionlinelist && this.sectionlinelist.length ){
this.sectionlinelist.each(function (sline, i) {
for( var key in data ){
if( key === sline.sectionkey ){
var m = sline._setunchangedlinemap(data[key], operation);
if( m )map[key] = m;
break;
}
}
}.bind(this));
}
this.unchangedsectionlinemap = map;
},
_setunchangedlinemap: function(data, operation){
if( !data ){
this.unchangedlinemap = {};
return;
}
var fromoutside = !operation;
var linedatalist = this.linelist.map(function (line) {
if( line.options.iseditable !== this.editable )return "";
if( line.options.isdeleteable !== this.deleteable )return "";
if( line.options.isaddable !== this.addable )return "";
return fromoutside ? json.stringify(line.data) : line.data;
}.bind(this));
var dstr, map = {};
data.data.each(function (d, idx) {
if(fromoutside)dstr = json.stringify(d);
for (var i = 0; i < this.linelist.length; i ) {
var isequal= fromoutside ? (dstr === linedatalist[i]) : (d === linedatalist[i] );
if ( isequal ) {
map[idx] = this.linelist[i];
linedatalist[i] = "";
break;
}
}
}.bind(this));
this.unchangedlinemap = map;
},
clearsubmodules: function(){
if( this.sectionlinelist && this.sectionlinelist.length ){
this.sectionlinelist.each(function (sline, i) {
sline.clearsubmodules();
}.bind(this));
}else{
var map = this.unchangedlinemap || {};
var lines = [];
object.values(map).each(function (d) {
lines = lines.concat(d);
});
for (var i=0; i
* 1、当使用promise的时候
* 使用异步函数生成器(promise)为组件赋值的时候,用getdata方法立即获取数据,可能返回修改前的值,当promise执行完成以后,会返回修改后的值。
* this.data[fieldid] 立即获取数据,可能获取到异步函数生成器,当promise执行完成以后,会返回修改后的值。
* {@link https://www.yuque.com/o2oa/ixsnyt/ws07m0#eggil|具体差异请查看链接}
* 2、当表单上没有对应组件的时候,可以使用this.data[fieldid]获取值,但是this.form.get('fieldid')无法获取到组件。
* @summary 获取数据表格数据.
* @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 );
* @return {datatabledata}
*/
getdata: function(){
if( this.importer ){
this.importer.destroysimulatemodule();
}
if (this.editable!==false){
// this.linelist.each(function(line, index){
// if( !this.multieditmode && line.options.isedited ){
// line.data = line.getdata();
// }else{
// line.data = line.getdata();
// }
// });
if( this.multieditmode){
this.linelist.each(function (line) {
line.computemoduledata("save");
})
}
return this._getbusinessdata();
}else{
return this._getbusinessdata();
}
},
getinputdata: function(){
if( this.importer ){
this.importer.destroysimulatemodule();
}
if (this.editable!==false){
return this._getbusinessdata();
}else{
return this._getbusinessdata();
}
},
//区段依据
_getsectionby: 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 "";
}
}
},
createerrornode: function(text){
var node = new element("div");
var iconnode = new element("div", {
"styles": {
"width": "20px",
"height": "20px",
"float": "left",
"background": " 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);
var parentnode = this.errnode;
while( parentnode && parentnode.offsetparent === null ){
parentnode = parentnode.getparent();
}
if (parentnode && !parentnode.isintoview()) parentnode.scrollintoview(false);
}
},
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;
}
}
this.linelist.each(function(line){
line.validationmode();
})
},
validationconfigitem: function(routename, data){
var flag = (data.status=="all") ? true: (routename == data.decision);
if (flag){
//???
var n = this.getinputdata();
if( o2.typeof(n)==="object"){
var arr = [];
object.each( n, function (d, key) {
if(o2.typeof(d) === "array")arr = arr.concat(d);
});
n = arr;
}
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 0 ? this.linelist[idx - 1].node : this.sectionkeynode;
if( map[idxstr] ){
if( !operation || operation === "moveuplist" ){
map[idxstr].node.inject( beforenode, "after" );
}
this.linelist.push( map[idxstr] );
this.datatable.linelist.push(map[idxstr]);
}else{
var node = this._createlinenode( beforenode );
var isedited = false, isnew = false;
if( this.options.isedited ){
var dt = this.datatable;
isnew = dt.isnew || (o2.typeof(dt.newlineindex) === "number" ? idx === dt.newlineindex : false);
isedited = (!dt.multieditmode && o2.typeof(dt.newlineindex) === "number") ? idx === dt.newlineindex : dt.multieditmode;
dt.isnew = false;
dt.newlineindex = null;
}
var line = this._loadline( node, d, idx, isedited, isnew );
this.linelist.push(line);
this.datatable.linelist.push(line);
}
}.bind(this))
}
if( this.totaltr )this.totaltr.inject( this.linelist.getlast().node, "after" );
this._loadtotal();
},
_loadline: function(container, data, index, isedited, isnew){
var line = new mwf.xapplication.process.xform.datatablepc.line(container, this.datatable, data, {
indexinsectionline : index,
indexinsectionlinetext : (index 1).tostring(),
index: this.datatable.linelist.length,
indextext : (this.datatable.linelist.length 1).tostring(),
isnew: isnew,
isedited: typeof(isedited) === "boolean" ? isedited : this.options.isedited,
iseditable: this.options.iseditable,
isdeleteable: this.options.isdeleteable,
isaddable: this.options.isaddable,
ismergeread: this.options.ismergeread,
sectionkey: this.sectionkey
}, this);
this.datatable.fireevent("beforeloadline", [line]);
line.load();
this.datatable.fireevent("afterloadline", [line]);
return line;
},
_createlinenode: function( beforenode ){
var tr;
if( beforenode ){
tr = new element("tr").inject(beforenode, "after");
}else if( this.totaltr ){
tr = new element("tr").inject(this.totaltr, "before");
}else{
tr = this.datatable._createlinenode();
// tr = new element("tr").inject(this.tbody || this.table);
}
return tr;
},
loadsectionkeynode: function () {
var stylename = this.datatable.isshowsectionkey() ? "sectionkeystyles" : "sectionbystyles";
var sectionkeystyles = this.datatable._parsestyles( this.datatable.json[stylename] || {} );
var keynode = new element("td.mwf_sectionkey", {
colspan: this.datatable.columncount,
styles : sectionkeystyles
}).inject( this.sectionkeynode );
this.keynode = keynode;
var separator;
if( this.datatable.isshowsectionkey() ){
separator = this.datatable.json.keycontentseparator;
}else{
separator = this.datatable.json.keycontentseparatorsectionby;
}
this.datatable.getsectionkeywithmerge( this.data, function (key) {
if( o2.typeof(key) === "string" ){
keynode.set("text", key (separator || ""));
}else{
promise.resolve(key).then(function (k) {
keynode.set("text", k (separator || ""));
}.bind(this))
}
}.bind(this));
},
_setunchangedlinemap: function(data, operation){
var fromoutside = !operation;
var dt = this.datatable;
var editalbe;
if( dt.isshowallsection ){
editalbe = dt.isshowallsection && dt.sectionby && dt.sectionby === this.sectionkey;
}
var linedatalist = this.linelist.map(function (line) {
if( dt.isshowallsection ){
if( line.options.iseditable !== (dt.editable && editalbe) )return "";
if( line.options.isdeleteable !== (dt.deleteable && editalbe) )return "";
if( line.options.isaddable !== (dt.addable && editalbe) )return "";
}else{
if( line.options.iseditable !== dt.editable )return "";
if( line.options.isdeleteable !== dt.deleteable )return "";
if( line.options.isaddable !== dt.addable )return "";
}
return fromoutside ? json.stringify(line.data) : line.data;
}.bind(this));
var dstr, map = {};
data.data.each(function (d, idx) {
if(fromoutside)dstr = json.stringify(d);
for (var i = 0; i < this.linelist.length; i ) {
var isequal = fromoutside ? (dstr === linedatalist[i]) : (d === linedatalist[i] );
if ( isequal ) {
map[idx] = this.linelist[i];
linedatalist[i] = "";
break;
}
}
}.bind(this));
this.isunchangedall = data.data.length === this.linelist.length;
if( this.isunchangedall ){
for( var i=0; i 0;
if( !hasunchangedline ){
if( this.sectionkeynode ){
this.sectionkeynode.destroy();
this.sectionkeynode = null;
}
}
var lines = [];
object.values(map).each(function (d) {
lines = lines.concat(d);
});
for (var i=0; i 0 ){
tcolumn.modulejson = this.form._getdomjson(modulenodes[0]);
if(tcolumn.type === "number")this.totalnumbermoduleids.push( tcolumn.modulejson.id );
}
}
}
}.bind(this));
},
_gettotaltr: function(){
return this.totaltr;
},
_loadtotal: function(){
var totaldata = {};
if( !this.datatable.totalflag )return totaldata;
if (!this._gettotaltr())this._loadtotaltr();
var data;
if( this.datatable.isshowallsection ){
object.each( this.datatable.getbusinessdatabyid(), function (d, k) {
if( this.sectionkey === k )data = d
}.bind(this))
}else{
data = this.data.data;
}
this.totalcolumns.each(function(column, index){
var json = column.modulejson;
if(!json)return;
var total = this.datatable._loadcolumntotal( column, data );
if( typeof(total) !== "null" )totaldata[json.id] = total;
}.bind(this));
data.total = totaldata;
return totaldata;
},
istotalnumbermodule: function( id ){
return this.totalnumbermoduleids.contains(id)
},
getlasttr: function () {
if( this.totaltr )return this.totaltr;
if( this.linelist.length )return this.linelist.getlast().node;
return this.sectionkeynode;
}
});
mwf.xapplication.process.xform.datatablepc.line = new class({
implements: [options, events],
options: {
isnew: false,
isedited : true, //是否正在编辑
iseditable : true, //能否被编辑
isdeleteable: true, //能否被删除
isaddable: true, //能否添加
ismergeread: false, //合并阅读
index : 0,
indextext : "0",
indexinsectionline: 0,
indexinsectionlinetext : "0",
sectionkey: ""
},
initialize: function (node, datatable, data, options, sectionline) {
this.setoptions(options);
this.node = node;
this.datatable = datatable;
this.data = data;
this.form = this.datatable.form;
this.sectionline = sectionline;
// if( !this.datatable.multieditmode && !this.options.isnew){
// this.originaldata = object.clone(data);
// }
this.init()
},
init: function(){
this.modules = [];
this.all = {};
this.all_templateid = {};
this.fields = [];
this.allfield = {};
this.allfield_templateid = {};
this.changedattachmentmap = {};
},
load: function(){
if( !this.datatable.multieditmode && this.options.isedited )this.datatable.currenteditedline = this;
this.loadmodules();
this.loadsequence();
this.createactions();
this.loadzebrastyle();
this.loadeditedstyle();
this.addnodeevent();
if( !this.datatable.multieditmode )this.originaldata = object.clone(this.data);
// if(this.options.isnew && this.options.isedited){
// debugger;
// this.data = this.getdata();
// if( !this.datatable.multieditmode )this.originaldata = object.clone(this.data);
// this.options.isnew = false;
// }
},
resetid: function(){
this.setindex();
},
setindex: function(index, indexinsectionline){
var hasindexarg = typeof(index) !== "null";
var hasindexinsectionlinearg = typeof(indexinsectionline) !== "null";
if( hasindexarg && hasindexinsectionlinearg){
if( this.options.index === index && this.options.indexinsectionline === indexinsectionline )return;
}else if( hasindexarg && !hasindexinsectionlinearg){
if( this.options.index === index )return;
}else if(!hasindexarg && hasindexinsectionlinearg){
if( this.options.indexinsectionline === indexinsectionline )return;
}
if( hasindexarg ){
this.options.index = index;
this.options.indextext = (index.toint() 1).tostring();
}
if( hasindexinsectionlinearg ){
this.options.indexinsectionline = indexinsectionline;
this.options.indexinsectionlinetext = (indexinsectionline.toint() 1).tostring();
}
//合并状态或拆分状态
var sectionkey = this.options.sectionkey || this.datatable.sectionby;
this.modules.each(function (module) {
var json = module.json;
var id, oldid = json.id, templatejsonid = json.originialid;
if( this.datatable.isshowallsection ){
id = this.datatable.json.id ".." sectionkey "..data.." this.options.indexinsectionline ".." json.originialid;
}else if( sectionkey ){
id = this.datatable.json.id ".." sectionkey "..data.." this.options.index ".." json.originialid;
}else{
id = this.datatable.json.id "..data.." this.options.index ".." json.originialid;
}
json.id = id;
switch (module.json.type) {
case "select":
(module.areanode || module.node).set("id", id);
break;
default:
module.node.set("id", id);
break;
}
if( json.type==="attachment" || json.type==="attachmentdg" ){
json.site = this.getattachmentsite(json, templatejsonid, sectionkey);
}
delete this.all[oldid];
this.all[id] = module;
delete this.allfield[oldid];
this.allfield[id] = module;
if(this.form.all[oldid]){
delete this.form.all[oldid];
this.form.all[id] = module;
}
if(this.form.forms[oldid]){
delete this.form.forms[oldid];
this.form.forms[id] = module;
}
if( hasindexarg || hasindexinsectionlinearg ){
this.loadsequence();
this.loadzebrastyle();
}
}.bind(this));
},
loadmodules: function(){
this.node.set("html", this.datatable.templatehtml);
var modulenodes = this.form._getmodulenodes(this.node, true);
//合并状态或拆分状态
var sectionkey = this.options.sectionkey || this.datatable.sectionby;
modulenodes.each(function (node) {
var mwftype = node.get("mwftype");
if (mwftype === "form")return;
var _self = this;
var tjson = this.form._getdomjson(node);
if( tjson ){
var json = object.clone(tjson);
if( !this.options.isedited || !this.options.iseditable )json.isreadonly = true;
var templatejsonid = json.id;
var index = this.options.index;
var id;
if( this.datatable.isshowallsection ){
id = this.datatable.json.id ".." sectionkey "..data.." this.options.indexinsectionline ".." json.id;
}else if( sectionkey ){
id = this.datatable.json.id ".." sectionkey "..data.." index ".." json.id;
}else{
id = this.datatable.json.id "..data.." index ".." json.id;
}
json.originialid = templatejsonid;
json.id = id;
node.set("id", id);
if( json.type==="attachment" || json.type==="attachmentdg" ){
json.type = "attachmentdg";
json.ignoresite = true;
json.site = this.getattachmentsite(json, templatejsonid, sectionkey);
}
if (this.form.all[id]) this.form.all[id] = null;
if (this.form.forms[id])this.form.forms[id] = null;
var hasdata = this.data.hasownproperty(templatejsonid);
var module = this.form._loadmodule(json, node, function () {
if( _self.options.ismergeread ){
this.field = false; //不希望保存数据
this._getbusinessdata = function(){
return _self.data[templatejsonid];
};
this._setbusinessdata = function () {};
}
if( _self.widget )this.widget = _self.widget;
this.parentline = _self;
this.parentdatatable = _self.datatable;
//只读方法值在页面加载的时候或者new的时候计算一下
if( this.json.compute === "show" ){
var needcomputeshow = false;
if( _self.datatable.loading ) {
needcomputeshow = true;
}else if( _self.options.isnew && !_self.reloading ){
needcomputeshow = true;
}
if( !needcomputeshow ){
this.json.compute = "create"; //
if( this.options.moduleevents && this.options.moduleevents.length ){ //恢复compute
var eventname = ( this.options.moduleevents || [] ).contains("afterload") ? "afterload" : "load";
var resetcompute = function () {
this.json.compute = "show";
this.removeevent( eventname, resetcompute );
}.bind(this)
this.addevent(eventname, resetcompute);
}
}
}
});
if(!module.parentline)module.parentline = this;
if(!module.parentdatatable)module.parentdatatable = this.datatable;
if((json.type==="attachment" || json.type==="attachmentdg")){
module.addevent("change", function(){
if( this.datatable.multieditmode ){
_self.datatable.saveformdata();
}else{
_self.attachmentchangeflag = true;
}
}.bind(this))
}
this.form.modules.push(module);
this.modules.push(module);
this.all[id] = module;
this.all_templateid[templatejsonid] = module;
if (module.field) {
// if(hasdata){
// module.setdata(this.data[templatejsonid]);
// }else if(this.options.isedited){
// this.data[templatejsonid] = module.getdata();
// }
if(this.options.isedited ) {
if (json.type !== "attachment" && json.type !== "attachmentdg"){
if( module.json.compute === "save" && module.getinputdata ){
this.data[templatejsonid] = module.getinputdata();
}else{
this.data[templatejsonid] = module.getdata();
}
}
}else if(!hasdata && module.getvalue ){
this.data[templatejsonid] = module.getvalue();
}
this.allfield[id] = module;
this.allfield_templateid[templatejsonid] = module;
this.fields.push( module );
if( this.options.isedited && this.datatable.multieditmode ){
module.addevent("change", function(){
this.datatable.fireevent("change", [{lines: [this], type: "editmodule", module: module}]);
}.bind(this))
}
//该字段是合集数值字段
if(this.datatable.multieditmode && this.istotalnumbermodule(templatejsonid)){
//module
module.addevent("change", function(){
this.datatable._loadtotal();
if( this.sectionline )this.sectionline._loadtotal();
}.bind(this))
}
}
}
}.bind(this));
},
istotalnumbermodule: function(id){
if( this.sectionline ){
return this.sectionline.istotalnumbermodule(id)
}else{
return this.datatable.istotalnumbermodule(id)
}
},
getindex: function(){
return this.options.index;
},
getmodule: function(templatejsonid){
return this.all_templateid[templatejsonid];
},
get: function(templatejsonid){
return this.all_templateid[templatejsonid];
},
getattachmentsite: function(json, templatejsonid, sectionkey){
//确保site最长为64,否则后台会报错
var index = 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.datatable.json.id;
templateid = (templateid.length > maxlength) ? templateid.substr(templateid.length-maxlength, maxlength) : templateid;
return templateid sectionid basesite;
},
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.datatable.deleteattachment(d.id);
for( var i=0; i 0 )mjson = this.form._getdomjson(mnodes[0]);
}
if(thjson && mjson && this.isavaliablecolumn(thjson, mjson)){
this.columnjsonlist.push({
"thjson": thjson,
"title": th.get("text"),
"mjson" : mjson,
"available": true
})
}
}.bind(this));
},
getlineexportdata: function(line, index ){
var exportdata = [];
this.columnjsonlist.each(function (column) {
var module;
if( column.mjson && column.available ){
module = line.all_templateid[column.mjson.id];
}
if ( !module ) {
exportdata.push("");
}else{
var text;
if ( column.mjson.type === "label" && module.node) {
text = module.node.get("text");
}else{
text = module.getexceldata();
}
if( !text && o2.typeof(text) !== "number" ){
text = "";
}
exportdata.push( text );
}
}.bind(this));
return exportdata;
},
// getlineexportdata: function(line, index ){
// var exportdata = [];
// this.columnjsonlist.each(function (column) {
//
// var module;
// if( column.mjson && column.available ){
// module = line.all_templateid[column.mjson.id];
// }
// if ( !module ) {
// exportdata.push("");
// }else{
// var value = module.getdata();
// var text = "";
//
// if( value ){
// switch (column.mjson.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":
// text = value;
// break;
// case "calendar":
// text = value;
// break;
// case "elautocomplete":
// text = value;
// break;
// case "elcascader":
// if( typeof(value) === "text" )
// break;
// default:
// text = value;
// break;
// }
// } else if ( column.mjson.type === "label" && module.node) {
// text = module.node.get("text");
// }
//
// if( !text && o2.typeof(text) !== "number" ){
// text = "";
// }
//
// exportdata.push( text );
// }
// }.bind(this));
// return exportdata;
// },
isavaliablecolumn : function(thjson, mjson){
if (thjson && ( thjson.isshow === false || thjson.isimpexp === false ))return false; //隐藏列,不允许导入导出
if (mjson && (mjson.type == "sequence" || mjson.celltype == "sequence") )return false; //序号列
if (mjson && ["image","button","imageclipper","writingboard","attachment","attachmentdg","label",
"elbutton","elcarousel","eldropdown","elicon","eltree"].contains(mjson.type) )return false; //图片,附件,label列不导入导出
// if (type==="import" && module && ["label"].contains(module.json.type))return false; //label 不导入
return true;
},
getcolwidtharray : function(){
var colwidtharr = [];
this.columnjsonlist.each(function(c, index){
if ( c.available ) {
if (c.mjson && ["org","reader","author","personfield","orgfield"].contains(c.mjson.type)) {
colwidtharr.push(340);
} else if (c.mjson && c.mjson.type === "address") {
colwidtharr.push(170);
} else if (c.mjson && c.mjson.type === "textarea") {
colwidtharr.push(260);
} else if (c.mjson && c.mjson.type === "htmleditor") {
colwidtharr.push(500);
} else if (c.mjson && c.mjson.type === "tinymceeditor") {
colwidtharr.push(500);
} else if (c.mjson && c.mjson.type === "calendar") {
colwidtharr.push(150);
} else {
colwidtharr.push(150);
}
}
}.bind(this));
return colwidtharr;
},
getdateindexarray : function(){
var dateindexarr = []; //日期格式列下标
var idx=0;
this.columnjsonlist.each(function(c){
if ( c.available && c.mjson ) {
if(c.mjson.type === "calendar")dateindexarr.push(idx);
idx ;
}
}.bind(this));
return dateindexarr;
},
gettitlearray : function(){
var arr = [];
this.columnjsonlist.each(function(c, index){
if ( c.available && c.mjson )arr.push(c.title);
}.bind(this));
return arr;
},
getexcelname: function(){
var title;
if( this.datatable.json.excelname && this.datatable.json.excelname.code ){
title = this.form.macro.exec(this.datatable.json.excelname.code, this);
}else{
title = mwf.xapplication.process.xform.lp.datatableexportdefaultname;
}
var titlea = title.split(".");
if( ["xls","xlst"].contains( titlea[titlea.length-1].tolowercase() ) ){
titlea.splice( titlea.length-1 );
}
title = titlea.join(".");
return title;
},
exportwithimportdatatoexcel : function ( importeddata ) {
mwf.require("mwf.widget.mask", null, false);
this.mask = new mwf.widget.mask({ "style": "desktop", "zindex": 50000 });
// 适配移动端
if (layout.mobile) {
this.mask.load();
} else {
this.mask.loadnode(this.form.app.content);
}
this.datatable.fireevent("beforeexport");
this.getcolumnlist();
var resultarr = [];
var titlearr = this.gettitlearray("import");
titlearr.push( mwf.xapplication.process.xform.lp.validationinfor );
resultarr.push( titlearr );
importeddata.each( function( linedata, lineindex ){
var array = [];
this.columnjsonlist.each( function (obj, i) {
array.push( ( linedata[ obj.title ] || '' ).replace(/
/g, "\n") );
});
array.push( linedata.errortextlistexcel ? linedata.errortextlistexcel.join("\n") : "" );
resultarr.push( array );
}.bind(this));
var colwidtharr = this.getcolwidtharray();
colwidtharr.push( 300 ); //提示信息
var excelname = this.getexcelname();
var arg = {
data : resultarr,
colwidtharray : colwidtharr,
title : excelname,
witherror : true
};
this.datatable.fireevent("export", [arg]);
new mwf.xapplication.process.xform.datatablepc.excelutils( this.datatable ).exporttoexcel(
arg.data || resultarr,
arg.title || excelname,
arg.colwidtharray || colwidtharr,
this.getdateindexarray(), //日期格式列下标
null,
function () {
if (this.mask) {
this.mask.hide();
this.mask = null;
}
}.bind(this)
);
}
});
mwf.xapplication.process.xform.datatablepc.importer = new class({
implements: [options, events],
options: {
},
initialize: function (datatable, options) {
this.setoptions(options);
this.datatable = datatable;
this.form = this.datatable.form;
this.lp = mwf.xapplication.process.xform.lp;
this.columntext = this.lp.importvalidationcolumntext;
this.columntextexcel = this.lp.importvalidationcolumntextexcel;
this.excelutil = new mwf.xapplication.process.xform.datatablepc.excelutils( this.datatable );
this.columnjsonlist = [];
},
isavaliablecolumn : function(thjson, mjson){
if (thjson && ( thjson.isshow === false || thjson.isimpexp === false ))return false; //隐藏列,不允许导入导出
if (mjson && (mjson.type == "sequence" || mjson.celltype == "sequence") )return false; //序号列
if (mjson && ["image","button","imageclipper","writingboard","attachment","attachmentdg","label",
"elbutton","elbutton","elcarousel","eldropdown","elicon","eltree"].contains(mjson.type) )return false; //图片,附件,label列不导入导出
// if (type==="import" && module && ["label"].contains(module.json.type))return false; //label 不导入
return true;
},
importfromexcel : function () {
this.datatable.fireevent("beforeimport");
this.getcolumnlist();
var datecolarray = this.getdateindexarray(); //日期列
var orgtitlearray = this.getorgtitlearray();
this.excelutil.upload( datecolarray, function (data) {
mwf.require("mwf.widget.mask", null, false);
this.mask = new mwf.widget.mask({ "style": "desktop", "zindex": 50000 });
// 适配移动端
if (layout.mobile) {
this.mask.load();
} else {
this.mask.loadnode(this.form.app.content);
}
this.importeddata = data;
if( !this.checkcount() )return;
this.loadsimulatemodule();
this.columnjsonlist.each(function (c) {
c.module = this.importerline.getmodule(c.mjson.id)
}.bind(this));
if( orgtitlearray.length > 0 ){
this.listallorgdata( orgtitlearray, function () {
this.checkandimport();
}.bind(this));
}else{
this.checkandimport();
}
}.bind(this));
},
checkandimport: function () {
this.checkdata( function (flag) {
if( !flag ){
this.openerrordlg();
}else{
this.importdata()
}
this.destroysimulatemodule();
}.bind(this));
},
destroysimulatemodule: function(){
if( !this.importerdatatable ){
this.form.disallowsaving = false;
return;
}
this.importerdatatable.destroy();
this.importerdatatable = null;
this.form.disallowsaving = false;
},
loadsimulatemodule: function(){
this.form.disallowsaving = true;
this.importerdatatable = new mwf.xapplication.process.xform.datatablepc.importerdatabale( this.datatable );
this.importerdatatable.load();
this.importerline = this.importerdatatable.addline({});
},
getcolumnlist: function(){
this.columnjsonlist = [];
var ths = this.datatable.titletr.getelements("th.mwf_origional");
var tds = this.datatable.templatetr.getelements("td.mwf_origional");
var idx = 0;
ths.each(function(th, index){
var thjson = this.form._getdomjson( th );
var mjson;
if(tds[index]){
var mnodes = this.form._getmodulenodes(tds[index]); //获取总计列内的填写组件
if( mnodes.length > 0 )mjson = this.form._getdomjson(mnodes[0]);
}
if(thjson && mjson && this.isavaliablecolumn(thjson, mjson)){
this.columnjsonlist.push({
"thjson": thjson,
"title": th.get("text"),
"mjson" : mjson,
"field": mjson.id,
"index": idx,
// "module": this.importerline.getmodule(mjson.id)
// "module": this.simelatemodulemap[mjson.id]
});
idx ;
}
}.bind(this));
return this.columnjsonlist;
},
getdateindexarray : function(){
var dateindexarr = []; //日期格式列下标
var idx=0;
this.columnjsonlist.each(function(c){
if ( c.mjson && c.mjson.type === "calendar") {
dateindexarr.push(idx);
}
idx ;
}.bind(this));
return dateindexarr;
},
getorgtitlearray : function(){
var orgtitlearr = [];
this.columnjsonlist.each(function(c){
if ( c.mjson && ["org","reader","author","personfield","orgfield"].contains(c.mjson.type) ) {
orgtitlearr.push(c.title);
}
}.bind(this));
return orgtitlearr;
},
parseimporteddata: function(){
var data = [];
this.importeddata.each( function( ilinedata ){
var linedata = {};
this.columnjsonlist.each( function (obj, i) {
var index = obj.index;
var module = obj.module;
var json = obj.mjson;
var text = obj.title;
var d = ilinedata[text] || "";
var value;
if( d === "" || d === undefined || d === null ){
value = "";
}else{
switch (json.type) {
case "org":
case "reader":
case "author":
case "personfield":
case "orgfield":
var arr = this.stringtoarray(d);
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;
default:
value = d; //换行符
break;
}
}
linedata[ json.id ] = value;
}.bind(this));
data.push( linedata );
}.bind(this));
return data;
},
stringtoarray: function(string){
return string.replace(/
/g,",").split(/\s*,\s*/g ).filter(function(s){
return !!s;
});
},
importdata: function(){
var data = this.parseddata; //this.parseimporteddata(idata);
this.datatable.fireevent("import", [data] );
this.datatable.setdata( { "data" : data } );
this.datatable.fireevent("afterimport", [data] );
this.datatable.fireevent("change", [{lines: this.datatable.linelist, type : "import"}]);
if (this.mask) {
this.mask.hide();
this.mask = null;
}
this.form.notice( mwf.xapplication.process.xform.lp.importsuccess );
},
openerrordlg : function(){
var edata = this.importeddata;
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 "'" )
}
})
return arr.join(" ")
}
var htmlarray = [""];
var titlestyle = objecttostring(this.datatable.json.impexptabletitlestyles, "style");
htmlarray.push("");
this.columnjsonlist.each(function (obj, i) {
htmlarray.push( "" );
});
htmlarray.push("");
htmlarray.push("" );
var contentstyles = object.clone( this.datatable.json.impexptablecontentstyles );
if( !contentstyles[ "border-bottom" ] && !contentstyles[ "border" ] )contentstyles[ "border-bottom" ] = "1px solid #eee";
var contentstyle = objecttostring( object.merge( contentstyles, {"text-align":"left"}) , "style" );
edata.each( function( linedata, lineindex ){
htmlarray.push( "" );
this.columnjsonlist.each( function (obj, i) {
htmlarray.push( "" ); //换行符
});
htmlarray.push( "" );
htmlarray.push( "" );
}.bind(this));
htmlarray.push( "" obj.title " | " mwf.xapplication.process.xform.lp.validationinfor " |
---|
" ( linedata[ obj.title ] || '' ).replace(/
/g," ") " | " ( linedata.errortextlist ? linedata.errortextlist.join(" ") : "" ) " |
" );
var width = this.datatable.json.impexpdlgwidth || 1000;
var height = this.datatable.json.impexpdlgheight || 700;
width = width.toint();
height = height.toint();
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,
"width": width,
"height": height,
"buttonlist": [
{
"type": "exportwitherror",
"text": mwf.xapplication.process.xform.lp.datagridexport,
"action": function () { _self.exportwithimportdatatoexcel(edata); }
},
{
"type": "cancel",
"text": mwf.lp.process.button.cancel,
"action": function () { dlg.close(); }
}
],
"onpostclose": function(){
dlg = null;
}.bind(this)
});
if (this.mask) {
this.mask.hide();
this.mask = null;
}
},
checkcount: function(){
var idata = this.importeddata;
var lp = mwf.xapplication.process.xform.lp;
var exceeded = false;
var maxcount = this.datatable.json.maxcount ? this.datatable.json.maxcount.toint() : 0;
if( maxcount > 0 && idata.length > maxcount )exceeded = true;
var less = false;
var mincount = this.datatable.json.mincount ? this.datatable.json.mincount.toint() : 0;
if( mincount > 0 && idata.length < mincount) less = true;
if( exceeded ) {
var text = lp.importtoomanynotice.replace("{n1}", idata.length).replace("{n2}", this.datatable.json.maxcount);
this.form.notice(text, "error");
return false;
}
if( less ){
var text = lp.importtoofewnotice.replace("{n1}", idata.length).replace("{n2}", this.datatable.json.mincount );
this.form.notice(text,"error");
return false;
}
return true;
},
checkdata : function( callback){
this.parseddata = this.parseimporteddata();
this.isimportsuccess = true;
this.checklinedata(0, function () {
var arg = {
validted : this.isimportsuccess,
data : this.importeddata
};
this.datatable.fireevent( "validimport", [arg] );
callback( arg.validted )
}.bind(this));
},
checklinedata: function(lineindex, callback){
if( lineindex < this.importeddata.length ){
this._checklinedata(this.importeddata[lineindex], lineindex, function (flag) {
lineindex ;
if( !flag )this.isimportsuccess = false;
this.checklinedata(lineindex, callback);
}.bind(this));
}else{
if(callback)callback();
}
},
_checklinedata: function(linedata, lineindex, callback){
linedata.errortextlist = linedata.errortextlist || [];
linedata.errortextlistexcel = linedata.errortextlistexcel || [];
var parsedlinedata = (this.parseddata && this.parseddata[lineindex]) ? this.parseddata[lineindex] : [];
this.checkmoduledata(0, linedata, parsedlinedata, function () {
var flag = !linedata.errortextlist.length;
callback(flag);
});
},
checkmoduledata: function(index, linedata, parsedlinedata, callback){
if( index < this.columnjsonlist.length ){
var result = this._checkmoduledata(this.columnjsonlist[index], linedata, parsedlinedata);
promise.resolve(result).then(function (flag) {
index ;
this.checkmoduledata(index, linedata, parsedlinedata, callback);
}.bind(this))
}else{
if(callback)callback();
}
},
_checkmoduledata: function (columnjson, linedata, parsedlinedata) {
var index = columnjson.index;
var json = columnjson.mjson;
var module = columnjson.module;
var text = columnjson.title;
var colinfor = this.columntext.replace( "{n}", index 1 );
var colinforexcel = this.columntextexcel.replace( "{n}", this.excelutil.index2colname( index ) );
var d = linedata[text] || "";
var parsedd = parsedlinedata[json.id] || "";
var lp = this.lp;
var flag = true;
if(d){
switch (json && json.type) {
case "org":
case "reader":
case "author":
case "personfield":
case "orgfield":
var arr = this.stringtoarray(d);
arr.each( function(d, idx){
var obj = this.getorgdata( d );
if( obj.errortext ){
linedata.errortextlist.push( colinfor obj.errortext lp.fullstop );
linedata.errortextlistexcel.push( colinforexcel obj.errortext lp.fullstop );
flag = false;
}
}.bind(this));
break;
case "number":
case "currency":
case "elnumber":
if (isnan(d)){
linedata.errortextlist.push( colinfor d lp.notvalidnumber lp.fullstop );
linedata.errortextlistexcel.push( colinforexcel d lp.notvalidnumber lp.fullstop );
flag = false;
}
break;
case "calendar":
case "eldate":
case "eldatetime":
if( !( isnan(d) && !isnan(date.parse(d) ))){
linedata.errortextlist.push(colinfor d lp.notvaliddate lp.fullstop );
linedata.errortextlistexcel.push( colinforexcel d lp.notvaliddate lp.fullstop );
flag = false;
}
break;
default:
break;
}
}
if (module && module.setdata && json.type !== "address"){
var haserror = false;
if(["org","reader","author","personfield","orgfield"].contains(json.type)){
if(o2.typeof(parsedd)==="array" && parsedd.length){
haserror = parsedd.some(function (item) { return item.errortext; });
flag = false;
}
}
if(!haserror){
module.setexceldata(parsedd);
var ps = [];
if( module.moduleexcelag )ps.push( module.moduleexcelag );
if( module.modulevalueag && !ps.contains(module.modulevalueag) )ps.push( module.modulevalueag );
if( module.moduleselectag && !ps.contains(module.moduleselectag) )ps.push( module.moduleselectag );
return promise.all( ps ).then(function () {
var result = module.validationexcel();
if ( result && result.length ){
linedata.errortextlist.push(colinfor result.join("\n") );
linedata.errortextlistexcel.push( colinforexcel result.join("\n"));
flag = false;
}
parsedlinedata[json.id] = module.getdata();
return flag;
})
}
}
return flag
},
exportwithimportdatatoexcel: function(edata){
var exporter = new mwf.xapplication.process.xform.datatablepc.exporter(this.datatable);
exporter.exportwithimportdatatoexcel(edata)
},
getorgdata : function( str ){
str = str.trim();
var flag = str.substr(str.length-2, 2);
switch (flag.tolowercase()){
case "@i":
return this.identitymap[str] || {"errortext": str mwf.xapplication.process.xform.lp.notexistinsystem };
case "@p":
return this.personmap[str] || {"errortext": str mwf.xapplication.process.xform.lp.notexistinsystem };
case "@u":
return this.unitmap[str] || {"errortext": str mwf.xapplication.process.xform.lp.notexistinsystem };
case "@g":
return this.groupmap[str] || {"errortext": str mwf.xapplication.process.xform.lp.notexistinsystem };
default:
return this.identitymap[str] ||
this.personmap[str] ||
this.unitmap[str] ||
this.groupmap[str] ||
{"errortext": str mwf.xapplication.process.xform.lp.notexistinsystem };
}
},
listallorgdata : function (orgtitlelist, callback) {
var identitylist = [], personlist = [], unitlist = [], grouplist = [];
if( orgtitlelist.length > 0 ){
this.importeddata.each( function( linedata, lineindex ){
// if( lineindex === 0 )return;
orgtitlelist.each( function (title, index) {
if( !linedata[title] )return;
var arr = this.stringtoarray(linedata[title]);
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;
}
})
}.bind(this))
}.bind(this));
var identityloaded, personloaded, unitloaded, grouploaded;
var check = function () {
if( identityloaded && personloaded && unitloaded && grouploaded ){
if(callback)callback();
}
};
this.identitymap = {};
if( identitylist.length ){
identitylist = identitylist.unique();
o2.actions.load("x_organization_assemble_express").identityaction.listobject({ identitylist : identitylist }, function (json) {
json.data.each( function (d) { this.identitymap[ d.matchkey ] = d; }.bind(this));
identityloaded = true;
check();
}.bind(this))
}else{
identityloaded = true;
check();
}
this.personmap = {};
if( personlist.length ){
personlist = personlist.unique();
o2.actions.load("x_organization_assemble_express").personaction.listobject({ personlist : personlist }, function (json) {
json.data.each( function (d) { this.personmap[ d.matchkey ] = d; }.bind(this));
personloaded = true;
check();
}.bind(this))
}else{
personloaded = true;
check();
}
this.unitmap = {};
if( unitlist.length ){
unitlist = unitlist.unique();
o2.actions.load("x_organization_assemble_express").unitaction.listobject({ unitlist : unitlist }, function (json) {
json.data.each( function (d) { this.unitmap[ d.matchkey ] = d; }.bind(this));
unitloaded = true;
check();
}.bind(this))
}else{
unitloaded = true;
check();
}
this.groupmap = {};
if( grouplist.length ){
grouplist = grouplist.unique();
o2.actions.load("x_organization_assemble_express").groupaction.listobject({ grouplist : grouplist }, function (json) {
json.data.each( function (d) { this.groupmap[ d.matchkey ] = d; }.bind(this));
grouploaded = true;
check();
}.bind(this))
}else{
grouploaded = true;
check();
}
}
}
});
mwf.xdesktop.requireapp("template", "utils.excelutils", null, false);
mwf.xapplication.process.xform.datatablepc.excelutils = new class({
extends: mwf.xapplication.template.utils.excelutils
});